繁体   English   中英

在R中绘制带置信区间的时间序列

[英]Plot time series with confidence intervals in R

这是我在R中制作的几个不同时间序列的情节: 在此输入图像描述

我用一个简单的循环制作了这些:

for(i in 1:ngroups){
  x[paste0("Group_",i)] = apply(x[,group == i],1,mean)
}

plot(x$Group_1,type="l",ylim=c(0,300))
for(i in 2:ngroups){
    lines(x[paste0("Group_",i)],col=i)
}

我也可以使用matplot制作这个情节。 现在,正如您所看到的,每个组都是其他几个列的平均值。 我想要做的是如上图所示绘制系列,但另外显示有助于该平均值的基础数据的范围。 例如,紫色线条将以浅紫色区域为界。 在任何给定的时间指数,紫色区域将从紫色组中的最低值延伸到最高值(或者,例如,5到95百分位数)。 是否有一种优雅/聪明的方式来做到这一点?

我使用一些随机数据制作了一个df。

这是df

df
   x         y
1  1 3.1667912
2  1 3.5301539
3  1 3.8497014
4  1 4.4494311
5  1 3.8306889
6  1 4.7681518
7  1 2.8516945
8  1 1.8350802
9  1 5.8163498
10 1 4.8589443
11 2 0.3419090
12 2 2.7940851
13 2 1.9688636
14 2 1.3475315
15 2 0.9316124
16 2 1.3208475
17 2 3.0367743
18 2 3.2340156
19 2 1.8188969
20 2 2.5050162

当您使用stat_summary与mean_cl_normal和geom smooth进行绘图时

   ggplot(df,aes(x=x,y=y))+geom_point() +  
stat_summary(fun.data=mean_cl_normal, geom="smooth", colour="red")

在此输入图像描述

有人评论说,也许mean_cl_boot更好,所以我用它。

 ggplot(df,aes(x=x,y=y))+geom_point() +
  stat_summary(fun.data=mean_cl_boot, geom="smooth", colour="red")

在此输入图像描述

他们确实有点不同。 您也可以根据需要使用confint参数。

这是使用graphics包(R附带的graphics )的答案。 我还试图解释如何创建polygon (用于生成CI)。 这可以重新用于解决您的问题,我没有确切的数据。

# Values for noise and CI size
s.e. <- 0.25 # standard error of noise
interval <- s.e.*qnorm(0.975) # standard error * 97.5% quantile

# Values for Fake Data
x <- 1:10 # x values
y <- (x-1)*0.5 + rnorm(length(x), mean=0, sd=s.e.) # generate y values

# Main Plot
ylim <- c(min(y)-interval, max(y)+interval) # account for CI when determining ylim
plot(x, y, type="l", lwd=2, ylim=ylim) # plot x and y

# Determine the x values that will go into CI
CI.x.top <- x # x values going forward
CI.x.bot <- rev(x) # x values backwards
CI.x <- c(CI.x.top, CI.x.bot) # polygons are drawn clockwise

# Determine the Y values for CI
CI.y.top <- y+interval # top of CI
CI.y.bot <- rev(y)-interval # bottom of CI, but rev Y!
CI.y <- c(CI.y.top,CI.y.bot) # forward, then backward

# Add a polygon for the CI
CI.col <- adjustcolor("blue",alpha.f=0.25) # Pick a pretty CI color
polygon(CI.x, CI.y, col=CI.col, border=NA) # draw the polygon

# Point out path of polygon
arrows(CI.x.top[1], CI.y.top[1]+0.1, CI.x.top[3], CI.y.top[3]+0.1)
arrows(CI.x.top[5], CI.y.top[5]+0.1, CI.x.top[7], CI.y.top[7]+0.1)

arrows(CI.x.bot[1], CI.y.bot[1]-0.1, CI.x.bot[3], CI.y.bot[3]-0.1)
arrows(CI.x.bot[6], CI.y.bot[6]-0.1, CI.x.bot[8], CI.y.bot[8]-0.1)

# Add legend to explain what the arrows are
legend("topleft", legend="Arrows indicate path\nfor drawing polygon", xjust=0.5, bty="n")

以下是最终结果: 在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM