I'm trying to add a horizontal line to each facet of my plot containing the mean value for solely the data in each facet. The only solutions I've found so far are to calculate the mean value in a separate dataframe and add that to the plot. Is there really no way to do this without that added step??
# plot with shared mean across facets
mutate(cars, grp = if_else(speed <15, "slow", "fast")) %>%
ggplot(aes(x = speed, y = dist)) +
geom_point() +
geom_hline(aes(yintercept = mean(dist))) +
facet_grid(.~grp)
# I would have thought something like this would work, but it gives the same result
mutate(cars, grp = if_else(speed <15, "slow", "fast")) %>%
ggplot(aes(x = speed, y = dist)) +
geom_point() +
stat_summary(aes(yintercept = mean(dist)), fun = mean, geom = "hline") +
facet_grid(.~grp)
I'm trying to add a horizontal line to each facet of my plot containing the mean value for solely the data in each facet. The only solutions I've found so far are to calculate the mean value in a separate dataframe and add that to the plot. Is there really no way to do this without that added step??
# plot with shared mean across facets
mutate(cars, grp = if_else(speed <15, "slow", "fast")) %>%
ggplot(aes(x = speed, y = dist)) +
geom_point() +
geom_hline(aes(yintercept = mean(dist))) +
facet_grid(.~grp)
# I would have thought something like this would work, but it gives the same result
mutate(cars, grp = if_else(speed <15, "slow", "fast")) %>%
ggplot(aes(x = speed, y = dist)) +
geom_point() +
stat_summary(aes(yintercept = mean(dist)), fun = mean, geom = "hline") +
facet_grid(.~grp)
Share
Improve this question
asked Feb 3 at 21:05
tnttnt
1,45920 silver badges36 bronze badges
1 Answer
Reset to default 3You can achieve your desired result using after_stat()
to map the mean
computed by stat_summary
on yintercept
and by mapping a constant on x
inside stat_summary
:
library(ggplot2)
library(dplyr, warn = FALSE)
mutate(cars, grp = if_else(speed < 15, "slow", "fast")) %>%
ggplot(aes(x = speed, y = dist)) +
geom_point() +
stat_summary(
aes(yintercept = after_stat(y), x = 1),
fun = mean, geom = "hline"
) +
facet_grid(. ~ grp)