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

如何用ggplot仅将north区域的堆叠条形图改为灰度

仅修改ggplot堆叠条形图中指定区域的填充颜色

要实现仅将"north"区域的堆叠条设为灰度、其余区域保留原配色的需求,核心是让ggplot能区分不同区域下的q14分组,而非仅按q14统一配色。以下是适配大数据集的解决方案:

步骤说明

  1. 将填充映射从q14改为interaction(Region, q14),生成"区域-q14"的组合分组,确保每个区域的q14类别都能被单独设置颜色
  2. 自动生成颜色向量:匹配"north"区域的q14值为灰度,其余区域沿用原配色
  3. 调整图例,保持图例仅显示q14的两个类别,且颜色为原配色逻辑

完整代码

Region <- c("north", "south", "east", "west", "north", "south", "east", "west")
q14 <- c("5", "5", "5", "5", "4", "4", "4", "4")
N <- c(4342, 5325, 654, 1231, 3453, 234, 345, 5634)
Percentage <- c(72, 71, 68, 67, 21, 20, 18, 17)
df <- data.frame(Region, q14, N, Percentage)

# 生成填充分组的所有层级
fill_groups <- levels(interaction(df$Region, df$q14))

# 自动生成颜色向量:north区域用灰度,其余用原配色
fill_colors <- ifelse(
  grepl("north", fill_groups),
  # north区域:q14=5浅灰,q14=4深灰
  ifelse(grepl("5", fill_groups), "#e0e0e0", "#999999"),
  # 其他区域:沿用原配色
  ifelse(grepl("5", fill_groups), "#bbd6ad", "#63ab41")
)
names(fill_colors) <- fill_groups

ggplot(df, aes(x=Region, y=Percentage, fill=interaction(Region, q14), label=Percentage)) + 
  geom_bar(stat = "identity") +
  # 应用自定义颜色
  scale_fill_manual(
    values = fill_colors,
    # 图例仅显示q14的两个类别
    breaks = c(fill_groups[grepl("5", fill_groups)][1], fill_groups[grepl("4", fill_groups)][1]),
    labels = c("5", "4"),
    # 图例颜色强制显示原配色
    guide = guide_legend(override.aes = list(fill = c("#bbd6ad", "#63ab41")))
  ) +
  labs(fill = "q14") + # 重命名图例标题
  geom_text(position = position_stack(vjust = 0.5)) # 可选:添加百分比标签到条形内部

代码关键点

  • interaction(Region, q14):创建唯一的填充分组,让ggplot能识别"north-5"、"north-4"这类特定组合
  • grepl函数:自动匹配包含"north"或"5"/"4"的分组,无需手动枚举所有区域,适配大数据集
  • guide_legend(override.aes):确保图例显示的是原配色,而非north区域的灰度,避免图例混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:07:23