I am trying to make geom_ribbon leave a gap for missing values. I am trying to implement the solutions discussed here and here, but I fail to see how to get the ribbon removed from the areas of the plot were values are missing. Here is my code:
mtmodel <- lm(mpg ~ wt, data = mtcars)
mtcars$Low <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,2]
mtcars$High <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,3]
mtcars$Mean <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,1]
new_mtcars<-gather(mtcars, "Variable", "value", Low:Mean)
new_new_mtcars <- new_mtcars %>%
mutate(grouping = case_when(
between(wt, min(wt), mean(wt) + 0.09) ~ "group1",
wt >= max(wt) - 0.5 ~ "group2"
))
ggplot(new_new_mtcars,aes(x=wt,y=value,linetype=as.factor(Variable))) +
geom_path(size = 0.71) +
geom_ribbon(aes(fill = new_new_mtcars$grouping, ymin = min(wt), ymax = max(wt), alpha = .25, na.rm=TRUE))
Thanks in advance for any help