I have produced a stacked bar plot using ggplot2 with the code below:
library(ggplot2)
g <- ggplot(data=df.m, aes(x=Type_Checklist,fill=Status)) +
geom_bar(stat="bin", position="stack", size=.3) +
scale_fill_hue(name="Status") +
xlab("Checklists") + ylab("Quantity") +
ggtitle("Status of Assessment Checklists") +
theme_bw() +
theme(axis.text.x = element_text(angle=90, vjust=0.5, size=10))+
stat_bin(geom = "text",aes(label = paste(round((..count..)/sum(..count..)*100), "%")),vjust = 1)
print(g)
The code manages to show the percentage as labels and maintained the actual quantities on the y axis. However, I wanted the percentages to be calculated per bar (shown on the x axis), not for the entire set of checks (bars in the plot).
I managed to do exactly that with the following code:
#count how many checklists per status`
qty.checklist.by.status.this.week = df.m %>% count(Type_Checklist,Status)
# Add percentage
qty.checklist.by.status.this.week$percentage <- (qty.checklist.by.status.this.week$n/ nrNAs * 100)
#add column position to calculate where to place the percentage in the plot
qty.checklist.by.status.this.week <- qty.checklist.by.status.this.week %>% group_by(Type_Checklist) %>% mutate(pos = (cumsum(n) - 0.5 * n))
g <- ggplot(data=qty.checklist.by.status.this.week, aes(x=Type_Checklist,y=n,fill=Status)) +
geom_bar(stat="identity",position="stack", size=.3) +
scale_fill_hue(name="Status") +
xlab("Checklists") + ylab("Quantity") +
ggtitle("Status of Assessment Checklists") +
theme_bw() +
theme(axis.text.x = element_text(angle=90, vjust=0.5, size=10))+
geom_text(aes(y = pos,label = paste(round(percentage), "%")),size=5)
print(g)
But that solution seems quite manual, since I need to calculate the position of each label, different from the first plot that positions the labels automatically using stat_bin.
Existing answers have been very useful, such as Showing percentage in bars in ggplot and Show % instead of counts in charts of categorical variables and How to draw stacked bars in ggplot2 that show percentages based on group? and R stacked percentage bar plot with percentage of binary factor and labels (with ggplot) but they don't address exactly this situation.
To reiterate, how could I use the first solution, but calculate the percentages per bar, not for the entire set of bars in the plot?
Could anyone give me some help please? Thanks!