代码之家  ›  专栏  ›  技术社区  ›  cephalopod

如何将合计标签包含到已经在堆栈中有数据值的几何条形图中

  •  0
  • cephalopod  · 技术社区  · 7 年前

    这真是一个后续问题 Showing data values on stacked 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))
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   pogibas    7 年前

    您必须创建另一个汇总表(每年的频率总和),并将其添加到另一个绘图中。 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))
    

    enter image description here

    推荐文章