Using reticulate: troubleshooting tips

reticulate is a R package by RStudio to allow seamless use of python codes in R. Although it works nicely, you may encounter some common issues when setting it up, especially when doing so on a virtual machine.

(1) Sourcing python

The very first thing is to check python is properly installed.

py_discover_config()

If libpython is missing, do this:

$ sudo apt-get install -y r-base python3 python3-dev python3-pip python3-ven python3-tk

(2) Installing packages

use_python("/usr/bin/python3.5") # point this to where your python executable is

You can create a virtual environment to install packages, say it's called "python_environment"

virtualenv_create("python_environment") # create a virtual environment for reticulate

Then you can installed packages

virtualenv_install("python_environment", "matplotlib")

You may also want to check what virtual environments are there, and the path to a particular environment.

virtualenv_list()
virtualenv_python('python_environment')

To use a environment in your code, include use_virtualenv("python_environment",required = T)

(3) Matplotlib

Unfortunately, not all Matplotlib backends work for reticulate. Make sure you put plt.switch_backend('agg') in your python code.

When using this backend, some programs may be missing. You need to install them in the terminal.

$ sudo apt install texlive-fonts-recommended texlive-fonts-extra
$ sudo apt-get install dvipng

https://github.com/rstudio/reticulate/issues/470 https://stackoverflow.com/questions/54477891/filenotfounderror-errno-2-no-such-file-or-directory-latex-latex-python

Checking if everything works

After loading reticulate in R, try running below after typing repl_python(), or as a python code chunk in a R markdown document.

```{python}
use_python("/usr/bin/python3.5") # point this to where your python executable is
use_virtualenv("python_environment",required = T)
import numpy as np
import matplotlib.pyplot as plt
plt.switch_backend('agg')
t = np.arange(0.0,2.0,0.01)
s = 1+np.sin(2*np.pi*t)
plt.plot(t,s)
plt.show()
space-1.jpg

*Centered text*

Little red riding hood

1 / 3
Caption Text
2 / 3
Caption Two
3 / 3
Caption Three


Go Top