2

I am unable to import matplotlib.pyplot as plt in Rstudio.

I tried the solutions already available on SO.

Here are my attempts:

I installed reticulate package the devtools install way. devtools::install_github(rstudio/reticulate)

library(reticulate)

repl_python()

import matplotlib.pyplot as plt

import numpy as np

x = np.linspace(0,10, 100) plt.plot(x, x, label = "linear") plt.legend() plt.show()

I received the following error - RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa ImportError: numpy.core.multiarray failed to import

I tried in RMarkdown as well.

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(reticulate)
use_condaenv(condaenv = "python36", conda = "auto", required = FALSE)
```

```{python}
repl_python()
import numpy as np
import matplotlib.pyplot as plt

n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)

plt.plot (X, Y+1, color='blue', alpha=1.00)
plt.plot (X, Y-1, color='blue', alpha=1.00)
plt.show()
```

Received the following error -

RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa Traceback (most recent call last): File "C:\Users\Vidhya\AppData\Local\Temp\Rtmp6vCzV6\chunk-code-13e83c491e61.txt", line 2, in <module> import matplotlib.pyplot as plt File "C:\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 29, in <module> import matplotlib.colorbar File "C:\Anaconda3\lib\site-packages\matplotlib\colorbar.py", line 32, in <module> import matplotlib.artist as martist File "C:\Anaconda3\lib\site-packages\matplotlib\artist.py", line 15, in <module> from .transforms import (Bbox, IdentityTransform, TransformedBbox, File "C:\Anaconda3\lib\site-packages\matplotlib\transforms.py", line 39, in <module> from matplotlib._path import (affine_transform, count_bboxes_overlapping_bbox, ImportError: numpy.core.multiarray failed to import

Mr. T
  • 11,960
  • 10
  • 32
  • 54
Naive_Natural2511
  • 687
  • 2
  • 8
  • 20

2 Answers2

2

I had similar issues. I did following and it solved. Before that I would like to refer you in following threads from where I got the solution...

Qt platform plugin issue Rstudio

PyQt5 - Failed to load platform plugin "windows". Available platforms are: windows, minimal

Here is what you have to do [change the path according to your system]

In R:-

py_run_string("import os as os")
py_run_string("os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'C:/Dev/Anaconda/Library/plugins/platforms'")
np <- import("numpy", as = "np")
plt <- import("matplotlib.pyplot", as = "plt")

x <- np$linspace(0,10, 100)
plt$plot(x, x, label = "linear")
plt$legend()
plt$show()

In repl_python (embedded mode)

import matplotlib.pyplot as plt

import numpy as np

x = np.linspace(0,10, 100)
plt.plot(x, x, label = "linear")
plt.legend()
plt.show()

Hope this helps... cheers

Indranil Gayen
  • 702
  • 1
  • 4
  • 17
0

I wanted to throw my solution into the pile if anyone is still having issues with this like I was. My issue was that the line "import matplotlib.pyplot as plt" in my_python_code.py was rejected by reticulate with the error message:

reticulate::source_python('~/my_python_code.py')

Error in py_run_file_impl(file, local, convert) :

ModuleNotFoundError: No module named 'matplotlib.pyplot'; 'matplotlib' is not a package

Run reticulate::py_last_error() for details.

This was causing the code not to run and plots not to show up in the plot viewer making RStduio useless as a Python IDE.

There are lots of places that talk about this with no clear reason why "import matplotlib.pyplt as plt" in my_python_code.py gets the error message. I can go to my virtual environment and clearly see that matplotlib is there.

My solution was to execute the following R script before running my Python code. Here is the R script that sets up the environment:

library(reticulate)
use_virtualenv(virtualenv = "/path/to/my/env", required = TRUE)
reticulate::py_run_string("import matplotlib.pyplot as plt") 

To test this you can do the following code:

library(reticulate)
use_virtualenv(virtualenv = "/path/to/my/env", required = TRUE)
reticulate::py_run_string("import matplotlib.pyplot as plt") 
reticulate::py_run_file("my_python_code.py")

which works just fine. Now do the following which gives the error message again:

library(reticulate)
use_virtualenv(virtualenv = "/path/to/my/env", required = TRUE)
# reticulate::py_run_string("import matplotlib.pyplot as plt") 
reticulate::py_run_file("my_python_code.py")

Note that reticulate::py_run_string("import matplotlib.pyplot as plt") has been commented out. So for some reason the import command for matplotlib needs to be run twice. Once outside of the Python script and then again inside the Python script as usual.

Also, to be clear, the first two lines only set up reticulate to point to a specific Python virtual environment. There are different ways to do this per the reticulate documentation. This method allows me to point to different virtual environments as needed.

I run this script before I run my Python code, and now my plots show up in the RStudio plot viewer just like they do for my R code.

Finally, does anyone know why this is? This seems strange since other Python libraries like NumPy don't need to be dealt with this way.

Dennis
  • 189
  • 1
  • 3