r - 如何将总计标签包含到已在堆栈中具有数据值的 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))
解决方案
您必须创建另一个汇总表(按年份计算的频率总和)并将其添加为另一个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))
推荐阅读
- visual-studio-code - 发布 VSCode 扩展后缺少 SVG 图标
- twilio - 即使升级后也无法从 twilio 向未经验证的用户发送 otp 短信
- amazon-web-services - 允许从特定账户的所有 EC2 实例访问 S3 存储桶
- ldap - 身份验证/授权提供商:为 1 天的项目选择哪一个?
- php - 如何使用php对数据库中的列求和
- r - 如何将字符串向量映射为函数的参数?
- mysql - MySQL 选择 id from to 并排除开始和结束 id
- rstudio - 包被存储在临时文件中
- java - 从函数返回,一旦函数中的值为空
- sql - 如何简单地转动桌子(枢轴?)我似乎无法理解这个简单的概念