R Markdown: How to Make Rstudio Display Python Plots Inline Instead of in New Window

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

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:

Sample Image

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.

Does Rmarkdown allow knitting of matplotlib plots? If so, will you help me troubleshoot?

I found an answer here by Kevin Arseneau. Plot Python Plots Inline

I would not call this a duplicate because the problem was different, but the solution worked for both problems.

What is needed is to add the following code:

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

Here is my updated working code. It is similar to original question and updated with a python chunk for imports that Bryan suggested.

---
title: "Python Plot"
output: html_document
---

```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(echo = TRUE)
library(reticulate) #Allows for Python to be run in chunks
```

```{python import}
import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = '/path/to/Anaconda3/Library/plugins/platforms'
import numpy as np
import matplotlib.pyplot as plt

```{python, eval=TRUE}

trees = np.array(r.trees) #Imported an internal R dataset. It got rid of headers and first row. Don't know how to deal with that right now.
type(trees)
np.shape(trees)
print(trees[1:6,:])

plt.plot(trees[:,0], trees[:,1])
plt.show()
plt.clf() #Reset plot surface
```

Make R Studio plots only show up in new window

The dev.new() function will open a new plot window, which then becomes the target for all plots.

If you wish to open another window you can run the command a second time to open a second window.

dev.off() will shut down the window (in the order they were opened by default).

You can see how to control multiple graphics devices in the documentation here.

Unable to Knit To PDF the R-notebook containing Python code

I have found the answer for my question at https://stackoverflow.com/a/50711837/7357673. I posted it here to close this question and for future visitors.

How can I view Python objects created in a RMardown session in RStudio Environment window?

In any chunk that assigns to a Python variable b, follow that assignment with a command like r.b = b. Then b and its value will appear in the Environment window.

r. is the converse of py$; it lets the Python chunk access the R namespace.

Reference: https://blog.rstudio.com/2018/03/26/reticulate-r-interface-to-python/


Edit: to be more concise, you could chain the assignment:
r.b = b = [1,2,3,4,5]

Not completely sure it's wise, though. The whole thing about Python chain assignments going left-to-right (see, e.g., https://stackoverflow.com/a/36346517) freaks me out. The point made there about two Python variables pointing to the same object should be kept in mind, although as far as I can tell, assigning a new value to b in an R chunk doesn't change the value of py$b.



Related Topics



Leave a reply



Submit