且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R Markdown:如何让 RStudio 内联显示 Python 图而不是在新窗口中显示?

更新时间:2023-02-25 14:52:21

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

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

---输出:html_document---## Python *pyplot*```{python pyplot,回声=假}导入 matplotlib导入 matplotlib.pyplot 作为 plt将 numpy 导入为 npt = np.arange(0.0, 2.0, 0.01)s = 1 + np.sin(2 * np.pi * t)图, ax = plt.subplots()ax.plot(t, s)ax.set(xlabel='time (s)', ylabel='电压 (mV)',title='关于尽可能简单,伙计们')ax.grid()fig.savefig("pyplot.png")plt.close(图)`````{r, echo=FALSE}knitr::include_graphics("pyplot.png")``

在没有任何过程中断的情况下产生以下内容:

来源:matplotlib.org

注意根据发行说明 对于 RStudio v1.2.679-1 预览版,此版本将显示由 Python 块发出的 matplotlib 图.

更新

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

```{python pyplot, echo=FALSE}导入 matplotlib导入 matplotlib.pyplot 作为 plt将 numpy 导入为 npt = np.arange(0.0, 2.0, 0.01)s = 1 + np.sin(2 * np.pi * t)图, ax = plt.subplots()ax.plot(t, s)ax.set(xlabel='time (s)', ylabel='电压 (mV)',title='关于尽可能简单,伙计们')ax.grid()plt.show()``

对于 Anaconda 用户

如果您使用 Anaconda 作为您的 Python 发行版,您可能会遇到一个问题,即由于缺少路径/环境变量的问题,在 RStudio 中找不到 Qt.>

错误将类似于:

此应用程序无法启动,因为它无法在"中找到或加载 Qt 平台插件windows",重新安装应用程序可能会解决此问题.

快速解决方法是将以下内容添加到 python 块中以设置环境变量.

导入操作系统os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = '/path/to/Anaconda3/Library/plugins/platforms'

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

So, I've been using R Markdown extensively lastly, and I'm pretty satisfied with what it can do.

However, I'm having a problem with python plots. I have a chunk of python code where I plot multiple figures in python.

When I do that with R, RStudio will display all the plots generated in this chunk side by side inline.

Unfortunately, when doing the same with a chunk of python code, RStudio opens a new Window where it displays the plot, then the code execution is halted until I close that window, then it plots the next figure, I have to close it again, etc etc.

Is there a possibility to force RStudio to put the figures inline, and then continue code execution? Thanks for your help in advance!

To expand on my earlier comment, I will elaborate with a complete answer. When using matplotlib, the plots are rendered using Qt, which is why you are getting popup windows.

If we use fig.savefig instead of pyplot.show and then pyplot.close we can avoid the popup windows. Here is a minimal example:

---
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")
```

Which produces the following without any process interruption:

Source: 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.

Update

Using the latest preview release mentioned above, updating the chunk to use pyplot.show will now display inline as desired.

```{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()
```

For Anaconda users

If you use Anaconda as your python distribution, you may experience a problem where Qt is not found from RStudio due to problem with missing path/environment variable.

The error will appear similar to:

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.

A quick fix is to add the following to a python chunk to setup an environment variable.

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

Replacing /path/to with the relevant location to your Anaconda distribution.