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:
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.