Graphic time series with an average 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)) 

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

Is it possible to build a faceted time series that includes the average curve in each graph using ggplot2?

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

+6
source share
1 answer

It may not be the prettiest code, but I believe that it gets 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 feel free to improve my code.

spaghetti plot with stat_smooth and facet_grid

+12
source

Source: https://habr.com/ru/post/912334/


All Articles