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

使用scale_*_manual时在图例中保留未使用的因子水平

问题描述

我尝试将fill美学映射到有序因子,但数据中缺少部分因子水平。我已经通过scale_fill_manual()为所有因子水平分配了填充色,但图例中缺失水平的颜色未正确显示——虽然drop = FALSE参数保留了所有因子水平,但未出现的水平显示为缺失的灰色,而非我指定的颜色。如何让图例完整反映我为所有刻度指定的颜色映射?

附带代码及当前图例效果:

library(ggplot2)

factor_data <- 
  data.frame(
    my_factor = 
      factor("Level three", 
             levels = c("Level one", "Level two", "Level three", "Level four", "Level five"))
  )

fill_colours <- colorRampPalette(c("green", "white"))(5)

fill_colours
#> [1] "#00FF00" "#3FFF3F" "#7FFF7F" "#BFFFBF" "#FFFFFF"

ggplot(factor_data) +
  geom_bar(
    aes(x = 1, fill = my_factor),
    colour = "black", linewidth = 0.8) +
  scale_fill_manual(name = "IMD Rank (England)",
                    values = fill_colours,
                    drop = FALSE) + 
  ggtitle("Deprivation of LLSOA")

当前图例:未出现的因子水平显示为灰色

解决方法

方案1:强制覆盖图例样式(无需修改原始数据)

ggplot会默认将数据中未出现的因子水平标记为"缺失",导致图例用灰色占位。我们可以通过guide_legend()的override.aes参数,强制指定图例中每个水平的填充色,忽略数据是否包含该水平。

修改后的代码:

library(ggplot2)

factor_data <- 
  data.frame(
    my_factor = 
      factor("Level three", 
             levels = c("Level one", "Level two", "Level three", "Level four", "Level five"))
  )

fill_colours <- colorRampPalette(c("green", "white"))(5)

ggplot(factor_data) +
  geom_bar(
    aes(x = 1, fill = my_factor),
    colour = "black", linewidth = 0.8) +
  scale_fill_manual(
    name = "IMD Rank (England)",
    values = fill_colours,
    drop = FALSE,
    # 强制图例所有水平使用指定填充色
    guide = guide_legend(override.aes = list(fill = fill_colours))
  ) + 
  ggtitle("Deprivation of LLSOA")

方案2:构造包含所有因子水平的完整数据

如果希望图表底层数据包含所有因子水平(即使计数为0),可以手动构造完整数据框,将未出现的水平计数设为0,这样ggplot会自动识别所有水平并应用指定颜色。

代码示例:

library(ggplot2)

# 生成包含所有因子水平的完整数据
full_factor_data <- data.frame(
  my_factor = factor(
    c("Level one", "Level two", "Level three", "Level four", "Level five"),
    levels = c("Level one", "Level two", "Level three", "Level four", "Level five")
  ),
  count = c(0, 0, 1, 0, 0) # 未出现的水平计数设为0
)

fill_colours <- colorRampPalette(c("green", "white"))(5)

ggplot(full_factor_data) +
  geom_bar(
    aes(x = 1, fill = my_factor, y = count),
    stat = "identity", # 使用自定义计数而非自动统计
    colour = "black", linewidth = 0.8) +
  scale_fill_manual(
    name = "IMD Rank (England)",
    values = fill_colours,
    drop = FALSE
  ) + 
  ggtitle("Deprivation of LLSOA")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:57:07