r - 在 ggplot 中绘制置信区间(来自矩阵)
问题描述
我使用基本的投入产出分析模拟了一个小区域的两个经济部门的环境破坏。
我使用矩阵绘制了每年按部门(我有 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)
解决方案
首先,请提供一些可重复的数据。我想你的问题已经在这里得到了回答。
假设在您的示例媒体中,趋势均值的 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)
给你下面的情节
推荐阅读
- javascript - 我做了一个javascript函数,现在我想缩短它,我该怎么做?
- ios - 尝试使用闭包在 ViewController 之间传递数据时出现什么错误?
- sql - 在 SQL 中将 Str 格式的日期更改为 Datetime 格式
- java - 邮递员状态:访问 POST 请求 Web 服务时出现 415 不支持的媒体类型
- python - 将带有 GMT 的时间戳转换为 Pandas 中的时间戳
- android - 通过 ADB 检索 Android 呼叫日志
- gruntjs - 如何使用 Grunt 将文件复制到每个目录?
- python-3.x - 在 django 中将 html 转换为 pdf 时处理 base64 图像的对齐
- android - 如何在Android中计算两个TIMESTAMP之间的时间差
- unit-testing - 如何设置 HTTP GET 虚假响应