我有以下代码为我ggplot - 在facet_wrap功能抽出20个地块在页面上每个名称和有5个P代码沿x轴。 我想,以计算每个名称的平均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)