[英]how to include label for totals to a geom_bar stacked plot which already has data vales within stacks
这实际上是一个后续问题, 在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))
您必须创建另一个汇总表(按年的频率总和),并将其添加到图上,作为另一个vjust
> 1的geom_text
图层。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.