How can I shade the region between max and min data points in R?

Viewed 27

I'm trying to make the confidence intervals in this graph reach the data points. Basically I have max and min values and I want a line through the mean and the space between the max and min to be shaded. How can I achieve this?

This is what my code looks like to make the graph pictured below:

ggplot(MassModels, aes(x = Length, y = Mass, color = Model)) +  scale_shape_manual(values = c(1,2,0,3,4,8,10)) + theme(legend.position="none") + geom_point() + geom_smooth(method = loess, se=T) + labs(x=expression("TL (cm)"), y=expression(M[b] (kg))) 

enter image description here

1 Answers

We could do that using stat_summary:

ggplot(mtcars, aes(cyl, mpg)) +
  stat_summary(geom = "ribbon", fun.min = min, fun.max = max, alpha = 0.1) +
  stat_summary(geom = "line", fun = mean) +
  geom_point(aes(y = mpg)) 

enter image description here

Or more hands-on, we could calculate it and use geom_ribbon, either in line with the ggplot call...

library(ggplot2); library(dplyr)
ggplot(mtcars, aes(cyl)) +
  geom_ribbon(data = . %>% group_by(cyl) %>%
                summarize(min = min(mpg), max = max(mpg)),
              aes(ymin = min, ymax = max),
              alpha = 0.1) +
  geom_line(data = . %>% group_by(cyl) %>%
                summarize(mean = mean(mpg)),
              aes(y = mean)) +
  geom_point(aes(y = mpg)) 

...or as a separate step:

mtcars_sum <- mtcars %>% 
  group_by(cyl) %>%
  summarize(min = min(mpg), mean = mean(mpg), max = max(mpg))

ggplot(mtcars, aes(cyl)) +
  geom_ribbon(data = mtcars_sum, alpha = 0.1, aes(ymin = min, ymax = max)) +
  geom_line(data = mtcars_sum, aes(y = mean)) +
  geom_point(aes(y = mpg)) 

enter image description here

Related