R 中分组箱线图中的颜色

问题描述 投票:0回答:1

我正在使用 ggplot 为分层样本创建分组箱线图。作为一个虚构的示例,y 轴上是值(例如,测试分数),x 轴上是类别(白人、黑人和亚洲人)。但我还通过另一个变量对每个类别进行分组(例如,男性 vs. 女性)。所以,会有 6 个盒子。

我希望类别的颜色为红色、蓝色和紫色。但我希望性别分组变量使颜色变亮和变暗(例如,亚洲男性 = 浅紫色,亚洲女性 = 深紫色)。

这可能吗?谢谢!

我在网上进行了大量搜索,但没有找到解决方案。我确信我不是第一个这样做的人,但我还没有找到如何做到这一点的解释。

r ggplot2 boxplot grouped-bar-chart
1个回答
0
投票

有几种不同的方法可以做到这一点。您可以使用

alpha
美学:

ggplot(df, aes(Race, Score, fill = Race, alpha = Sex,, 
               group = interaction(Sex, Race))) +
  geom_boxplot(outlier.colour = NA) +
  geom_point(size = 0.5, position = position_jitterdodge(0.1), alpha = 0.2) +
  scale_fill_manual(NULL, values = c("deepskyblue", "purple", "red")) +
  scale_y_continuous(limits = c(0, 6), expand = c(0, 0)) +
  theme_minimal(base_size = 20) +
  labs(x = NULL) +
  scale_alpha_manual(values = c(0.5, 1)) +
  guides(alpha = guide_legend(override.aes = list(fill = "gray"))) +
  theme(panel.grid.major.x = element_blank())

或按性别和种族的

interaction
填写

ggplot(df, aes(Race, Score, fill = interaction(Sex, Race, sep = " "), 
               group = interaction(Sex, Race))) +
  geom_boxplot(alpha = 0.7, outlier.colour = NA) +
  geom_point(size = 0.5, position = position_jitterdodge(0.1), alpha = 0.2) +
  scale_fill_manual(NULL, values = c("deepskyblue3", "deepskyblue",
                                     "purple3", "purple",
                                     "red3", "red")) +
  scale_y_continuous(limits = c(0, 6), expand = c(0, 0)) +
  theme_minimal(base_size = 20) +
  labs(x = NULL) +
  theme(panel.grid.major.x = element_blank())

就我个人而言,我发现这种颜色的使用是无端且令人困惑的。呈现数据时,应使用颜色来清楚地识别分组,但如果分组已经在轴上明显,则无需这样做。我认为以下内容更干净、更优雅、更容易一目了然(并且色盲安全)

ggplot(df, aes(Race, Score, fill = Sex, group = interaction(Sex, Race))) +
  geom_boxplot(alpha = 0.5, outlier.colour = NA, width = 0.3,
               position = position_dodge(0.5)) +
  geom_point(size = 0.5, position = position_jitterdodge(0.05, 0, 0.5), 
             alpha = 0.2) +
  scale_fill_manual(NULL, values = c("gold", "deepskyblue4")) +
  scale_y_continuous(limits = c(0, 6), expand = c(0, 0)) +
  theme_minimal(base_size = 20) +
  labs(x = NULL) +
  theme(panel.grid.major.x = element_blank(), legend.position = "top")

© www.soinside.com 2019 - 2024. All rights reserved.