Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding trend lines/boxplots (by group) in ggplot2

Tags:

plot

r

ggplot2

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.

like image 245
Tal Galili Avatar asked May 03 '10 20:05

Tal Galili


1 Answers

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

geom_smooth plot http://img143.imageshack.us/img143/7678/geomsmooth.png

like image 196
rcs Avatar answered Oct 20 '22 09:10

rcs