Search code examples
rggplot2label

How to label plot with value of bars?


I'm trying to make a barplot with two categorical values. This particular thread was very helpful

My code was this

ggplot(DF, aes(Participant.Type, ..count...)) + 
    geom_bar(aes(fill=Sex), position ="dodge") +
    theme_classic() +
    ggtitle("Main phenotypes stated for the PCDH19 cohort on GEL") + 
    scale_fill_viridis(option ="viridis")

This was my resulting graph. I'm now trying to add the count of the particular bars on top - like Female proband is 135, Male proband is 165 and so on. I tried adding different iterations of the geom_text command so I could achieve this. Commands here:

 + geom_text(aes(label= ..count))
 + geom_text(aes(label= Sex))

Could anyone please help?

barplot of two categorical variables with purple for female and yellow for male


Solution

  • With some sample data from that question you linked you can do it like this:

    library(ggplot2)
    library(viridis)
    #> Loading required package: viridisLite
    
    Fruit <- c(rep("Apple", 3), rep("Orange", 5))
    Bug <- c("worm", "spider", "spider", "worm", "worm", "worm", "worm", "spider")
    
    df <- data.frame(Fruit, Bug)
    
    ggplot(df, aes(Fruit, fill = Bug)) + geom_bar(position = "dodge") +
      geom_text(
        aes(label = after_stat(count)),
        stat = "count",
        vjust = -0.5,
        position = position_dodge(width = 0.9)
      ) +
      geom_text(
        aes(y = after_stat(count), label = Bug),
        stat = "count",
        vjust = -1.5,
        position = position_dodge(width = 0.9)
      ) +
      scale_y_continuous(expand = expansion(add = c(0, 1))) +
      scale_fill_viridis(option = "viridis", discrete = TRUE)
    

    A few things to note:

    • geom_bar doesn't need ..count.. passed as a y-value - it defaults to counting
    • after_stat(count) is the updated form of .. notation
    • Text labels need dodges added - default width is 0.9 for bars so this width matches the placement of the bars.