r - 使百分比参与分组但由另一个变量着色
问题描述
我正在尝试使用 ggplot 在 R 中制作条形图。该图应该代表不同长度的百分比,每个方面代表一个分类变量。我想通过第三个变量为条形着色。这是我正在做的模拟:
lengths <- sample(x = c(12, 15, 20, 25, 30, 32, 35, 40, 45, 60), size = 1000, replace = TRUE)
group <- sample(c("A", "B", "C", "D"), size = 1000, replace = TRUE)
sex <- sample(c("Female", "Male"), size = 1000, replace = TRUE)
data <- data.frame(lengths = lengths, sex = sex, group = group)
rm(lengths, group, sex)
ggplot(data = data %>%
bind_rows(data %>%
mutate(group = "Total")), aes(x = lengths, group = group, fill = sex)) +
geom_bar(aes(y = ..prop..), color = "black", stat = "count") +
labs(y = "%", fill = "sex") +
facet_wrap(~ group, nrow = 6, strip.position = "right", scales = "free") +
scale_x_continuous(limits = c(20,80)) +
scale_y_continuous(labels = scales::percent) +
theme(legend.position = c(.75, .95), legend.background = element_rect(fill = "white", color = "black"), axis.line = element_line(color = "black"), panel.background = element_blank(), legend.direction = "horizontal", strip.background = element_blank(), strip.text.y = element_blank()) +
scale_color_discrete(guide = "none") +
scale_fill_manual(values = c("purple", "blue", "gray"))
但结果不是我要找的,因为所有的条都是灰色的,而不是按性别填充的:
这是我用来计算每组内计数比例的代码(不是性别)。如果我不考虑 group 参数,则比例尺看起来是错误的。
所以本质上我仍然想显示相对于每个不同组的比例,但用另一个分类变量填充条形。
任何想法如何解决这个问题?
谢谢
解决方案
只需删除 group=group:
`ggplot(data = data %>%
bind_rows(data %>%
mutate(group = "Total")), aes(x = lengths, fill = sex)) +
geom_bar(aes(y = ..prop..), color = "black", stat = "count") +
labs(y = "%", fill = "sex") +
facet_wrap(~ group, nrow = 6, strip.position = "right", scales = "free") +
scale_x_continuous(limits = c(20,80)) +
scale_y_continuous(labels = scales::percent) +
theme(legend.position = c(.75, .95), legend.background = element_rect(fill = "white", color = "black"), axis.line = element_line(color = "black"), panel.background = element_blank(), legend.direction = "horizontal", strip.background = element_blank(), strip.text.y = element_blank()) +
scale_color_discrete(guide = "none") +
scale_fill_manual(values = c("purple", "blue", "gray"))`
我花了很长时间才弄清楚这一点。
推荐阅读
- scala - 在 Spark 中,如何读取使用 bucketBy 编写的 parquet 文件并保存分桶数据?
- angular - 如何使用 pairwise() 管道使用 FormGroup.valueChanges?
- bazel - Bazel:cc_binary 无法在相关 cc_library 中找到标头
- java - 从 HashMap 中获取或获取 Object Array 中的值
- python-3.x - peewee playhouse.flask_utils import object_list 在首页什么都没有出现
- c - 我想检查我的函数是否返回一个指向正确对象的指针
- sql - 尝试在 Oracle 中创建静态函数时如何查看错误?当我运行它无法执行并且没有说任何错误
- filter - 为什么将过滤器添加到 web.xml 会导致 404 错误?
- microsoft-graph-api - 如何检索列表分配返回的引用实体
- git - 拉取来自分叉仓库的 PR 以在本地进行测试