我使用此代码制作以下堆积条形图:
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)
现在,我想在每个栏的顶部添加每个组的总和,但我不知道如何。
有人能帮帮我吗?
非常感谢!!!!!
答案 0 :(得分:12)
如果您想避免制作第3个摘要数据集,可以使用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
看起来很不错。