最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - calculate mean for geom_hline for mean within each facet - Stack Overflow

programmeradmin0浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 3

You 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)

发布评论

评论列表(0)

  1. 暂无评论