Search code examples
rggplot2geom-bargeom-text

Percentages for geom_text in stacked barplot with counts


I want to have a stacked barplot with percentages in it based on counts. I have almost reached what I want but every value in the text is 100% instead of the real percentage ... I think there is one small mistake in my code but I can not find it.


ggplot(
  mtcars,
  aes(fill = factor(gear), 
      x = factor(carb))
) + 
  geom_bar(stat = "count", 
           position = "fill", 
           color = "black",
           width = 0.5) + 
  geom_text(aes(label = scales::percent(..prop..)), 
            position = position_fill(vjust = 0.5), 
            stat = "count") + 
  coord_flip()

enter image description here


Solution

  • Building on this answer

    You can use this:

    ggplot(
      mtcars,
      aes(fill = factor(gear), 
          x = factor(carb))
    ) + 
      geom_bar(stat = "count", 
               position = "fill", 
               color = "black",
               width = 0.5) + 
    
      geom_text(aes(label = scales::percent(..count../tapply(..count.., ..x.. ,sum)[..x..])),
                position = position_fill(vjust = 0.5),
                stat = "count") +
      coord_flip()
    

    enter image description here