繁体   English   中英

在ggplot中绘制置信区间(从矩阵中)

[英]Plotting confidence intervals in ggplot (from a matrix)

我使用基本的投入产出分析模拟了小区域两个经济部门的环境破坏。

我使用矩阵绘制了每年按部门划分的平均损失及其置信区间(我有一个10年的时间段),如下面的代码所示。

我想使用ggplot获得类似的图表。

目前,我已经决定省略与数据设置相对应的代码和模拟,以使问题尽可能简洁,请告诉我是否应该包含它。

预先感谢您的帮助

# Average drop in each iteration
medias=t(apply(vX,2,function(x) apply(x,2,mean)))

# std deviations
devtip=t(apply(vX,2,function(x) apply(x,2,sd)))
devtip
# and their confidence intervals
inter95=t(apply(vX,2,function(x) apply(x,2,quantile,p=c(0.025,0.975))))
# where the first two columns are the interval for the first sector
# where the second two columns are the interval for the first sector

inter95[,1:2] # ci for the first sector 
inter95[,3:4] # ci for the second sector  

# Plots the drop in demandfor each sector each year and its CI

matplot(medias[,],type="l",lty=1,lwd=1,ylab="Variación de la producción en Media",xlab="Tiempo (Iteracción)",ylim=range(inter95))
for(sec in 1:length(sec.int)){
  inter=apply(vX[,,sec],2,quantile,p=c(0.025,0.975))
  segments(x0=1:N,y0=inter[1,],y1=inter[2,],col=(1:length(sec.int))[sec])
}
legend("right",paste("Sec.",sec.int),col=1:length(sec.int),bty="n",lty=1)

首先,请提供一些可重复的数据。 而且我认为你的问题已在这里得到解答。

假设在你的例子中medias是一个矩阵,ncol = 2,两个趋势均值,inter95另一个矩阵,ncol = 4,保存置信区间,我会这样做:

df <- cbind.data.frame(medias, inter95)
names(df) <- c("mean1", "mean2", "lwr1", "upr1", "lwr2", "upr2")
df$time <- 1:n

ggplot(df, aes(time, mean1)) +
  geom_line() +
  geom_ribbon(data= df,aes(ymin= lwr1,ymax= upr1),alpha=0.3) +
  geom_line(aes(time, mean2), col= "red") +
  geom_ribbon(aes(ymin= lwr2,ymax= upr2),alpha=0.3, fill= "red")

使用此数据

set.seed(1)
n <- 10
b <- .5
medias <- matrix(rnorm(n*2), ncol= 2)
inter95 <- matrix(c(medias[ , 1]-b, medias[, 1]+b, medias[ , 2]-b, medias[ , 2]+b), ncol= 4)

给你以下情节

情节

暂无
暂无

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

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