Graphing matplotlib with Python code in a R Markdo

2019-04-21 16:13发布

问题:

Is it possible to use Python matplotlib code to draw graph in RStudio?

e.g. below Python matplotlib 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()

Output graph will be:

Then I need to write a R Markdown to include these code and generate graph automatically after knitting the markdown.

回答1:

One possible solution is save the plot as a image, then load the file to 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:



回答2:

  1. install.packages('devtools') first, get install_github function
  2. install_github("rstudio/reticulate") install the dev version of reticulate
  3. in r markdown doc, use 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 don't need to save any image.



回答3:

You can do that with reticulate, but most time in trying to follow a tutorial in doing that you may encounter some technicalities that weren't sufficiently explained.

My answer is a little late but I hope it's a thorough walkthrough of doing it the right way - not rendering it and then loading it as a png but have the python code executed more "natively".

Step 1: Configure Python from RStudio

You want to insert an R chunk, and run the following code to configure the path to the version of Python you want to use. The default python that comes shipped with most OS is usually the outdated python 2 and is not where you install your packages. That is the reason why it's important to do this, to make sure Rstudio will use the specified python instance where your matplotlib library (and the other libraries you will be using for that project) can be found:

library(reticulate)
# change the following to point to the desired path on your system
use_python('/Users/Samuel/anaconda3/bin/python')
# prints the python configuration
py_config()

You should expect to see that your session is configured with the settings you specified:

python:         /Users/Samuel/anaconda3/bin/python
libpython:      /Users/Samuel/anaconda3/lib/libpython3.6m.dylib
pythonhome:     /Users/Samuel/anaconda3:/Users/Samuel/anaconda3
version:        3.6.3 |Anaconda custom (64-bit)| (default, Oct  6 2017, 12:04:38)  [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]
numpy:          /Users/Samuel/anaconda3/lib/python3.6/site-packages/numpy
numpy_version:  1.15.2

python versions found: 
 /Users/Samuel/anaconda3/bin/python
 /usr/bin/python
 /usr/local/bin/python
 /usr/local/bin/python3
 /Users/Samuel/.virtualenvs/r-tensorflow/bin/python

Step 2: The familiar plt.show

Add a Python chunk (not R!) in your R Markdown document (see attached screenshot) and you can now write native Python code. This means that the familiar plt.show() and plt.imshow() will work without any extra work. It will be rendered and can be compiled into HTML / PDF using knitr.

This will work:

plt.imshow(my_image, cmap='gray') 

Or a more elaborated example:

import numpy as np
import matplotlib.pyplot as plt
import os
import cv2

DATADIR = '/Users/Samuel/Datasets/PetImages'
CATEGORIES = ['Dog', 'Cat']

for category in CATEGORIES:
    path = os.path.join(DATADIR, category) # path to cat or dog dir
    for img in os.listdir(path):
        img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
        plt.imshow(img_array, cmap='gray')
        plt.show()
        break
    break

Output:

Step 3: Knit to HTML / PDF / Word etc

Proceed to knit as usual. The end product is a beautifully formatted document done in Python code using R Markdown. RStudio has come a long way and I'm surprised the level of support it has for Python code isn't more known so hoping anyone that stumbled upon this answer will find it informative and learned something new.