facet_wrap添加geom_hline [英] facet_wrap add geom_hline

查看:247
本文介绍了facet_wrap添加geom_hline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ggplot有以下代码-facet_wrap函数在页面上为每个名称绘制20个图,并且在x轴上有5个Pcode.我想计算每个Name的平均TE.Contr并将该值绘制为每条图上的一条水平线(由Facet_wrap分割).目前,我的代码绘制了ALL TE.Contr的平均值.值而不是平均TE.Contr.特定名称的名称.

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)

推荐答案

使用mtcars的最小示例-您必须创建一个数据框,其中每个gear的均值(在本例中为Name).

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)

这篇关于facet_wrap添加geom_hline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆