Pablo Brugarolas
Pablo Brugarolas

Reputation: 3

Plotting confidence intervals in ggplot (from a matrix)

I have simulated the enviromental damage on two economic sectors of a small region using basic input-output analysis.

I have plotted the average damage and its confidence interval by sector each year (I have a 10-year period) as reported in the code below, using matrix.

I would like to get a similar graph using ggplot.

For now, I have decided to omit the code corresponding to the data set up and the simulations to make the question as concise as possible, please, let me know if I should include it.

Thank you in advance for your help

# 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)

Upvotes: 0

Views: 1101

Answers (1)

user11538509
user11538509

Reputation:

Firstly, please provide some reproducible data. And I think you question has been answered here.

Assuming that in your example medias is a matrix with ncol= 2 for the both trend means and inter95 another matrix with ncol= 4, saving the confidence intervals, I would do:

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")

Using this data

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)

gives you the following plot

plot

Upvotes: 1

Related Questions