Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R plot jumping confidence region

Tags:

r

ggplot2

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: graph from excel

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?

like image 564
figNewton Avatar asked Oct 17 '22 06:10

figNewton


2 Answers

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))
like image 115
Sada93 Avatar answered Oct 19 '22 17:10

Sada93


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)

enter image description here

like image 33
d.b Avatar answered Oct 19 '22 16:10

d.b