[R] How to plot multiple data sets with different colors (also with legend)?

Ista Zahn istazahn at gmail.com
Mon Oct 19 05:24:04 CEST 2009


Hi Peng,
Comments below.

On Sun, Oct 18, 2009 at 9:22 PM, Peng Yu <pengyu.ut at gmail.com> wrote:
> On Sun, Oct 18, 2009 at 5:42 PM, Matthieu Dubois <matthdub at gmail.com> wrote:
>> Hi,
>>
>> the blue point is not shown simply because it is printed outside
>> the current plot area. If you want to use the base graphics, you
>> have to manually define the xlim and ylim of the plot. Legend is added
>> with the command "legend".
>>
>> E.g.
>> x=rbind(c(10,11),c(10,11))
>> y=cbind(-1:0,-1:0)
>> plot(y,col='yellow', xlim=c(-1,11), ylim=c(-1,11))
>> points(x,col='blue')
>> legend("topleft", c("x","y"), col=c('blue', 'yellow'), pch=1)
>>
>> This is nevertheless most easily done in ggplot2.
>> E.g.
>> library(ggplot2)
>> # put the whole data in a data frame
>> # and add a new variable to distinguish both
>> dat <- data.frame(rbind(x,y), var=rep(c('x','y'), each=2))
>> qplot(x=X1,y=X2, colour=var, data=dat)
>
> qplot generates a figure with some background grid. If I just want a
> blank background (as in plot), what options should I specify? How to
> specific the color like 'red' and 'blue' explicitly?
>

You can get a more traditional look by issuing

theme_set(theme_bw())

before the call to qplot(). The colors are controlled by the a scale,
which you can override as follows:

qplot(x=X1,y=X2, colour=var, data=dat) + scale_colour_manual(values =
c("red","green"))

> I have read the review for ggplot2 book on amazon. The rates are
> unanimously high. I want to know how much effort I should spend to
> learn ggplot2 versus conventional graphics R packages. Can ggplot2 do
> all the graphics tasks? Is it much easier to learn than conventional
> graphics packages?

ggplot2 can do most things that can be done in base graphics. It makes
many things that are difficult in base easy, like faceting and mapping
variables to a wide variety of scales. I myself use ggplot2 almost
exclusively. I don't know base graphics at all, and I'm able to
accomplish all my graphing needs with ggplot2. I would not say its
easier than base graphics, just different. Some things are easier with
base graphics, other things are easier with ggplot. I use it because I
like the consistent and rational user interface (and the default theme
is nice to look at).

The place to start learning ggplot2 (while your're waiting for the
book to be shipped perhaps) is http://had.co.nz/ggplot2/.

-Ista
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Ista Zahn
Graduate student
University of Rochester
Department of Clinical and Social Psychology
http://yourpsyche.org




More information about the R-help mailing list