facet_wrap add geom_hline

好久不见. 提交于 2019-12-11 15:14:24

问题


I have the following code for my ggplot - the facet_wrap function draws out 20 plots on the page for each Name and there are 5 Pcode along the x-axis. I would like to calculate the average TE.Contr for each Name and plot that value as a horizontal line on each of the plots (which are split out by Facet_wrap). Currently my codes plots the average of ALL TE.Contr. values instead of the average TE.Contr. of the specific Name.

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)

回答1:


Minimal example using mtcars - you have to create a data frame with mean for each gear (in your case it's 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)

For your case this should work:

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:


You could also create your own stat to calculate the line for you. Adapting the example from the extending ggplot2 guide You can make

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, ...)
  )
}

Then you could use it like

ggplot(mtcars, aes(mpg, cyl)) +
  stat_mean_line(color="red") +
  geom_point() +
  facet_wrap(~ gear)



来源:https://stackoverflow.com/questions/51332140/how-to-add-the-mean-of-data-as-a-horizontal-line-on-a-faceted-plot-in-r-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!