-1

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

Krantz
  • 1,424
  • 1
  • 12
  • 31
  • If you just want to get rid of the missing values, you can specify this at the beginning as `ggplot(new_new_mtcars %>% filter(!is.na(grouping)), aes(.........` – arg0naut91 Mar 03 '19 at 11:41
  • `+ geom_ribbon(data = df[!is.na (grouping), ], ...` – dww Mar 03 '19 at 12:18
  • Thanks, @dww. Using your code does not solve the problem. This `ggplot(new_new_mtcars,aes(x=wt,y=value,linetype=as.factor(Variable))) + geom_path(size = 0.71) + geom_ribbon(data = new_new_mtcars[!is.na (grouping), ],aes(fill = grouping, ymin = min(wt), ymax = max(wt), alpha = .25, na.rm=TRUE))` gives the message: ` In is.na(grouping) : is.na() applied to non-(list or vector) of type 'closure'`. Any thoughts? – Krantz Mar 03 '19 at 12:30

1 Answers1

2

Could try:

ggplot(new_new_mtcars) +
  geom_path(aes(x= wt, y = value, linetype = as.factor(Variable)), size = 0.71) + 
  geom_ribbon(data = . %>% filter(!is.na(grouping)),
              aes(x = wt, fill = grouping, ymin = min(wt), ymax = max(wt)), alpha = .25) 

Few other comments:

  • You don't need to reference your data frame in the aes call (just fill = grouping is enough),
  • If you want the transparency (alpha) parameter to take effect with a fixed value, you need to take it out of aes. Keep it inside when you are referencing a variable (e.g. you want to have different levels of alpha for certain groups/factors).
arg0naut91
  • 14,574
  • 2
  • 17
  • 38