Percentages for geom_text in stacked barplot with counts
Asked Answered
P

1

5

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

Pino answered 22/12, 2019 at 12:38 Comment(2)
Does this answer your question? How to draw stacked bars in ggplot2 that show percentages based on group?Lorenza
No because I cannot use stat = "identity". But thank you!Pino
C
9

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

Carrera answered 22/12, 2019 at 23:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.