【发布时间】:2021-12-12 18:24:21
【问题描述】:
我正在尝试使用 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 参数,则比例显示错误。
所以本质上我仍然想显示相对于每个不同组的比例,但用其他分类变量填充条形。
有什么办法解决这个问题吗?
谢谢
【问题讨论】: