首页 > 解决方案 > 使百分比参与分组但由另一个变量着色

问题描述

我正在尝试使用 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 参数,则比例尺看起来是错误的。

所以本质上我仍然想显示相对于每个不同组的比例,但用另一个分类变量填充条形。

任何想法如何解决这个问题?

谢谢

标签: rggplot2bar-chartfacet

解决方案


只需删除 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"))`

我花了很长时间才弄清楚这一点。


推荐阅读