plot data and their means in the same graph using ggplot

Viewed 32

using the data set airquality I have written the following code:

library("tidyverse")
data(airquality)
airquality <- na.omit(airquality)
airquality$date <- as.Date(paste("1973", airquality$Month, airquality$Day,
                                 sep="-"))
p1 <- ggplot(airquality, aes(x= date, y = Ozone, col=factor(Month))) + 
   geom_point()  + 
   geom_line()
p1

Now I would like to plot in the same graph the mean of ozone for each months. How can I do this?

1 Answers

You could add the mean as a dashed line. The easiest way to do this might be to simply pass the data you want to a geom_line layer:

ggplot(airquality, aes(x = date, y = Ozone, col = factor(Month))) +
  geom_point() +
  geom_line(alpha = 0.5) +
  geom_line(data = airquality %>% 
                    group_by(Month) %>%
                    summarise(Ozone = mean(Ozone), 
                              date = c(first(date), last(date)),
                              Month = mean(Month)),
            linetype = 2, size = 1) +
  scale_color_brewer(palette = "Set1") +
  theme_minimal(base_size = 16)

enter image description here

If you just want points showing the mean, you could simplify things with stat_mean from ggpubr

ggplot(airquality, aes(x = date, y = Ozone, col = factor(Month))) +
  geom_point() +
  geom_line(alpha = 0.5) +
  ggpubr::stat_mean(size = 5, shape = 21,
                    aes(fill = factor(Month)), color = "black") +
  scale_color_brewer(palette = "Set1") +
  scale_fill_brewer(palette = "Set1") +
  theme_minimal(base_size = 16)

enter image description here

To join these dots up, you could do:

ggplot(airquality, aes(x = date, y = Ozone, col = factor(Month))) +
  geom_point() +
  geom_line(alpha = 0.5) +
  geom_line(data = airquality %>% 
                    group_by(Month) %>% 
                    summarise(Ozone = mean(Ozone), date = mean(date)),
            color = "black", linetype = 2) +
  ggpubr::stat_mean(size = 5, shape = 21,
                    aes(fill = factor(Month)), color = "black") +
  scale_color_brewer(palette = "Set1") +
  scale_fill_brewer(palette = "Set1") +
  theme_minimal(base_size = 16)

enter image description here

Related