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

在ggplot2中自定义拆分式图例:geom_tile绘图图例优化需求

拆分ggplot2热力图图例为独立子图例

要实现将热力图按Q1、Q2、Q3拆分为带各自标题的子图例,你需要借助ggnewscale包突破ggplot2单个审美仅对应一个图例的限制。以下是完整实现步骤:

1. 模拟数据(匹配你的宽→长格式结构)

set.seed(123)
# 模拟你的宽格式数据
wide_df <- data.frame(
  id = 1:5,
  Q1 = sample(c("yes", "no"), 5, replace = TRUE),
  Q2 = sample(c("never", "rarely", "often"), 5, replace = TRUE),
  Q3 = sample(c("cats", "dogs"), 5, replace = TRUE)
)

# 转换为长格式
library(reshape2)
long_df <- melt(wide_df, id.vars = "id")

2. 绘制多图例热力图

将长格式数据按变量拆分,通过new_scale_fill()创建独立的填充图例:

library(ggplot2)
library(ggnewscale)

# 拆分数据为三个子集
q1_data <- long_df[long_df$variable == "Q1", ]
q2_data <- long_df[long_df$variable == "Q2", ]
q3_data <- long_df[long_df$variable == "Q3", ]

ggplot() +
  # Q1图层与图例
  geom_tile(data = q1_data, aes(x = id, y = variable, fill = value)) +
  scale_fill_discrete(name = "Q1") +
  
  # 重置填充审美,用于Q2
  new_scale_fill() +
  geom_tile(data = q2_data, aes(x = id, y = variable, fill = value)) +
  scale_fill_discrete(name = "Q2") +
  
  # 再次重置填充审美,用于Q3
  new_scale_fill() +
  geom_tile(data = q3_data, aes(x = id, y = variable, fill = value)) +
  scale_fill_discrete(name = "Q3") +
  
  # 基础样式调整
  labs(x = "样本ID", y = "问题") +
  theme_minimal() +
  theme(legend.box = "vertical", legend.position = "right")

自定义优化

如果需要指定每个图例的颜色,替换scale_fill_discrete()为scale_fill_manual()即可:

# 示例:为Q1自定义颜色
scale_fill_manual(name = "Q1", values = c("yes" = "#2ecc71", "no" = "#e74c3c"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 09:33:22