I'm trying to create a plot of confidence bands, which update every year.
Here is an example of the plot I'm trying to create:
Some reproducible data is below:
x_axis <- seq(1,24)
confidence_low_yr_1 <- c(seq(40,by=15, length.out = 12),rep(NA,12))
confidence_high_yr_1 <- c(seq(140,by=15, length.out = 12),rep(NA,12))
confidence_low_yr_2 <- c(rep(NA,11),seq(250,by=15, length.out = 13))
confidence_high_yr_2 <- c(rep(NA,11),seq(315,by=15, length.out = 13))
When I tried to plot the lines, I received an error about mismatching lengths.. I'm guessing this had to do with the NA values. I'm not sure how to go about this, so any help would be appreciated. Another issue is filling in the are between the lines.
Is this even possible?
Can be achieved with geom_ribbon()
.
library(ggplot2)
x_axis <- seq(1,24)
confidence_low_yr_1 <- c(seq(40,by=15, length.out = 12),rep(NA,12))
confidence_high_yr_1 <- c(seq(140,by=15, length.out = 12),rep(NA,12))
confidence_low_yr_2 <- c(rep(NA,11),seq(250,by=15, length.out = 13))
confidence_high_yr_2 <- c(rep(NA,11),seq(315,by=15, length.out = 13))
data = data.frame(x_axis = x_axis,confidence_low_yr_1 = confidence_low_yr_1,confidence_high_yr_1 = confidence_high_yr_1,confidence_low_yr_2 = confidence_low_yr_2,confidence_high_yr_2 = confidence_high_yr_2 )
ggplot(data, aes(x = x_axis))+
geom_ribbon(aes(ymin = confidence_low_yr_1,ymax = confidence_high_yr_1))+
geom_ribbon(aes(ymin = confidence_low_yr_2,ymax = confidence_high_yr_2))
graphics.off()
plot(1,
xlim = range(x_axis),
ylim = range(c(confidence_high_yr_1,
confidence_high_yr_2,
confidence_low_yr_1,
confidence_low_yr_2),
na.rm = TRUE),
type = "n")
lines(x_axis, confidence_high_yr_1)
lines(x_axis, confidence_high_yr_2)
lines(x_axis, confidence_low_yr_1)
lines(x_axis, confidence_low_yr_2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With