Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

r - facet_wrap add geom_hline

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...