在ggplot2的堆叠条形图的顶部显示每个组的总计(总和)值 [英] Showing total (sum) values each group on the top of stacked bar chart in ggplot2
本文介绍了在ggplot2的堆叠条形图的顶部显示每个组的总计(总和)值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用此代码制作了以下堆叠的条形图:
I used this code to make the following stacked bar chart:
library(ggplot2)
library(dplyr)
Year <- c(rep(c("2006", "2007", "2008", "2009"), each = 4))
Category <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data <- data.frame(Year, Category, Frequency)
Data2 <-Data%>%
group_by(Year, Category)%>%
summarise(Sum_grp = sum(Frequency))
Data3 <-transform(Data2, Pos = ave(Frequency, Year, FUN = cumsum) - Frequency / 2)
ggplot(Data3, aes(Year, Frequency, group=Category,fill = Category))+
geom_bar(stat="identity")+
geom_text(aes(label = Frequency,y=Pos), size = 3)
现在,我想在每个小节的顶部添加每个组的总和,但是我不知道如何。
Now, I would like to add the sum of each group on the top each bar but I do not have any idea how.
有人可以帮我吗?
非常感谢!!!!
推荐答案
如果要避免创建第3个摘要数据集,可以使用 stat_summary
。
If you wanted to avoid making a 3rd summary dataset, you could use stat_summary
.
ggplot(Data3, aes(Year, Frequency, group = Category, fill = Category))+
geom_bar(stat="identity")+
geom_text(aes(label = Frequency,y=Pos), size = 3) +
stat_summary(fun.y = sum, aes(label = ..y.., group = Year), geom = "text")
根据需要使用 vjust
将标签向上移动更多。我发现 vjust = -.2
看起来不错。
Use vjust
to move the labels up more if needed. I found vjust = -.2
seemed to look pretty good.
这篇关于在ggplot2的堆叠条形图的顶部显示每个组的总计(总和)值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文