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

R语言:为热图添加独立响应变量列,观测分组与响应的相关性

为热图添加独立配色的侧边响应列

针对你的需求,这里提供两种实用方案,都能实现热图与侧边响应列的独立配色,且保留你已有的行聚类顺序:

方案一:使用pheatmap包(推荐,适合大型数据)

pheatmap原生支持行/列注释,无需手动调整布局,配色设置更灵活,适合处理800行的大型数据:

# 先安装并加载包(首次使用需安装)
install.packages("pheatmap")
library(pheatmap)

# 复用你的示例数据(添加随机种子保证可复现)
set.seed(123)
mydf <- as.matrix(data.frame(A = sample(10, 20, replace = T), 
                             B = sample(10, 20, replace = T),
                             C = sample(10, 20, replace = T),
                             D = sample(10, 20, replace = T),
                             E = sample(10, 20, replace = T)))

response <- sample(100, 20, replace = T)
mydf_order <- hclust(dist(mydf))$order

# 创建行注释数据框,行名需与排序后的矩阵一致
annot_row <- data.frame(Response = response[mydf_order])
rownames(annot_row) <- rownames(mydf[mydf_order,])

# 绘制热图与侧边响应列
pheatmap(mydf[mydf_order,], 
         Rowv = NA, Colv = NA, 
         labRow = as.character(mydf_order),
         annotation_row = annot_row,  # 绑定侧边响应注释
         color = colorRampPalette(c("blue", "white", "red"))(100),  # 热图配色
         annotation_colors = list(Response = colorRampPalette(c("green", "yellow", "orange"))(100)),  # 响应列独立配色
         gaps_col = 5)  # 可选:添加你需要的竖线(这里是第5列后分隔)

方案二:Base R 手动布局(无需额外包)

如果你不想安装新包,可以用layout手动拆分绘图区域,分别绘制热图和响应列:

set.seed(123)
mydf <- as.matrix(data.frame(A = sample(10, 20, replace = T), 
                             B = sample(10, 20, replace = T),
                             C = sample(10, 20, replace = T),
                             D = sample(10, 20, replace = T),
                             E = sample(10, 20, replace = T)))

response <- sample(100, 20, replace = T)
mydf_order <- hclust(dist(mydf))$order
mydf_sorted <- mydf[mydf_order,]
response_sorted <- response[mydf_order]

# 设置布局:左侧热图占90%宽度,右侧响应列占10%
layout(matrix(c(1,2), nrow=1), widths = c(9,1))

# 绘制热图,调整边距避免重叠
par(mar = c(5,4,4,0))
heatmap(mydf_sorted, Rowv = NA, Colv = NA, labRow = as.character(mydf_order), 
        margins = c(5,1))

# 绘制侧边响应列,调整边距适配
par(mar = c(5,0,4,2))
image(t(matrix(response_sorted, nrow=1)), 
      col = colorRampPalette(c("green", "yellow", "orange"))(100),
      axes = FALSE)
# 添加行标签
axis(4, at = seq(0,1,length.out=length(response_sorted)), 
     labels = as.character(mydf_order), las=2)
# 添加响应列标题
mtext("Response", side=4, line=2)

两种方案都能让你直观观测热图聚类分组与response变量的对应关系,且热图和响应列使用完全独立的配色方案,避免尺度差异带来的视觉干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 21:35:01