Search code examples
rggplot2countlabelgeom-text

How to add count labels in ggplot2 barplot?


I'm trying to place count labels in a ggplot2 barplot and I haven't been able to do it. I need to display the number of pixels within each temperature range. The dataframe was built from a raster: EneroT5cmSC

datene <- as.data.frame(EneroT5cmSC,xy=TRUE)%>%drop_na()
datene$cuts <- cut(datene$layer, breaks=seq(21, 29, length.out=12))

dput:

datene_stuc <-  structure(
list(
  x = c(-57.063098328,-57.021448328,-56.996458328,-56.988128328),
  y = c(-30.087481664,-30.087481664,-30.087481664,-30.087481664),
  layer = c(
    25.6227328470624,
    26.6386584334308,
    26.0636709134397,
    26.0580615984563
  ),
  cuts = structure(
    c(7L, 9L,
      8L, 8L),
    .Label = c(
      "(20,20.8]",
      "(20.8,21.6]",
      "(21.6,22.5]",
      "(22.5,23.3]",
      "(23.3,24.1]",
      "(24.1,24.9]",
      "(24.9,25.7]",
      "(25.7,26.5]",
      "(26.5,27.4]",
      "(27.4,28.2]",
      "(28.2,29]"
    ),
    class = "factor"
  )
),
row.names = c(NA,
              4L),
class = "data.frame")

Barplot code:

ggplot() +
geom_bar(data = datene, aes(cuts, fill = cuts)) + 
scale_fill_viridis_d(option = "B",'Temp (Cº)') +
theme(axis.title.x=element_blank(), axis.title.y=element_blank()) +
geom_text(aes(label = ..count..), stat = "count", vjust = 1.5, colour = "black")

The labels on each bar do not appear


Solution

  • If you replace the code arguments from geom_bar to ggplot() and change vjust = -1 it works like this:

    datene_stuc <-  structure(
      list(
        x = c(-57.063098328,-57.021448328,-56.996458328,-56.988128328),
        y = c(-30.087481664,-30.087481664,-30.087481664,-30.087481664),
        layer = c(
          25.6227328470624,
          26.6386584334308,
          26.0636709134397,
          26.0580615984563
        ),
        cuts = structure(
          c(7L, 9L,
            8L, 8L),
          .Label = c(
            "(20,20.8]",
            "(20.8,21.6]",
            "(21.6,22.5]",
            "(22.5,23.3]",
            "(23.3,24.1]",
            "(24.1,24.9]",
            "(24.9,25.7]",
            "(25.7,26.5]",
            "(26.5,27.4]",
            "(27.4,28.2]",
            "(28.2,29]"
          ),
          class = "factor"
        )
      ),
      row.names = c(NA,
                    4L),
      class = "data.frame")
    
    library(ggplot2)
    ggplot(data = datene_stuc, aes(cuts, fill = cuts)) +
      geom_bar() + 
      geom_text(aes(label = ..count..), stat = "count", vjust = -1, colour = "black") +
      scale_fill_viridis_d(option = "B",'Temp (Cº)') +
      theme(axis.title.x=element_blank(), axis.title.y=element_blank()) 
    

    Created on 2022-07-17 by the reprex package (v2.0.1)