9

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))
Display name
  • 4,153
  • 5
  • 27
  • 75

1 Answers1

7

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

Tom Jemmett
  • 181
  • 4
  • Thanks, an expansion on this can be found here https://stackoverflow.com/questions/46327431/ggplot2-and-facet-wrap-add-geom-hline – Display name Jan 17 '19 at 21:16