如何将总计标签包含到 geom_bar 堆叠图中,其中堆叠中已经有数据值
how to include label for totals to a geom_bar stacked plot which already has data vales within stacks
这真的是这里的后续问题 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))
您必须创建另一个汇总 table(按年份计算的频率总和)并将其作为另一个 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))
这真的是这里的后续问题 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))
您必须创建另一个汇总 table(按年份计算的频率总和)并将其作为另一个 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))