R and 3D plots

From IridiaWiki
Jump to: navigation, search

The R Project for Statistical Computing is a convenient tool for plotting experimental data. If you are using Debian, you can find the R core .deb package, otherwise you can download the R source code and compile it yourself.


Basics

Starting R: Once R is installed you start it by typing R. This will give you an R prompt.

Quitting R: q()

HTML help: help.start()

Searching online help: help.search("what you don't know")

Assignment: variable <- value, eg. x <- 42

Show content of a variable: variable, eg. x

Loading data from a file: read.table("filename") (assuming that your data file contains data only, where each line describes one point in a multi-dimensional space).

Loading data from a file into a variable: xyz <- read.table("filename") (you knew that!)

3D Plots

In order to plot in 3D you need to add a package called scatterplot3d to R. You should download scatterplot3d package from one of the CRAN mirrors and leave it as a .tar.gz file. Then as root type the following from command-line:

# R CMD INSTALL scatterplot3D_version.tar.gz

Now, to use the package you start R and type:

> library(scatterplot3d)

In order to load the package. Hereafter, you can use the function scatterplot3d(). Assume that you have a file in the following format:

# an example file for 3D plots with R and scatterplot3d
x1 y1 z1
x2 y2 z2
x3 y3 z3
..
..

To do the plot the following sequence of commands will do the trick:

# R
> library(scatterplot3d)
> xyz <- read.table("examplefile.data")
> scatterplot3d(xyz)
> xyz
x1 y1 z1
x2 y2 z2
x3 y3 z3


Assuming everything looks good and you want to save the plot:

> postscript("greatlookinggraph.eps")
> scatterplot3d(xyz)
> dev.off()
> q()

The command dev.off() turns off the postscript device and flushes unwritten data. There are multiple devices, the default on UNIX is the x11 device, which produces nice windows. A device is started and set to the default graphical output device by simply typing the name of the device followed by brackets. Remember to issue a dev.off() when you are done with a device. A list of available devices is shown if you type help(Devices) -- lookout by the way R is case-sensitive hence, help(devices) will leave you with nothing but an error message.

Use help(scatterplot3d) to get the full list of parameters and options for the function.


3D and colors

Replace the scatterplot3d parameters with the following in order to get (nicer) colorful 3D plots:

scatterplot3d(xyz, highlight.3d=TRUE, col.axis="blue", col.grid="lightblue", main="scatterplot3d", pch=20)
Personal tools