R Markdown: How can I make RStudio display Python

2019-03-13 02:03发布

问题:

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!

回答1:

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.