簡體   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