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

R语言热图树状图重排:分组聚类后调整样本顺序

解决热图分组排序问题:组内聚类+指定组间顺序

要实现**先展示所有normal样本(组内按相似度聚类),再展示所有KIRP样本(组内同样按相似度聚类)**的效果,核心思路是拆分分组做组内聚类,再合并指定顺序,具体步骤和代码如下:

步骤说明

  1. 按分组拆分样本,分别对normal和KIRP组计算组内相似度并聚类
  2. 提取两组聚类后的样本顺序,按normal在前,KIRP在后的规则合并
  3. 用合并后的顺序重排表达矩阵,绘制热图时关闭全局列聚类

代码示例(以pheatmap为例)

假设你已有:

  • 表达矩阵expr_mat(行=基因,列=样本)
  • 样本分组向量sample_groups(命名向量,值为"normal"/"KIRP",名字对应样本名)
# 1. 拆分两组样本
normal_samples <- names(sample_groups)[sample_groups == "normal"]
kirp_samples <- names(sample_groups)[sample_groups == "KIRP"]

# 2. 组内聚类:计算距离+层次聚类,提取组内样本顺序
# Normal组
normal_dist <- dist(t(expr_mat[, normal_samples]), method = "euclidean") # 转置后计算样本间距离
normal_hclust <- hclust(normal_dist, method = "ward.D2") # 聚类方法可按需调整
normal_order <- normal_samples[normal_hclust$order]

# KIRP组
kirp_dist <- dist(t(expr_mat[, kirp_samples]), method = "euclidean")
kirp_hclust <- hclust(kirp_dist, method = "ward.D2")
kirp_order <- kirp_samples[kirp_hclust$order]

# 3. 合并自定义列顺序:normal在前,KIRP在后
custom_col_order <- c(normal_order, kirp_order)

# 4. 重排表达矩阵
expr_mat_reordered <- expr_mat[, custom_col_order]

# 5. 绘制热图(关闭全局列聚类,保留组内聚类后的顺序)
library(pheatmap)
pheatmap(expr_mat_reordered,
         cluster_cols = FALSE, # 禁止全局列聚类,使用自定义顺序
         annotation_col = data.frame(Group = sample_groups[custom_col_order]), # 添加分组注释
         show_colnames = TRUE) # 按需显示样本名

用ComplexHeatmap实现的版本

如果使用ComplexHeatmap包,逻辑一致:

library(ComplexHeatmap)

# 复用上述步骤得到的custom_col_order
expr_mat_reordered <- expr_mat[, custom_col_order]

# 创建分组注释
col_annotation <- HeatmapAnnotation(Group = sample_groups[custom_col_order])

# 绘制热图
Heatmap(expr_mat_reordered,
        cluster_columns = FALSE,
        top_annotation = col_annotation)

关键说明

  • 聚类方法(hclust的method参数)和距离计算方法(dist的method参数)可根据你的数据类型调整(比如用"pearson"相关性替代欧氏距离)
  • 关闭cluster_cols参数是为了强制使用我们自定义的组内聚类+组间顺序,避免全局聚类打乱分组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:28:06