Search code examples
rggplot2geom-text

Geom_text issue with label on a bar chart


Based off the iris data set I'm trying to create a bar chart with the average Sepal Length for each Species as the label for each bar.

Reproducible example:

#load data
iris1 <- as.data.frame(iris)

#packages
library(ggplot2) #visualizations

#create bar chart with average Sepal Length for each Species as the label
ggplot(data = iris1, aes(x = iris1$Species, y = iris1$Sepal.Length)) + 
  geom_bar(stat = "summary", fun.y ="mean",  fill = "light blue") +
  labs(title = "Sepal Length by Species", x = "Species", y = "Sepal Length") +
  geom_text(label = iris1$Sepal.Length)

Output: enter image description here

ggplot(data = iris1, aes(x = iris1$Species, y = iris1$Sepal.Length)) + 
  geom_bar(stat = "summary", fun.y ="mean",  fill = "light blue") +
  labs(title = "Sepal Length by Species", x = "Species", y = "Sepal Length") +
  geom_text(label = mean(iris1$Sepal.Length))

Output: enter image description here

I'd expect the graph to show 1 label of the average Sepal Length for each bar (setosa, versicolor, and virginica).


Solution

  • you can try this:

    ggplot(iris1, aes(x = Species, y = Sepal.Length)) + 
      stat_summary(fun.y=mean, geom="bar", fill = "light blue") +
      stat_summary(aes(label=..y..), fun.y=mean, geom="text", size=8)
    

    Output:

    enter image description here