【问题标题】:Plotting confidence intervals in ggplot (from a matrix)在 ggplot 中绘制置信区间(来自矩阵)
【发布时间】:2019-05-23 12:38:18
【问题描述】:

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

我使用矩阵绘制了每年按部门(我有一个 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)

【问题讨论】:

    标签: r ggplot2 data-visualization


    【解决方案1】:

    首先,请提供一些可重现的数据。我想你的问题已经回答了here

    假设在您的示例媒体中,趋势均值的 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)
    

    为您提供以下情节

    plot

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 2016-10-20
      相关资源
      最近更新 更多