简体   繁体   English

Python 代码块图未显示在 R Markdown 中

[英]Python Code Chunk Graphs not showing up in R Markdown

I need to include Python code chunks in an R Markdown HTML.我需要在 R Markdown HTML 中包含 Python 代码块。 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 中有效。

```{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.但是我得到了这个,这不是 R markdown 文档中的图表。 I'm knitting to HTML我正在编织 HTML

Install the library reticulate via install.packages("reticulate") and load this chunk before your code presented above:通过install.packages("reticulate")安装库reticulate并在上面显示的代码之前加载这个块:

```{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.注意plt.show()命令。

This will produce your expected output!这将产生您预期的输出!

在此处输入图片说明

Exactly how J_F above described.上面 J_F 究竟是如何描述的。 Just as a reminder: In case you have more than one Python version on your system eg Mac with Python 2.7 and 3.x.提醒一下:如果您的系统上有多个 Python 版本,例如带有 Python 2.7 和 3.x 的 Mac。

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

```{python3}
enter code here
```

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM