python - R Markdown : How can I make RStudio display Python plots inline instead of in new window?

标签 python r rstudio r-markdown

所以,我最近一直在广泛使用 R Markdown,我对它的功能非常满意。

但是,我在使用 python 绘图时遇到了问题。我有一大块 python 代码,我在 python 中绘制了多个图形。

当我使用 R 执行此操作时,RStudio 将并排内联显示在此 block 中生成的所有绘图。

不幸的是,当对一大块 python 代码执行相同操作时,RStudio 打开一个新窗口并在其中显示绘图,然后代码执行停止,直到我关闭该窗口,然后它绘制下一个数字,我必须再次关闭它,等等。

是否有可能强制 RStudio 将图形内联,然后继续执行代码? 提前感谢您的帮助!

最佳答案

为了扩展我之前的评论,我将详细说明一个完整的答案。当使用 matplotlib 时,绘图是使用 Qt 呈现的,这就是您会收到弹出窗口的原因。

如果我们使用 fig.savefig 而不是 pyplot.show 然后使用 pyplot.close 我们可以避免弹出窗口。这是一个最小的例子:

---
output: html_document
---

## Python *pyplot*

```{python pyplot, echo=FALSE}
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

fig.savefig("pyplot.png")
plt.close(fig)
```

```{r, echo=FALSE}
knitr::include_graphics("pyplot.png")
```

在没有任何进程中断的情况下产生以下结果:

enter image description here

来源:matplotlib.org

N.B. According the the release notes for RStudio v1.2.679-1 Preview, this version will show matplotlib plots emitted by Python chunks.

更新

使用上面提到的最新预览版本,更新 block 以使用 pyplot.show 现在将根据需要显示内联。

```{python pyplot, echo=FALSE}
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

plt.show()
```

对于 Anaconda 用户

如果您使用 Anaconda 作为您的 python 发行版,您可能会遇到这样的问题:由于缺少路径/环境变量的问题,无法从 RStudio 中找到 Qt

错误将类似于:

This application failed to start because it could not find or load the Qt platform plugin "windows" in "", Reinstalling the application may fix this problem.

快速修复是将以下内容添加到 python block 中以设置环境变量。

import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = '/path/to/Anaconda3/Library/plugins/platforms'

/path/to 替换为您的 Anaconda 发行版的相关位置。

关于python - R Markdown : How can I make RStudio display Python plots inline instead of in new window?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50352614/

相关文章:

python - 最简单的 python 相当于 R 的 grepl

r - 根据各种其他列值中的值创建新列 - 使用 R

r - 从 lapply 或带有 print 语句的函数调用时 kable 出现意外行为

python - 指定配置文件的最pythonic方法是什么?

r - 使用 R 应用 ifelse 而不应用 for 循环

r - 更改 rmarkdown pdf 输出的背景颜色

javascript - Plot.ly 在 R : Unwanted alphabetical sorting of x-axis

python - Shape Context Error 通过计算两个不同形状的距离

python - 将 Router 与 Django REST Framework 一起使用时,如何让 APIViews 和 ViewSets 显示在 API Root 上?

python - 使用字符串列表在文件中搜索多个字符串