maptlotlib plot causes knitting of .Rmd to get stuck

Dear Rstudio gurus,

I am running Rstudio on a windows 10 machine.

I have an .Rmd book which starts like this:

```{r setup, include=TRUE}

knitr::opts_chunk$set(echo = TRUE, error = TRUE)


```{r use_condaenv}


cat(" about to do py_discover_config()")

```{python import_os_tarfile_urllib_packages}

import os

print("print (done import os) do os.getcwd()")

print(os.getcwd() )

import tarfile

import urllib

import pandas as pd

print("done import_os_tarfile_urllib_packages")

import numpy as np

import matplotlib.pyplot as plt

Then there are Python and R code chunks to import and examine a data set from .csv

The there is this code chunk:

{python plot_histograms}

housing.hist(bins=50, figsize=(20,15))



If I run the code chunks one after another by clicking on the little green arrow, everything runs fine and I get the histogram oin the .Rmd file and as a png file. But inf I try to knit the .Rmd file, it gets hung up on the plot_histograms chunk.

Eventually I get two popups:

POP-UP 1: Rterm This application failed to start because no Qt plaform plugin could be initialized. Reinstallign the application may fix this problem

POP-UP 2: R for Windows terminal front end has stopped working

If I knit the same .Rmd but having commented out the plot_histograms chunk, it runs fine.

I found this: R Session Aborted on plot$plot(x,y)

Not sure if this is still the same problem.

Does this mean I should give up on matplotlib if I use Rstudio and reticulate?

Hi @studiosa,

It's hard to tell what the problem is here and help without being able to run the example myself. Can you provide a reproducible example that runs from start to finish?

Here's a great guide to creating a reproducible example:


Dear alexgold,

Thank you for looking into this.

Below is the entire .Rmd file.

It runs fine if I simply step through it chunk by chunk. It produces the histograms both via {python plot_histograms} and via {r r_ggpplot_histograms} chunks.

It also runs fine if I comment out the {python plot_histograms} chunk and then knit the .Rmd file. In this case it produces the histograms via {r r_ggpplot_histograms} chunk.

But if I try to knit the .Rmd file without commenting out the {python plot_histograms} chunk, then it gets stuck on running that chunk and eventually pops up an error message about Rterm application (failed to start).


title: "Chapter 2 ML A Geron book"
df_print: paged
chunk_output_type: inline

Load and histogram housing data chapt 2

Load the reticulate library after installing it (install.packages("reticulate"))

{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE, error = TRUE)



# getwd()

temp_start_systime = Sys.time()

# install.packages("reprex")
type or paste code here

cat(" about to do py_discover_config()")

Python chunks can be used in RMD files (;!!CQl3mcHX2A!SPizAgI9ndlZx-L7OiIgpkCdwKvK5IADaNZVv8CitZMAp-RT3JMJpcbkDVcCygVsYLI8AA$ )

import os
print("print (done import os) do os.getcwd()")
print(os.getcwd() )

import tarfile

import urllib

import pandas as pd
print("done import_os_tarfile_urllib_packages")

import numpy as np

import matplotlib.pyplot as plt


HOUSING_URL=  DOWNLOAD_ROOT + "datasets/housing/housing.tgz"

HOUSING_PATH = os.path.join("datasets", "housing")

# os.makedirs(HOUSING_PATH, exist_ok=False)
# FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'datasets\\housing

os.makedirs(HOUSING_PATH, exist_ok=True)
# Does not seem to create the directory anew 
# (does not delete already existing file in that directory)

print("\n os.getcwd() \n")
# print(os.getcwd())

tgz_path=os.path.join(HOUSING_PATH, "housing.tgz")
# print( "\n tgz_path\n",tgz_path)

urllib.request.urlretrieve(HOUSING_URL, tgz_path)

Unpack data via python

housing_tgz =
housing_tgz.extractall(path = HOUSING_PATH)

Load data via python

csv_path=csv_path = os.path.join(HOUSING_PATH, "housing.csv")

print("csv_path", csv_path)

housing = pd.read_csv(csv_path)



print("\n housing[ ocean_proximity ].value_counts() \n")
housing[ "ocean_proximity" ].value_counts()

print("\n housing.describe() \n")

print("\n housing[longitude].describe() \n")

print("\n housing[ocean_proximity].describe() \n")

# Try to do histograms in python
housing.hist(bins=50, figsize=(20,15))

housing.hist(bins=50, figsize=(10,15), color="red")

housing.hist(bins=50, figsize=(20,10), color="green")

# Runs fine when I run 1 chunk at a time, but causes R to get stuck
#If I try to knit the .Rmd 
# So Comment this out for now 

Us ggplot to plot histograms



housing_r = py$housing

housing_r %>%
  keep(is.numeric) %>% 
  gather() %>% 
  ggplot(aes(value)) +
    facet_wrap(~ key, scales = "free", ncol=2) +
    geom_histogram(color="green", fill="blue")

housing_r %>%
  keep(is.numeric) %>% 
  gather() %>% 
  ggplot(aes(value)) +
    facet_wrap(~ key, scales = "free", nrow=2) +

Hi @studiosa,

It looks like other people have run into this problem when using conda environments. There was a lively discussion on the RStudio github repo on this, and it seems that someone found a solution.

It looks like the short version is to add a line like

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.

For more information, it looks like there's a more thorough answer on the reticulate package github and on stack overflow.

It also looks like updating to a newer version of RStudio might fix the issue.

Hope that's helpful!

Dear alexkgold
It does not look like the instructions apply to my case

  1. I checked the version of Rstudio I have and compared it to what you have on the site. I think I have the latest:

Version 1.2.5033

© 2009-2019 RStudio, Inc.

"Orange Blossom" (330255dd, 2019-12-04)

  1. I searched my PC for “Anaconda3/Library” and also for “plugins/platforms” and did not find it.

I think I have miniconda and not Anaconda3.

I recall that when I was installing reticulate and various Python packages on my laptop, something was going wrong, and someone at Rstudio recommended that I use miniconda:. After that I was able to install Python packages, like keras, right from inside Rstudio using conda_install()

I found a folder C:\Users\userXYZ\AppData\Local\r-miniconda. It does not have plugins or platforms
Please see below for steps I followed to install miniconda and install a package using miniconda.

> install.packages("reticulate")
> install_miniconda()
Miniconda has been successfully installed at "C:/Users/userXYZ/AppData/Local/r-miniconda".
## python:         C:/Users/userXYZ/AppData/Local/r-miniconda/envs/r-reticulate/python.exe
## libpython:      C:/Users/userXYZ/AppData/Local/r-miniconda/envs/r-reticulate/python36.dll
## pythonhome:     C:/Users/userXYZ/AppData/Local/r-miniconda/envs/r-reticulate
## version:        3.6.7 (default, Dec  6 2019, 07:03:06) [MSC v.1900 64 bit (AMD64)]
## Architecture:   64bit
## numpy:          C:/Users/userXYZ/AppData/Local/r-miniconda/envs/r-reticulate/Lib/site-packages/numpy
## numpy_version:  1.17.4

## Tell reticulate to use the newly created environment
## New Python packages can be installed using conda_install()
conda_install(envname = "r-reticulate", packages = "keras")

## Successfully installs keras

Hi @studiosa,

What about this path?


1 Like

SUCCESS!! Thank you so much.
I am very impressed and grateful that you found the solution.

I plan to let others around me know (I am trying to promote the idea of using Python with R in the RStudio environment, rather than just Python via Anaconda3 )

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.