简体   繁体   中英

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

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

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() .

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.

I'd simply precompute the statistics, and build the plot afterwards:

library(plyr)
library(ggplot2)
dat = ddply(mtcars, .(gear), summarise, mean_mpg = mean(mpg))
dat = within(dat, {
    gear = factor(gear)
    mean_mpg_string = sprintf('%0.1f', mean_mpg)
  })
ggplot(dat, aes(x = gear, y = mean_mpg)) + 
    geom_bar(aes(fill = gear), stat = "identity") + 
    geom_text(aes(label = mean_mpg_string), vjust = -0.5)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM