tags:

views:

349

answers:

1

Hi all,

I have 40 subjects, of two groups, over 15 weeks, with some measured variable (Y).

I wish to have a plot where: x = time, y = T, lines are by subjects and colours by groups.

I found it can be done like this:

TIME <- paste("week",5:20)
ID <- 1:40
GROUP <- sample(c("a","b"),length(ID), replace = T)
group.id <- data.frame(GROUP, ID)
a <- expand.grid(TIME, ID)
colnames(a) <-c("TIME", "ID")
group.id.time <- merge(a, group.id)
Y <- rnorm(dim(group.id.time)[1], mean = ifelse(group.id.time$GROUP =="a",1,3) )
DATA <- cbind(group.id.time, Y)
qplot(data = DATA,
        x=TIME, y=Y, 
        group=ID,       
        geom = c("line"),colour = GROUP) 

But now I wish to add to the plot something to show the difference between the two groups (for example, a trend line for each group, with some CI shadelines) - how can it be done?

I remember once seeing the ggplot2 can (easily) do this with geom_smooth, but I am missing something about how to make it work.

Also, I wondered at maybe having the lines be like a boxplot for each group (with a line for the different quantiles and fences and so on). But I imagine answering the first question would help me resolve the second.

Thanks.

+7  A: 
p <- ggplot(data=DATA, aes(x=TIME, y=Y, group=ID)) +
            geom_line(aes(colour=GROUP)) +
            geom_smooth(aes(group=GROUP))

geom_smooth plot

rcs
Thanks rcs. How do I change the shaded SE to be of 95% instead of 68% ?
Tal Galili
I would just note that the default smoothing intervals do not (to my knowledge) take into account any auto-correlation present within subject. Longitudinal data will almost certainly have a correlation structure. I really like this type of plot.
Ian Fellows
You can use `level` in `stat_smooth` (0.95 by default): `p+geom_smooth(level=0.95, aes(group=GROUP))`
rcs
That's great, thanks! Last question - where did you find that these are the parameters ?
Tal Galili
In the manual page of the corresponding stat (`geom_smooth` uses `stat_smooth` per default). http://had.co.nz/ggplot2/stat_smooth.html
rcs
Thanks rcs! I must have been mistaken; I thought the default confidence bands for geom_smooth() were set at 68% (+/- 1 sd). If you don't specify a level for geom_smooth(), does it just inherit the default level for the stat_smooth() that it's implicitly calling (viz. 95%)?
briandk