facet_wrap添加geom_hline

问题描述 投票:8回答:2

我的ggplot有以下代码 - facet_wrap函数在页面上为每个Name绘制20个图,沿x轴有5个Pcode。我想计算每个Name的平均TE.Contr,并将该值绘制为每个图上的水平线(由Facet_wrap拆分)。目前,我的代码绘制了ALL 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
2个回答
9
投票

使用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)

1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.