首页 > 解决方案 > 如何将总计标签包含到已在堆栈中具有数据值的 geom_bar 堆积图

问题描述

这真的是这里的后续问题Showing data values on packed bar chart in 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))

标签: rggplot2geom-bar

解决方案


您必须创建另一个汇总表(按年份计算的频率总和)并将其添加为另一个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))

在此处输入图像描述


推荐阅读