RPy

A simple and efficient access to R from Python

Sections
Exits
Acknowledgement
This site is hosted by

RPy (R from Python)


Plotting with RPy

RPy (rpy.sf.net) is a simple and easy-to-use Python interface for the R Programming Language.

The advantage to using RPy for plotting is that R is a high-quality environment for doing statistics and math work that comes with many, many, many plotting features. The disadvantage is that R is a large language with its own complexities. This page is a simple tutorial meant to get you to your first plot, and point you on your way towards your 2nd, 3rd, and Nth plots.

Getting started

To start, install RPy. (You'll probably need to install R, too.)

Now run Python, and enter the following code:

from rpy import *

x = range(0, 10)
y = [ 2*i for i in x ]

r.plot_default(x, y)
Assuming everything was installed correctly, and R can connect to your display (this could be tricky if you're using a remote Linux box from a Windows machine -- talk to your local Linux expert, or install R locally!) you should see a simple graph that plots x vs 2*x for x ranging from 0 to 9. This is what I see:

Getting moderately tricky

Let's plot multiple things, with lines, in different colors! (Exciting, ehh?)
from rpy import *
import math

x = range(0, 10)
y1 = [ 2*i for i in x ]
y2 = [ math.log(i+1) for i in x ]

r.plot_default(x, y1, col="blue", type="o")
r.points(x, y2, col="red", type="o")
You should see something like this:

Axis labels and titles

Finally, let's add some axis labels and a title.
from rpy import *
import math

x = range(0, 10)
y1 = [ 2*i for i in x ]
y2 = [ math.log(i+1) for i in x ]

r.plot_default(x, y1, col="blue", type="o")
r.points(x, y2, col="red", type="o")

xlabels = [ "#%d" % (i,) for i in x ]
r.axis(1, at = x, label=xlabels, lwd=1, cex_axis=1.15)
r.title("My Plot")

Outputting to a file

You can set things up to output to a file by putting either of these commands in front of the plot_default command:
outfile = "somefile.ps"
r.postscript(outfile, paper='letter')
or
outfile = "somefile.png"
r.bitmap(outfile, res=200)
The former writes a postscript file, and the latter writes a PNG file. Oh, and be sure to call r.dev_off before using the file -- that will flush any unwritten data.

The End

I'm afraid at this point we've exhausted my knowledge of R programming. The next place to go is the R-intro, a short and readable introduction to using R. You can skip right to the plotting section and use most of those commands directly from Python, as above.

Hope that helps!


Titus Brown titus@caltech.edu
News