Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Code Chunk Graphs not showing up in R Markdown

I need to include Python code chunks in an R Markdown HTML. However, when I do so, the plot doesn't show up.

This is the code chunk I have which want to implement. I know this works in Python.

```{python, results='asis'}
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as rng
import matplotlib.cm as cm
from matplotlib.animation import FuncAnimation

radii=(rng.random(int(1e3))+1)**2
iota=2*np.pi*rng.random(int(1e3))
x_posit=np.sqrt(radii)*np.cos(iota)
y_posit=np.sqrt(radii)*np.sin(iota)
plt.plot(x_posit, y_posit, 'go')
```

I expect to get a plot like this

But instead I get this, that is no graph in the R markdown Document. I'm knitting to HTML

like image 477
thatch4 Avatar asked Oct 21 '25 16:10

thatch4


1 Answers

Install the library reticulate via install.packages("reticulate") and load this chunk before your code presented above:

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

```{python}
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as rng
import matplotlib.cm as cm
from matplotlib.animation import FuncAnimation

radii=(rng.random(int(1e3))+1)**2
iota=2*np.pi*rng.random(int(1e3))
x_posit=np.sqrt(radii)*np.cos(iota)
y_posit=np.sqrt(radii)*np.sin(iota)
plt.plot(x_posit, y_posit, 'go')

plt.show()
```

Note the plt.show() command.

This will produce your expected output!

enter image description here

like image 176
J_F Avatar answered Oct 23 '25 07:10

J_F