如何将总计标签包含在已经在堆栈中包含数据值的 geom_bar 堆积图中

头足类

这真的是从这里的后续问题在 ggplot2 中的堆积条形图上显示数据值

在下图中,我还想包括列总数,例如:第一个堆栈应显示总数为 963 (168+259+226+340):

Year      <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), 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)

library(ggplot2)
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))
波吉巴斯

您必须创建另一个汇总表(按年份计算的频率总和)并将其添加为另一个geom_text图层,其中vjust> 1 位于条形图上方。

dfSum <- aggregate(Data$Frequency, list(Data$Year), sum)
ggplot(Data, aes(Year, Frequency, fill = Category, label = Frequency)) +
    geom_bar(stat = "identity") +
    geom_text(size = 3, position = position_stack(vjust = 0.5)) +
    geom_text(aes(Group.1, x, label = x), dfSum, inherit.aes = FALSE,
              position = position_stack(vjust = 1.05))

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章