[R] plot multiple data sets on same axis

Scott Lamb slamb at slamb.org
Sun Dec 30 23:11:46 CET 2007


I'm new to R and struggling to reproduce graphs I've made with gnuplot.
Example here:

    http://www.slamb.org/tmp/one-active.png

I have three different data sets plotted on the same axis. (I also have
a number of samples for each X value which I displayed with quartiles
rather than plotting every point; that will likely be the subject of my
next question.)

My attempts to do this in R: I've put the data into a frame with (x, y,
dataset) columns; dataset is a categorical variable. I can get a coplot
which sort of shows the information:

    attach(myframe)
    coplot(y ~ x | dataset)

but not on the same axis with a legend. I'd like to start by getting
that in a scatterplot form:

    # XXX: datasets hardcoded in here...
    # is split() supposed to do something similar to this?
    # or how do I get a list of datasets to feed into subset?
    myframe_a <- subset(myframe, dataset=='a')
    myframe_b <- subset(myframe, dataset=='b')
    ...

and then I can apparently plot one and add points from others to it:

    # XXX: more hardcoding...
    attach(myframe_a)
    plot(x, y, col='red')
    detach(myframe_a)
    attach(myframe_b)
    points(x, y, col='blue')
    detach(myframe_b)
    ...
    legend("topleft",
           legend=c("a", "b", ...),
           fill=c("red", "blue", ...))

but there are several things I don't like about this solution:

* there probably is an existing function which does this? I can't find it.

* obviously I don't want to duplicate code for each dataset. I'd rather
loop based on whatever datasets are in the frame, but I'm missing how to
do that here.

* points() appears to not alter xlim and ylim. Is there a convenient way
to autodetermine them based on all the points?

* I've hardcoded the colors. This is the sort of thing I'd rather leave
to an expert. (I.e. someone who has looked at colorblindness studies and
knows which colors are easiest to distinguish.)

Any ideas?

Cheers,
Scott



More information about the R-help mailing list