Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different `geom_hline()` for each facet of ggplot [duplicate]

Tags:

r

dplyr

ggplot2

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))
like image 456
Display name Avatar asked Jan 17 '19 20:01

Display name


Video Answer


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

like image 99
Tom Jemmett Avatar answered Sep 23 '22 05:09

Tom Jemmett