Different `geom_hline()` for each facet of ggplot

Viewed 3826

facet

library(tidyverse)
ggplot(mpg, aes(cty, hwy)) + 
  geom_point() + 
  facet_grid(year ~ fl) + 
  geom_hline(yintercept = mean(mpg$hwy))

I want each geom_hline() in the facet shown above to be the mean of the points that are only contained within that facet. I would think that I could do it with something like (below). But that doesn't work. I'm close, right?

library(tidyverse)
ggplot(mpg, aes(cty, hwy)) + 
  geom_point() + 
  facet_grid(year ~ fl) + 
  geom_hline(yintercept = mean(mpg %>% group_by(year, fl)$hwy))
1 Answers

If you have the value you wish to use for each facet as a column in the data frame, and that value is unique within each facet, then you can use geom_hline(aes(yintercept=column)), which will then plot a horizontal line for each of the facets

Related