facet_wrap add geom_hline

前端 未结 2 1417
梦如初夏
梦如初夏 2020-12-01 19:19

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 calcul

2条回答
  •  执念已碎
    2020-12-01 19:33

    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)
    

提交回复
热议问题