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

ggplot2中显示图例全部项(含缺失类别)以实现双图共享图例

解决共享图例及缺失类别颜色问题

核心问题修正

你的代码中虽指定drop=FALSE保留所有因子水平,但未将颜色与类别显式绑定,导致缺失类别的图例颜色异常。只需把颜色向量转为命名向量,就能确保每个类别(无论数据中是否存在)对应正确颜色,同时为双图共享图例打好基础。

修正后完整代码(含双图共享图例)

library(ggplot2)
library(RColorBrewer)
library(patchwork) # 用于组合图形并共享图例

# 定义所有填充类别
fill_levels <- c(
  "< 0", "0 - 5", "5 - 7", "7 - 10", 
  "10 - 15", "15 - 18", "18 - 20", 
  "20 - 21", "21 - 22", "22 - 23", 
  "23 - 24", "24 - 25", "25 - 26", "> 26"
)

# 生成颜色并转为命名向量(关键:颜色与类别一一绑定)
my_colors <- colorRampPalette(RColorBrewer::brewer.pal(11, "RdYlBu"))(14)
names(my_colors) <- fill_levels

# 第一个数据集(仅包含部分类别)
df1 <- data.frame(
  day = rep(1:5, each = 5),
  hour = rep(1:5, times = 5),
  tmp_bnd = sample(c("< 0", "0 - 5", "5 - 7", "7 - 10"), 25, replace = TRUE)
)
df1$tmp_bnd <- factor(df1$tmp_bnd, levels = fill_levels)

# 第二个数据集(包含另一部分类别)
df2 <- data.frame(
  day = rep(1:5, each = 5),
  hour = rep(1:5, times = 5),
  tmp_bnd = sample(c("10 - 15", "15 - 18", "> 26"), 25, replace = TRUE)
)
df2$tmp_bnd <- factor(df2$tmp_bnd, levels = fill_levels)

# 定义统一的绘图模板
plot_template <- function(data) {
  ggplot(data, aes(x = day, y = hour, fill = tmp_bnd)) +
    geom_tile(color = "white") +
    scale_fill_manual(
      values = my_colors,        
      breaks = fill_levels,      
      labels = fill_levels,      
      drop = FALSE               
    ) +
    theme_minimal() +
    theme(
      legend.title = element_text(size = 10),
      legend.key.size = unit(0.8, "cm")
    )
}

# 生成两个图并共享图例
p1 <- plot_template(df1)
p2 <- plot_template(df2)

# 使用patchwork组合,共享图例
p1 + p2 + plot_layout(guides = "collect") & theme(legend.position = "bottom")

关键说明

  1. 命名颜色向量:names(my_colors) <- fill_levels让每个颜色明确对应一个类别,避免因数据缺失类别导致的颜色匹配错误。
  2. 统一绘图模板:将重复的绘图代码封装成函数,确保两个图使用完全一致的填充尺度,保证图例共享时颜色统一。
  3. 共享图例实现:借助patchwork的plot_layout(guides = "collect"),自动合并两个图的图例,避免重复显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:34:56