How to add y value average text to geom_bar?

How to add y value average text to geom_bar?

Problem Description:

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 – 1

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:


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

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.