向R中的折线图添加功能区 [英] Add a ribbon to a line plot in R

查看:68
本文介绍了向R中的折线图添加功能区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以帮助我.我有10个时间序列,每一个都有100分. 我想将平均时间序列绘制为折线图,并在这条线上添加阴影带,以表示10个时间序列之间的标准差.

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.

时间序列定义为:

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) 

现在,我想将q.m绘制为一条线,并在可能的情况下使用q.pos和q.neg作为限制添加一条丝带

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

我想知道是否可以使用ggplot做到这一点.有谁对如何完成这项工作有任何想法.感谢您的投入.谢谢!

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!

推荐答案

您可能想查看以下链接:

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)

请注意,您正在计算列的标准偏差(在apply调用中为MARGIN = 2),而不是行.

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

这篇关于向R中的折线图添加功能区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆