[R] A beginner's question about ggplot

hadley wickham h.wickham at gmail.com
Fri May 1 19:49:26 CEST 2009


On Fri, May 1, 2009 at 12:22 PM, MUHC-Research
<villandl at dms.umontreal.ca> wrote:
>
> Dear R-users,
>
> I would have another question about the ggplot() function in the ggplot2
> package.
>
> All the examples I've read so far in the documentation make use of a single
> neatly formatted data.frame. However, sometimes, one may be interested in
> plotting on the same grid information or objects derived from two totally
> different datasets and customize both displays. I still cannot tell how this
> can be done using ggplot().
>
> Here's an example.
>
> ###############
> ## A very simple data.frame;
>
> my.data = data.frame(X1 =
> as.factor(rep(1:2,c(4,4))),X2=c(4,3,5,2,6,2,3,5),X3=c(1:3,2,2:4,5)) ;
>
> ## Let's say I want to add the X^2 line to the plot;
>
> squared = data.frame(X=1:12,Y=((1:12)/2)^2) ;
>
> ## A scatterplot for my.data ;
>
> p = ggplot(my.data,aes(x=X2,y=X3,group=X1)) ;
> p = p+geom_point(aes(colour=X1)) ;
>
> #############
>
> How can "squared" be added to the plot? At first, I used
>
> p+geom_line(data=squared,aes(x=X,y=Y,group=1,colour="green")) ;
>
> but the plotted line is always blue! In fact, I can replace colour by any
> character value and I will still get a blue line.

You have two alternatives:

p + geom_line(data=squared,aes(x=X,y=Y,group=1,colour="squared")) +
  labs(colour = "Dataset")

p + geom_line(data=squared,aes(x=X,y=Y,group=1), colour="green")

see section 4.5.2 of the book for details.

Hadley

-- 
http://had.co.nz/




More information about the R-help mailing list