[R] xyplot for longitudinal data

hadley wickham h.wickham at gmail.com
Wed Jul 18 06:24:23 CEST 2007


On 7/18/07, Osman Al-Radi <osman.al.radi at gmail.com> wrote:
> Dear R-help subscribers,
>
> I use xyplot to plot longitudinal data as follows:
>
> score<-runif(100,-4,5)
> group<-sample(1:4,100,rep=T)
> subject<-rep(1:25,4)
> age<-rep(runif(4,1,40),25)
> df<-data.frame(score,group,age,subject)
>
> xyplot(score~age|group, group=subject,
> panel=function(...){
> panel.loess(...,lwd=4)
> panel.superpose(...)}
> ,data=df)
>
> this produced a plot with four panels one for each group, with unique
> plotting parameters for each subject.
>
> How can I create a create a plot with a single panel where all four groups
> are superimposed using different line colors and symbols for each group, but
> preserving the longitudinal nature of the data (i.e. one line per subject).
>

Another approach would be to use the ggplot2 package (http://had.co.nz/ggplot2):

library(ggplot2)
qplot(age, score, data=df, group = interaction(subject, group),
geom="line", colour=factor(group)) + geom_smooth(aes(group=group),
enp.target=2, size=4)

# This gives a smooth per group, if you want one over all smooth
# use the following instead
+ geom_smooth(aes(group=1), enp.target=2, size=4)

# You can have both by adding both geom_smooths on

Hadley



More information about the R-help mailing list