在ggplot2中的堆积条形图顶部显示每个组的总(总和)值

时间:2016-08-08 21:22:42

标签: r ggplot2 dplyr

我使用此代码制作以下堆积条形图:

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) 

enter image description here

现在,我想在每个栏的顶部添加每个组的总和,但我不知道如何。

有人能帮帮我吗?

非常感谢!!!!!

1 个答案:

答案 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")

enter image description here

如果需要,使用vjust更多地移动标签。我发现vjust = -.2看起来很不错。