6
votes

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

1

1 Answers

12
votes

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