Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faceted time series with mean profile in ggplot2

Using the following simulated time series:

n=70
m1 = matrix(rnorm(n), ncol=7)
m2 = matrix(rnorm(n, 0,4), ncol=7)
d = data.frame(rbind(m1,m2), cl=rep(c(1,2), each=5))

(first 7 columns represent the time point, last column the class)

Is it possible to construct a faceted time series that includes the mean curve in each plot, using ggplot2?

The results should look something like this:plot with mean curves

like image 338
user680111 Avatar asked Apr 03 '12 19:04

user680111


1 Answers

It might not be the most beautiful code, but I believe it gets you what you are looking for,

n=70
m1 = matrix(rnorm(n), ncol=7)
m2 = matrix(rnorm(n, 0,4), ncol=7)
d = data.frame(rbind(m1,m2), cl=rep(c(1,2), each=5))

d <- cbind(paste("d", 1:NROW(d), sep = ""), d)
names(d)[1] <- "id.var"

library(reshape)
longDF <- melt(d, id=c("cl", "id.var"))
library(ggplot2)

p <- ggplot(data = longDF, aes(x = variable, y = value, group = id.var))
p + geom_line() + stat_smooth(aes(group = 1), method = "lm", 
se = FALSE, colour="red") + facet_grid(cl ~ .)

Please don't hesitate to improve my code.

spaghetti plot with stat_smooth and facet_grid

like image 76
Eric Fail Avatar answered Nov 18 '22 13:11

Eric Fail