ggplot2:使用使用stat_summary的fun.y ="mean"的条形图的标签值 [英] `ggplot2`: label values of barplot that uses `fun.y="mean"` of `stat_summary`

查看:182
本文介绍了ggplot2:使用使用stat_summary的fun.y ="mean"的条形图的标签值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我使用ggplot2stat_summary()绘制3档,4档和5档汽车的平均每加仑行驶里程数的小图,如何标记每个小节mpg的平均值?

If I use ggplot2's stat_summary() to make a barplot of the average number of miles per gallon for 3-, 4-, and 5-geared cars, for example, how can I label each of the bars with the average value for mpg?

library(ggplot2)
CarPlot <- ggplot() +
  stat_summary(data= mtcars,
               aes(x = factor(gear),
                   y = mpg,
                   fill = factor(gear)
                   ),
               fun.y="mean",
               geom="bar"
               )
CarPlot

我知道您通常可以使用geom_text(),但是我很难弄清楚该怎么做才能从stat_summary()获得平均值.

I know that you can normally use geom_text(), but I'm having trouble figuring out what to do in order to get the average value from stat_summary().

推荐答案

您应该使用内部变量..y..来获取计算出的平均值.

You should use the internal variable ..y.. to get the computed mean.

library(ggplot2)
CarPlot <- ggplot(data= mtcars) +
               aes(x = factor(gear),
                   y = mpg)+
      stat_summary(aes(fill = factor(gear)), fun.y=mean, geom="bar")+
      stat_summary(aes(label=round(..y..,2)), fun.y=mean, geom="text", size=6,
             vjust = -0.5)
CarPlot

但可能最好事先进行汇总.

but probably it is better to aggregate beforehand.

这篇关于ggplot2:使用使用stat_summary的fun.y ="mean"的条形图的标签值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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