Search code examples
rggplot2meangeom-text

How to add y value average text to geom_bar?


enter image description here

ggplot(aes(x=MALE, y=AMOUNT, fill=MALE)) + geom_bar(stat="summary", fun="mean") +
  ylab("Avg Amount") + theme(axis.title.x = element_blank())

How can I add the y value to the top of the bars given I've already created stat='summary' & fun='mean' when I created the graph?


Solution

  • To add the y value as label on top of your bars you can do:

    geom_text(aes(label = after_stat(y)), stat = "summary", fun = "mean", vjust = -.1)
    

    Using mtcars as example data and with some additional formatting of the label:

    library(ggplot2)
    
    ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
      geom_bar(stat = "summary", fun = "mean") +
      geom_text(aes(label = after_stat(sprintf("%.1f", y))), stat = "summary", fun = "mean", vjust = -.1) +
      ylab("Avg Amount") +
      theme(axis.title.x = element_blank())
    

    enter image description here