如何使用 Facet R 添加线条

How to Add Lines With A Facet R

所以我有一个分面图,我希望能够向其中添加随每个分面变化的线条。

代码如下:

p <- ggplot(mtcars, aes(x=wt))+
  geom_histogram(bins = 20,aes(fill = factor(cyl)))+
  facet_grid(.~cyl)+
  scale_color_manual(values = c('red','green','blue'))+
  geom_vline(xintercept = mean(mtcars$wt))

p

所以我的问题是,我怎样才能得到它,以便图表显示每个分面子图的平均值。

无论您的回答能力如何,我都希望您能理解并感谢您的宝贵时间。

您可以使用 ggstance 包中的 stat_summaryh 在 ggplot 调用中执行此操作。在下面的代码中,假设您尝试设置直方图条的填充颜色,我还将 scale_colour_manual 更改为 scale_fill_manual

library(tidyverse)
library(ggstance)

ggplot(mtcars, aes(x=wt))+
  geom_histogram(bins = 20,aes(fill = factor(cyl)))+
  stat_summaryh(fun.x=mean, geom="vline", aes(xintercept=..x.., y=0), 
                colour="grey40") +
  facet_grid(.~cyl)+
  scale_fill_manual(values = c('red','green','blue')) +
  theme_bw()

另一种选择是在 geom_vline 内计算所需的均值(这是 @Ben 建议的摘要方法的实现)。在下面的代码中,. 是一个 "pronoun",它指的是输入到 ggplot 中的数据框(mtcars):

ggplot(mtcars, aes(x=wt))+
  geom_histogram(bins = 20,aes(fill = factor(cyl)))+
  geom_vline(data = . %>% group_by(cyl) %>% summarise(wt=mean(wt)), 
             aes(xintercept=wt), colour="grey40") +
  facet_grid(.~cyl)+
  scale_fill_manual(values = c('red','green','blue')) +
  theme_bw()