Search code examples
rggplot2geom-bargeom-text

Show individual bar count label in grouped bar plot


I am trying to plot Male and Female in different Age Groups. I am trying to show the individual Male and Female Count in their respective bars/colours but the graphs shows the total count value in the AgeGroup. How I am going to show/label the individual count of male and female in their respective bars/colours by AgeGroup. Example Data is presented. Thanks

Age sex AgeGroup
22 F 18-25 Years
36 F 36-45 Years
20 M 18-25 Years

Code I used:

library(tidyverse)

ggplot(demo_df, mapping = aes(x = AgeGroup)) + 
  geom_bar(aes(fill = sex), position="dodge")+
  geom_text(stat = "count", aes(label = scales::comma(after_stat(count))),
            nudge_y = 10000, fontface = 2) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 0),
        axis.text.y.left = element_blank(),
        axis.title.y.left = element_blank())


Solution

  • One more version using geom_col and calculating stats before plotting: Data from @Allan Cameron (many thanks!):

    library(tidyverse)
    library(RColorBrewer)   
    
    demo_df %>% 
      as_tibble() %>% 
      count(sex, AgeGroup) %>% 
      ggplot(aes(x=AgeGroup, y=n, fill = sex))+
      geom_col(position = position_dodge())+
      geom_text(aes(label = n, group = sex), 
                position = position_dodge(width = .9),
                vjust = -1, size = 3)+
      scale_fill_brewer(palette = 1, direction = - 1) + 
      theme_bw() +
      theme(axis.text.x = element_text(angle = 90, hjust = 0),
            axis.text.y.left = element_blank(),
            axis.title.y.left = element_blank())
    

    enter image description here