Matti Pastell
I often use Python and matplotlib for exploring measurement data (from e.g. accelerometers), even if I use R for the actual analysis. The reason is that I like to be able to flexibly zoom into different parts of the plot using the mouse and this works well for me with matplotlib. So I decided to try to call matplotlib from R using Rcpp and Python/C API.
It was surprisingly simple to get it working and I put together a small R-package Rpyplot. The package seems to work well on Ubuntu and Windows 7 for my use cases.
A lot of the code is based on the informative Call Python from R through Rcpp post in Rcpp gallery. I decided not use Boost.Python to make compiling on Windows simpler.
This post explains how I implemented the package and hopefully it will also allow others to expand the package for their needs. If you do implement additional functionality for Rpyplot I’d appreaciate a pull request on Github.
You’ll need to have Python in your path and Python headers and matplotlib
installed (id sudo apt-get install python-dev python-matplotlib
in
Ubuntu). In Windows I have used the
Anaconda Python distribution.
The following sets the compiler flags for Ubuntu:
You can have a look at the Makevars.win in Rpyplot-package to see how to set the flags for Windows.
The snippet below contains code required to initialize Python and imports pyplot from matplotlib and pyrun
function that can be used to call Python from R. All code executed with pyrun
(or PyRun_SimpleString
in C++) runs Python source code in the scope of __main__
module.
It is not enough to be able to just run Python commands from strings, but we also need to pass data from R to Python. The numvec_to_python
function below copies a numeric vector from R to a Python list and adds it to Python’s __main__
module. It is then accessible to Python commands executed with pyrun
.
Using the functions defined above makes calling matplotlib simple. First you
will need to copy a vector to Python and then you are able to plot it running
Python commands using pyrun
. You can see how different plots are created in
Rpyplot by looking at Plot.R. The implemenation
of pycontourf
function also shows how to copy an R matrix to Python and
convert it to a NumPy array.
Here is a small example on how the above functions can be used to create two
line plots. You’ll need to call plt.show()
in order to open the plot, but
when you do the program will hang until all opened figure windows are closed
so make sure to only call it at the end of a script.
And here is the generated plot:
tags: python
Tweet