Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a ribbon to a line plot in R

Tags:

r

ggplot2

I was wondering if anyone could help me out. I have 10 time series each with 100 points. I would like to plot the average time series as a line plot, and add to this line a shaded ribbon representing the standard deviation among the 10 time series.

The time series are defined as:

q[110,10]  

I've calculated the mean series as:

q.mean = apply(q,c(1),mean)  

And the standard deviation limits as:

q.pos = q.mean + apply(q,2,sd)  
q.neg = q.mean - apply(q,2,sd) 

Now I'd like to plot q.m as a line, and if possible add a ribbon using q.pos and q.neg as limits

I was wondering if I can do this using ggplot. Does anyone have any idea on how to get this done. I appreciate any input. Thank you!

like image 690
user1031384 Avatar asked Dec 28 '22 11:12

user1031384


1 Answers

You might want to check out this link: http://docs.ggplot2.org/current/geom_ribbon.html

However this simple code should put you on the right track.

library(ggplot2)
q <- data.frame(
  x   = seq(1, 100, 1),
  ts1 = sample(1:100),
  ts2 = sample(1:100))

q$mean <- apply(q, 1, function(row) mean(row[-1]))
q$sd   <- apply(q, 1, function(row) sd(row[-1]))

eb <- aes(ymax = mean + sd, ymin = mean - sd)
ggplot(data = q, aes(x = x, y = mean)) + 
  geom_line(size = 2) + 
  geom_ribbon(eb, alpha = 0.5)

Note that you were computing standard deviation on columns (MARGIN = 2, in the apply call), not on rows.

like image 149
mbask Avatar answered Jan 06 '23 13:01

mbask