ggplot2和facet_wrap:添加geom_hline

use*_*385 8 r facet ggplot2 facet-wrap

我的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)
Run Code Online (Sandbox Code Playgroud)

PoG*_*bas 10

使用最小的示例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)
Run Code Online (Sandbox Code Playgroud)

对于你的情况,这应该工作:

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)
Run Code Online (Sandbox Code Playgroud)


MrF*_*ick 5

您还可以创建自己的统计数据来为您计算线路。改编来自扩展 ggplot2 指南的示例您可以

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, ...)
  )
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它

ggplot(mtcars, aes(mpg, cyl)) +
  stat_mean_line(color="red") +
  geom_point() +
  facet_wrap(~ gear)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明