4

I'am trying in R to plot the percentage labels for each bar in a stacked bar, if you see the first bar, the sum of percentages is 28%, not 100% as i am looking for it. it should be 72%, 14%, 14% for the first bar, for the second bar 11%, 67%, 22% and for the third 56%, 11%, 33%.

Stacked bar result image:

img

This is the code that i am using, with dummy data

df1 <- data.frame(ID = c(1, 2, 3, 4, 5),var1 = c('a', 'b', 'c', 'b', 'a','a', 'b', 'c', 'a', 'b','a', 'c', 'a', 'a', 'c','a', 'b', 'c', 'a', 'b','a', 'a', 'c', 'b', 'b'),var2 = c('l', 'm', 's', 'm', 's','l', 'm', 's', 's', 's','l', 'm', 's', 's', 'l','l', 'm', 's', 's', 'm','l', 'm', 'm', 'm', 'l'))

rs <- factor(df1$var1,levels = c("a","b","c"))

cs <- factor(df1$var2, levels = c("l","m","s"))

ggplot(df1, aes(cs, fill = rs)) + geom_bar() + 
    labs( x="", y="", title="", fill ="x") + ####LABELS
    theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),panel.background = element_blank(), axis.line = element_line(colour = "black")) + ####BACKGROUND
    geom_text(aes(label=..count.., group = cs),stat = "count", position = position_stack(1.05))+
    geom_text(aes(label=scales::percent(..count../sum(..count..))), stat='count',position=position_stack(0.5)) 

I tried adding the following line, because ..count.. gives me the value of the stack, for example var1:a, var2:l = 5, and ..count..,group=cs, gives me the total of the stacked bar, in this case for bar l = 7, but it does not work.

+geom_text(aes(label=scales::percent(..count../..count..,group = cs)), stat='count',position=position_stack(0.5))

I appreciate the help.

camille
  • 16,432
  • 18
  • 38
  • 60
Luisa Restrepo
  • 433
  • 4
  • 5

1 Answers1

1

Maybe it would be a bit simpler if you could pre-calculate what you want to show. One method could be

library(dplyr)
library(ggplot2)

df1 %>%
  count(var2, var1) %>%
  group_by(var2) %>%
  mutate(n1 = paste0(round(n/sum(n) * 100), "%")) %>%
  ggplot() + aes(var2, n, fill = var1) + 
  geom_col(width = .7) + 
  geom_text(aes(label = n1), position = position_stack(vjust = 0.5), size = 5) 

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213