Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphing matplotlib with Python code in a R Markdown document

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:

enter image description here

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

like image 805
beetlej Avatar asked Apr 05 '16 21:04

beetlej


People also ask

How do I add Python code to R Markdown?

To add a Python code chunk to an R Markdown document, you can use the chunk header ```{python} , e.g., ```{python} print("Hello Python!") ```

Is there an R Markdown for Python?

Overview. The reticulate package includes a Python engine for R Markdown that enables easy interoperability between Python and R chunks. Python chunks behave very similar to R chunks (including graphical output from matplotlib) and the two languages have full access each other's objects.


1 Answers

  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.

Imgur

like image 180
jtianling Avatar answered Sep 23 '22 02:09

jtianling