|
A simple and efficient access to R from Python |
|
Plotting with RPyThe 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 startedTo start, install RPy. (You'll probably need to install R, too.)Now run Python, and enter the following code: 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:from rpy import * x = range(0, 10) y = [ 2*i for i in x ] r.plot_default(x, y)
Getting moderately trickyLet's plot multiple things, with lines, in different colors! (Exciting, ehh?)You should see something like this: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")
Axis labels and titlesFinally, let's add some axis labels and a title.
Outputting to a fileYou 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 EndI'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 |
|