You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot箱线图颜色与代码设置不符,寻求解决方法

解决ggplot箱线图颜色不匹配指定值的问题

你的代码中指定了十六进制颜色但输出显示默认的红、蓝、绿,核心原因是:ggplot将你映射到fill/color美学的box_color、point_color等列,当作分类变量处理,自动分配了默认的离散调色板,而非直接使用你指定的颜色值。

修复方案

只需在绘图代码中添加scale_fill_identity()和scale_color_identity(),告诉ggplot直接使用映射变量的数值(即你定义的十六进制颜色码)作为颜色:

修改后的完整绘图代码:

# Create the plot
p1 <- filtered_cAMP_fen %>%
  filter(Assay_type == 'cAMP', Cell_Line %in% Plot_Line, exclusion == 'no', Treatment == treatments_for_plot) %>%
  ggplot(aes(x = as.factor(race_gen), y = cAMP_normed_meoh)) +
  geom_boxplot(aes(fill = box_color)) +
  geom_point(aes(fill = point_color, color = point_border),
             position = position_jitterdodge(jitter.width = 0.2, dodge.width = 0.75),
             shape = 21, size = 6) +
  # 关键:添加这两行,让ggplot直接使用指定的颜色值
  scale_fill_identity() +
  scale_color_identity() +
  theme(legend.position = "none",
        panel.background = element_rect(fill = "#FFFFFF"),
        panel.grid = element_blank(),
        axis.ticks.x = element_blank(),
        axis.text.x = element_text(size = 14),
        axis.text.y = element_text(size = 14),
        axis.title.y = element_text(size = 14),
        axis.line = element_line(color = "black"))

print(p1)

可选优化:简化颜色赋值代码

你可以用更简洁的逻辑替代重复的case_when条件,让代码更易维护:

filtered_cAMP_fen <- filtered_cAMP_fen %>%
  mutate(
    point_color = ifelse(race_gen %in% c("White_fem", "White_male"), "#000000", "#FFFFFF"),
    point_border = ifelse(race_gen %in% c("White_fem", "White_male", "Asian_fem", "Asian_male"), "#000000", "#FFFFFF"),
    box_color = case_when(
      race_gen %in% c("White_fem", "White_male") ~ "#FFFFFF",
      race_gen %in% c("Black_fem", "Black_male") ~ "#000000",
      race_gen %in% c("Asian_fem", "Asian_male") ~ "#8B0000"
    )
  )

内容的提问来源于stack exchange,提问作者Detlef Obal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 14:56:06