admin管理员组文章数量:1305301
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)
本文标签: rcalculate mean for geomhline for mean within each facetStack Overflow
版权声明:本文标题:r - calculate mean for geom_hline for mean within each facet - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741797704a2398034.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论