Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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

like image 705
Adam Liter Avatar asked Nov 22 '13 08:11

Adam Liter


People also ask

What does fun data mean in R?

fun.data. A function that is given the complete data and should return a data frame with variables ymin , y , and ymax .

What does stat =' summary do in Ggplot?

ggplot2 has the ability to summarise data with stat_summary . This particular Stat will calculate a summary of your data at each unique x value. The following creates a scatter plot of some points with a mean calculated at each x and connected by a line.


1 Answers

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.

like image 132
agstudy Avatar answered Sep 19 '22 14:09

agstudy