代码之家  ›  专栏  ›  技术社区  ›  Ibo

如何在r ggplot2[复制]中将数据的平均值作为一条水平线添加到分面图上

  •  0
  • Ibo  · 技术社区  · 7 年前

    我的ggplot有以下代码:facet_wrap函数在页面上为每个名称绘制20个图,x轴上有5个pcode。我想计算每个名称的平均te.contr,并将该值绘制为每个绘图(按facet_wrap拆分)上的水平线。目前我的代码绘制了所有TE.CONR的平均值。数值而不是平均温度。具体的名字。

    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)
    
    0 回复  |  直到 6 年前
        1
  •  10
  •   pogibas    6 年前

    最小示例使用 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
  •  2
  •   MrFlick    7 年前

    您还可以创建自己的统计数据来计算行。改编自 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)
    

    enter image description here

    推荐文章