r - 将用于堆叠条形图 ggplot 的数据转换为可用于堆叠百分比图的数据的工作流程
问题描述
我有以下数据集:
(df<-structure(list(age_group = structure(c(3L, 3L, 5L, 3L, 5L, 5L,
5L, 3L, 5L, 5L, 4L, 4L, 4L, 3L, 5L), .Label = c("65+", "55-64",
"45-54", "35-44", "25-34", "18-24"), class = "factor"), Gender = c("F",
"M", "M", "M", "F", "M", "M", "M", "F", "M", "M", "F", "M", "F",
"M")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-15L), .Names = c("age_group", "Gender")))
# A tibble: 15 x 2
age_group Gender
<fct> <chr>
1 45-54 F
2 45-54 M
3 25-34 M
4 45-54 M
5 25-34 F
6 25-34 M
7 25-34 M
8 45-54 M
9 25-34 F
10 25-34 M
11 35-44 M
12 35-44 F
13 35-44 M
14 45-54 F
15 25-34 M
由此,我使用 ggplot 创建了以下堆叠条形图:
我现在想制作一个堆积百分比图,如下面的 SO 问题所示:创建堆积条形图,其中每个堆栈被缩放为总和为 100%
准备数据以生成堆叠百分比图的工作流程是什么?在我上面发布的 SO 问题中,数据有一个额外的值字段,我没有。
解决方案
dat = aggregate(list(value = 1:NROW(df)), df[c("age_group", "Gender")], length)
dat$proportion = ave(dat$value, dat$age_group, FUN = function(x) x/sum(x))
ggplot(dat, aes(x = age_group, y = proportion, fill = Gender)) +
geom_col() +
coord_flip()
推荐阅读
- c# - 已经执行任务取消时任务仍在运行
- google-apps-script - Google Apps 脚本很慢。好奇我如何改进这一点
- azure - 检查哪些 IP 有权访问 Azure VM
- python - 在 Python 中绘制 T 分布、标记关键区域和标记 T 分数的最简单方法
- javascript - 使 CSS 网格或 flex 项目大小相等,并在它们之间拉伸分隔符
- c# - 如何使用 C# 从 MySQL 数据库中检索图像
- angular - 如何获取 Angular ng 服务开发服务器的 HTTPS 回调
- apache-kafka - Kafka Connect、Cassandra Sink:如何指定分区和集群键?
- python - 根据其他列制作n个字符的SSN号
- python-3.x - 当用户输入第一个和第二个是具有整数的 F 字符串时比较 2 个字符串时,如何让整数成为任何内容?