RStudio with python matplotlib graph

Can matplotlib Python code be used to draw graphs in RStudio?

eg. below the matplotlib python code:

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() 

The output schedule will be:

enter image description here

Then I need to write an R markdown to enable this code and automatically generate a graph after clicking a button.

+7
matplotlib rstudio
source share
2 answers

One possible solution is to save the graph as an image, then upload the file to a markdown.

 ### Call python code sample ```{r,engine='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) fig, ax = plt.subplots( nrows=1, ncols=1 ) ax.plot (X, Y+1, color='blue', alpha=1.00) ax.plot (X, Y-1, color='blue', alpha=1.00) #plt.show() fig.savefig('foo.png', bbox_inches='tight') print "finished" ``` Output image: ![output](foo.png) #### The End 

Output:

enter image description here

+5
source share
  • install.packages ('devtools') first, get the install_github function
  • install_github ("rstudio / reticulate") install the dev version of the mesh
  • in r markdown doc, use the code below to enable the function.

    ```{r setup, include=FALSE}
    library(knitr)
    library(reticulate)
    knitr::knit_engines$set(python = reticulate::eng_python)
    ```

Try it, you will get what you want, and you do not need to save the image.

Imgur

+4
source share

All Articles