2011-11-05 52 views
3

我想知道是否有人能帮助我。我有10个时间系列,每个系列都有100分。 我想将平均时间序列绘制为线条图,并在此线上添加代表10个时间序列中标准偏差的阴影带。将色带添加到R的线图中

时间序列被定义为:

q[110,10] 

我计算的平均系列作为:

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

和标准差为界限:

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

现在我想要将qm作为一条线,并且如果可能的话添加一个使用q.pos和q.neg作为限制的色带

我想知道如果我可以使用ggplot做到这一点。有没有人有任何想法如何做到这一点。我很欣赏任何输入。谢谢!

回答

8

你可能想看看这个链接:http://docs.ggplot2.org/current/geom_ribbon.html

但是这个简单的代码应该把你在正确的轨道上。

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) 

注意,你是在计算列标准偏差(MARGIN = 2,在申请通话),而不是行。

+0

嗨!出于好奇,我们能否以类似的方式使用geom_smooth。我试过'ggplot(q,aes(x = x,y = mean))+ geom_line(size = 1)+ stat_smooth(method =“lm”,formula = y〜q $ mean,size = 1)不行。 – user2217564

+0

这是因为'stat_smooth'的'公式'参数映射到'aes'映射。这个工作:'ggplot(q,aes(x = x,y = mean))+ geom_line(size = 1)+ stat_smooth(method =“lm”,formula = y〜x,size = 1)'或者自'y 〜x'是'formula'的默认值:'ggplot(q,aes(x = x,y = mean))+ geom_line(size = 1)+ stat_smooth(method =“lm”,size = 1)''。在任何一种情况下,“lm”平滑器都不会按照您的想法进行操作,您可能希望查看样条曲线 – mbask