【问题标题】:facet_wrap add geom_hlinefacet_wrap 添加 geom_hline
【发布时间】:2026-01-06 14:15:01
【问题描述】:

我的 ggplot 有以下代码 - facet_wrap 函数在页面上为每个名称绘制 20 个图,并且沿 x 轴有 5 个 Pcode。我想计算每个名称的平均 TE.Contr 并将该值绘制为每个图上的水平线(由 Facet_wrap 拆分)。目前我的代码绘制了所有 TE.Contr 的平均值。值而不是平均 TE.Contr。的具体名称。

T<-ggplot(data = UKWinners, aes(x = Pcode, y = TE.Contr., color =  Manager)) + geom_point(size =3.5)+ geom_hline(aes(yintercept = mean(TE.Contr.)))
T<-T + facet_wrap(~ Name, ncol = 5)

【问题讨论】:

标签: r ggplot2 facet facet-wrap


【解决方案1】:

使用mtcars 的最小示例 - 您必须为每个gear 创建一个数据框(在您的情况下为Name)。

library(tidyverse)
dMean <- mtcars %>%
    group_by(gear) %>%
    summarise(MN = mean(cyl))
ggplot(mtcars) +
    geom_point(aes(mpg, cyl)) +
    geom_hline(data = dMean, aes(yintercept = MN)) +
    facet_wrap(~ gear)

对于您的情况,这应该有效:

library(tidyverse)
dMean <- UKWinners %>%
    group_by(Name) %>%
    summarise(MN = mean(TE.Contr.))
ggplot(UKWinners) +
    geom_point(aes(Pcode, TE.Contr.)) +
    geom_hline(data = dMean, aes(yintercept = MN)) +
    facet_wrap(~ Name)

【讨论】:

    【解决方案2】:

    您还可以创建自己的统计数据来为您计算线。改编自extending ggplot2 guide的例子你可以做

    StatMeanLine <- ggproto("StatMeanLine", Stat,
      compute_group = function(data, scales) {
        transform(data, yintercept=mean(y))
      },
      required_aes = c("x", "y")
    )
    
    stat_mean_line <- function(mapping = NULL, data = NULL, geom = "hline",
                           position = "identity", na.rm = FALSE, show.legend = NA, 
                           inherit.aes = TRUE, ...) {
      layer(
        stat = StatMeanLine, data = data, mapping = mapping, geom = geom, 
        position = position, show.legend = show.legend, inherit.aes = inherit.aes,
        params = list(na.rm = na.rm, ...)
      )
    }
    

    然后你可以像这样使用它

    ggplot(mtcars, aes(mpg, cyl)) +
      stat_mean_line(color="red") +
      geom_point() +
      facet_wrap(~ gear)
    

    【讨论】: