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

ggplot中为mobility_categories不同值设置差异化颜色问题

解决ggplot中给mobility_categories设置自定义颜色的问题

你的代码核心问题是没有将fill映射到mobility_categories,导致scale_fill_manual无法识别需要上色的变量,同时比例计算的分组逻辑也需要调整以匹配需求。

修正后的代码

DiabetesAndCRC3_only_rectal %>% 
  filter(!is.na(mobility_categories)) %>% 
  ggplot(aes(x = factor(mobility_categories))) +
  # 关键:添加fill映射,并设置group=1确保分面内计算整体占比
  geom_bar(aes(y = after_stat(prop), fill = mobility_categories),
           stat = "count", width = 0.8, group = 1) +
  geom_text(aes(label = scales::percent(after_stat(prop)), y = after_stat(prop)),
            stat = "count", vjust = -.5, group = 1) +
  facet_grid(~Diabetes_status) +
  scale_y_continuous(labels = scales::percent, expand = c(0,0), limits = c(0,0.5)) +
  # 自定义每个mobility_categories对应的颜色
  scale_fill_manual(values = c(
    "<24" = "#2ecc71", 
    ">24" = "#3498db", 
    ">36" = "#f39c12", 
    ">48" = "#e74c3c"
  ))

关键调整说明

  1. 添加fill映射:在geom_bar的aes中加入fill = mobility_categories,让ggplot明确按该变量区分柱子颜色,这是scale_fill_manual生效的前提。
  2. 调整分组逻辑:设置group = 1,确保每个分面(对应一类Diabetes_status)内,计算的是每个mobility_categories占该分面总样本的比例,避免分组逻辑混乱导致的比例错误。
  3. 自定义颜色:在scale_fill_manual的values参数中,为每个mobility_categories的取值指定对应的颜色代码,可根据需求替换为你需要的颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:05:36