[R] Creating multiple graphs based on one variable

Luc Villandre villandl at dms.umontreal.ca
Tue May 26 16:01:44 CEST 2009


Tim Clark wrote:
> Dear List,
>
> I would like to create several graphs of similar data.  I have x and y values for several different individuals (in this case fish).  I would like to plot the x and y values for each fish separately.  I can do it using a for loop, but I think I should be using "apply".  Please let me know what I am doing wrong, or if there is a "better" way to do this.  What I have is:
>
> #Test data
> dat<-data.frame(c(rep(1:10,4)),c(rep(1:10,4)),c(rep(c("Tony","Mike","Vicky","Fred"),each=10)))
> names(dat)<-c("x","y","Name") 
>
> #Create function to plot x and y
> myplot<-function() plot(dat$x,dat$y)
>
> #Apply the function to each of the names
> par(mfcol=c(2,2))   
> apply(dat,2,myplot,by=dat$Name) #Does not work - tried various versions
>
> I would like separate plots for Tony, Mike, and Vicky.  What is the best way to do this?  
>
> Thank!
>
> Tim
>
>
> Tim Clark
> Department of Zoology 
> University of Hawaii
>
> ______________________________________________
> 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.
>   

Hi Tim,

I'm now rather fond of Hadley Wickham's ggplot2 package. Its structure 
is most of the times intuitive and it does yield nice-looking output.

In order to solve your problem, taking advantage of the ggplot2 
framework, you can simply use the following:
> library(ggplot2) ;
> ## If you want all the curves to be on the same plotting grid ;
>
> p <- ggplot(dat, aes(x=x,y=y, group=Name)) ;
> p + geom_line(aes(colour=Name)) ; ## Only one curve will be visible 
> since they are all superposed.
>
> ## If you want the curves to be on separate plotting grids ;
>
> p <- ggplot(dat, aes(x=x,y=y, group=Name)) ;
> p <- p + geom_line(aes(colour=Name)) ;
> p+facet_grid(. ~ Name) ;
Hope this helps,
-- 
*Luc Villandré*
/Biostatistician
McGill University Health Center -
Montreal Children's Hospital Research Institute/




More information about the R-help mailing list