如何计算堆积条形图中每条柱的百分比?

时间:2015-07-08 13:43:23

标签: r ggplot2

我使用ggplot2制作了一个堆积条形图,其代码如下:

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)

代码设法将百分比显示为标签并在y轴上保持实际数量。 但是,我希望每个条形计算百分比(显示在x轴上),而不是整个检查集(图中的条形图)。

我设法用以下代码完成了这个:

#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)

但是这个解决方案似乎非常手动,因为我需要计算每个标签的位置,这与使用stat_bin自动定位标签的第一个图不同。

现有答案非常有用,例如Showing percentage in bars in ggplotShow % instead of counts in charts of categorical variablesHow to draw stacked bars in ggplot2 that show percentages based on group?R stacked percentage bar plot with percentage of binary factor and labels (with ggplot) 但他们并没有完全解决这种情况。

重申一下,我怎么能使用第一个解决方案,但计算每个柱的百分比,而不是图中的整个条形图?

请问有人给我一些帮助吗?谢谢!

0 个答案:

没有答案