I am trying to create a stacked bar chart which has proportional values (percentages) but at the same time shows absolute values on top of the respective bar. At the moment, I am only able to display values at wrong places on the chart.
My data.frame
looks something like this:
Var1 Freq pltype Num
1 SA 18 A1 2
2 SN 2 A1 4
3 UA 18 A1 1
4 SA 4 A2 2
5 UA 34 A2 1
6 SA 8 A3 2
7 SN 1 A3 4
8 UA 29 A3 1
9 SA 21 A4 2
10 SN 10 A4 4
11 UA 7 A4 1
12 N 2 A5 3
13 SA 14 A5 2
14 SN 1 A5 4
15 UA 21 A5 1
16 SA 11 A6 2
17 SN 1 A6 4
18 UA 26 A6 1
19 SA 3 A7 2
20 SN 16 A7 4
21 UN 19 A7 5
22 N 6 A8 3
23 SA 5 A8 2
24 UA 27 A8 1
So far I have created this piece of code:
#Ordered characters by numbers and plotted them
p1 <- ggplot(f[order(f$Num), ],aes(x=pltype,y=(Freq*100)/sum(data.frame(df[[exp]][1])$Freq),fill=Num))+
geom_bar(stat="identity")
p1+scale_fill_brewer(palette="Pastel1",labels=tp_code)+
theme(axis.text.x = element_text(angle = 30, hjust = 1, vjust=1)) +
xlab("Question")+ylab("Percentage")+geom_text(aes(label=Freq))+
ggtitle(names(df)[exp])
This gives me the following stacked bar chart:
I used the code from "R Graphics Cookbook" first creating a cumulative sum of Frequencies:
ce <- arrange(f, pltype, desc(Freq))
ce <- ddply(ce, "pltype",transform, label_y = cumsum(Freq))
Trying different permutations by messing with the geom_text
I could not get the code to work properly. Also this code has the problem that it shows cumulative sum and not the absolute value within each category.
Any help would be greatly appreciated!