20

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!

mjbeyeler
  • 443
  • 5
  • 15
  • 3
    Question worthy of bounty imo. – InfiniteFlash May 23 '18 at 15:01
  • 4
    can you please post some sample Python code that produces the plot in question? – user5359531 Jun 05 '18 at 15:45
  • 1
    This is python behaviour and not directly related to the RStudio IDE. I'm assuming you are using `matplotlib.pyplot`, which uses *Qt* to draw and the result is what is appearing in the popup window. You can read [here](https://stackoverflow.com/questions/28269157/plotting-in-a-non-blocking-way-with-matplotlib#33050617) and [here](https://stackoverflow.com/questions/458209/is-there-a-way-to-detach-matplotlib-plots-so-that-the-computation-can-continue) about the blocking behaviour and ways you may workaround this. – Kevin Arseneau Jun 06 '18 at 01:35

1 Answers1

23

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:

enter image description here

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.

Kevin Arseneau
  • 6,186
  • 1
  • 21
  • 40
  • Hi, thanks for your answer! That's exactly what I am doing now as well, except that instead of your approach with `knitr::include_graphics` I'm using `Output image: *new line + indent* ![output](pyplot.png)`, which makes the image appear a bit smaller, which is useful if the plotted image is large. Like this you can display many images and keep the report readable. – mjbeyeler Jun 07 '18 at 09:13
  • @Michael Do you think Kevin's answer sufficiently answers your question? Will give the bounty to him if it does (it looks good to me) – InfiniteFlash Jun 07 '18 at 16:51
  • 1
    Generally I think that it does, but unfortunately I'm not able to reproduce his minimal example. Maybe it is because I'm using Anaconda python? I always get the following popup error message: "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." (I have checked that Qt is installed on my Anaconda distribution). – mjbeyeler Jun 08 '18 at 10:51
  • 1
    @Michael, that error is caused by not finding *Qt* in your path (related to the Anaconda install on windows). I'll add a note in my answer. – Kevin Arseneau Jun 08 '18 at 11:12
  • @KevinArseneau I did exactly as you said, and now I'm getting a bit of a different error: https://imgur.com/a/2Fo96gF – mjbeyeler Jun 08 '18 at 11:38
  • @Michael, I'm afraid that troubleshooting your Anaconda distribution is outside the scope of my answer. – Kevin Arseneau Jun 08 '18 at 11:50
  • You're right. It really is an Anaconda-specific problem it seems. I tested your code on my regular Python distribution (which unfortunately I can't use for my project), and your code works. Als, your suggestion below for RStudio 1.2 is working. Thanks! – mjbeyeler Jun 08 '18 at 12:36
  • I marked the issue as solved, but if anyone here is using Anaconda and has an idea as to what might be causing these errors, please let me know. :) – mjbeyeler Jun 08 '18 at 13:46
  • 1
    @Michael I have the exact same problem with the "This application failed to start because .... application may fix this problem." issue. It happens whenever I knit a .rmd file with a python chunk. I'll probably tag you in the post or message you somehow to it. It'll be useful. Also, it looks like Kevin posted a potential solution. Will have to try it! – InfiniteFlash Jun 08 '18 at 14:35
  • Exactly, it seems to be a problem with knit! And the potential solution didn't work for me. – mjbeyeler Jun 08 '18 at 16:09
  • Thank you so much! Your solution is invaluable :) – Akira Mar 05 '20 at 19:09
  • You can create a system variable `QT_QPA_PLATFORM_PLUGIN_PATH` to fix the issue, too. Set the value as @KevinArseneau suggested above. – Jakub Małecki Aug 26 '20 at 13:37
  • How about when using plotly instead of matplotlib? How can plotly figure be shown inline? Fig.show() opens a new window? – rm1104 Dec 31 '21 at 19:17