Skip to content

Creating multiple graphs based on one variable

3 messages · Tim Clark, Stefan Grosse, Luc Villandre

#
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
#
On Tue, 26 May 2009 02:34:55 -0700 (PDT) Tim Clark
<mudiver1200 at yahoo.com> wrote:
TC> I would like separate plots for Tony, Mike, and Vicky.  What is the
TC> best way to do this?  

use the lattice package:

library(lattice)
xyplot(y~x|Name,data=dat)

Mr. Sarkar (the author of the package) has written an excellent book on
his package I recommend it.

hth
Stefan
#
Tim Clark wrote:
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:
Hope this helps,