Stack Exchange
Several labels while using geom_text function
I am using the following code and I want to have one label for each bar indicating the value of that bar instead of several labels as shown below. Can someone please help?
    ggplot(data = iris, aes(x = Species , y = Sepal.Length, fill = Species)) +
      geom_bar(stat = "summary",
               show.legend = T,
               fun = mean) +
      ylab("Sepal Length") + xlab("Types of Species") +
      ggtitle('Sepal Length vs Species') +
      scale_fill_manual("legend",
                        values = c(
                          "setosa" = "black",
                          "versicolor" = "orange",
                          "virginica" = "blue"
                        )) + geom_text(aes(label = Sepal.Length))



You can try this:
ggplot(data = iris, aes(x = Species , y = Sepal.Length, fill = Species)) +
  geom_bar(stat = "summary",
           show.legend = T,
           fun = mean) +
  ylab("Sepal Length") +
  xlab("Types of Species") +
  ggtitle('Sepal Length vs Species') +
  scale_fill_manual("legend",
                    values = c(
                      "setosa" = "black",
                      "versicolor" = "orange",
                      "virginica" = "blue"
                    )) +
  geom_text(aes(label = round(..y.., 2)), 
            stat = "summary",
            vjust = -.5)



Hi Ronak, thanks, this worked. I am fairly new to R, can you help me to know what does ..y.. means?

To refer to variables straight from the dataset, colnames are used as an aesthetic (e.g. aes(x = Species)). geom_bar can't use these variables straight, it needs to calculate the aesthetic in form of mean, count orsum. In your case geom_barcalculated the mean for each Species. ..y.. referes to this calculated  aesthtetic. So if you want to use values that are calculated by geom_baror stat_xxx you need to use ..calculated value..

As a work around you may calculate the means before you create a plot. Then you can use these the colnames containing the means directly. iris %>% group_by(Species) %>% summarise(Sepal.Length = mean(Sepal.Length)) %>%  ggplot(aes(x = Species, y = Sepal.Length, fill = Species)) + geom_col() + geom_text(aes(label = Sepal.Length))

This is an awesome but very underrated answer. Thanks for this code.
