如何手动聚类热图行?基因类型分组热图绘制方案咨询
手动分组基因绘制热图的解决方案
下面提供两种常用R包的实现方法,核心思路是关闭自动行聚类,手动按预设分组排序基因,并添加分组注释:
方法一:使用pheatmap包
pheatmap是绘制热图的常用工具,支持自定义行顺序和分组注释:
- 准备数据与分组信息
# 模拟表达矩阵(行=基因,列=样本) set.seed(123) expr_matrix <- matrix(rnorm(10*6), nrow=10, rownames = c(paste0("PF_", 1:5), paste0("ECM_", 1:5))) colnames(expr_matrix) <- paste0("Sample_", 1:6) # 手动定义基因分组 gene_groups <- factor(c(rep("Protein Folding", 5), rep("ECM Component", 5)), levels = c("Protein Folding", "ECM Component"))
- 按分组排序基因
# 按分组顺序重新排列表达矩阵的行 sorted_expr <- expr_matrix[order(gene_groups), ] # 同步更新分组信息的顺序 sorted_groups <- gene_groups[order(gene_groups)]
- 绘制带分组注释的热图
library(pheatmap) # 创建分组注释的dataframe annotation_row <- data.frame(Group = sorted_groups) rownames(annotation_row) <- rownames(sorted_expr) # 绘制热图,关闭行聚类 pheatmap(sorted_expr, cluster_rows = FALSE, # 关闭自动行聚类 annotation_row = annotation_row, # 添加行分组注释 show_rownames = TRUE, main = "Gene Expression Heatmap with Manual Groups")
方法二:使用ComplexHeatmap包
ComplexHeatmap功能更灵活,支持添加分组分隔线、自定义注释样式:
- 数据准备(同方法一)
- 绘制热图
library(ComplexHeatmap) # 创建分组注释 ha <- rowAnnotation(Group = sorted_groups, col = list(Group = c("Protein Folding" = "#1f77b4", "ECM Component" = "#ff7f0e"))) # 绘制热图,关闭行聚类,添加注释和分组线 Heatmap(sorted_expr, cluster_rows = FALSE, row_names_side = "left", top_annotation = NULL, right_annotation = ha, row_gap = unit(2, "mm"), # 组间添加间隙 heatmap_legend_param = list(title = "Expression"), main = "Manual Grouped Gene Heatmap")
关键注意点
- 必须设置
cluster_rows = FALSE,避免自动聚类打乱手动分组 - 若需要保留样本的聚类,可保留
cluster_cols = TRUE(默认开启) - 分组注释的颜色可根据需求自定义
内容的提问来源于stack exchange,提问作者Maria Faleeva
相关产品推荐
相关产品推荐

