`ggplot2`: label values of barplot that uses `fun.y=“mean”` of `stat_summary`

前端 未结 2 1821
半阙折子戏
半阙折子戏 2020-12-16 01:19

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

2条回答
  •  佛祖请我去吃肉
    2020-12-16 02:02

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

    enter image description here

    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.

提交回复
热议问题