[英]facet_wrap add geom_hline
我的ggplot有以下代码-facet_wrap函数为每个名称在页面上绘制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)
使用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)
您也可以创建自己的统计信息来为您计算行。 从扩展的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, ...)
)
}
然后你可以像这样使用它
ggplot(mtcars, aes(mpg, cyl)) +
stat_mean_line(color="red") +
geom_point() +
facet_wrap(~ gear)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.