ComplexHeatmap绘制块注释报错:labels长度与切片数不匹配
问题解决:ComplexHeatmap 块注释长度不匹配报错
报错原因
- 顶部subtype注释问题:使用
anno_block时未先将样本按clust分组排序,导致程序无法正确划分切片;且unique(meta$clust)的类别数与实际连续分组后的切片数不匹配(原始数据中同clust的样本是分散的)。 - 行注释问题:左侧行注释对应热图的列(细胞类型),未明确指定切片划分规则,
anno_block无法识别切片数量。 - type注释问题:
group_block_anno函数依赖样本按type连续排列,否则无法准确定位块的位置。
修正后完整代码
library(ComplexHeatmap) library(GetoptLong) # 定义颜色向量 clust.col <- c("#003f5c", "#374c80","#7a5195","#bc5090","#ef5675","#ff764a", "#ffa600", "#84E4F7", "#FFB480","#FDFD86", "#00a692") meth.col <- c("#ff816f", "#ffbaae", "#f1f1f1", "#7e959e", "#004252") met.immune.col <- c("#01444f", "#01575e", "#0d6a6a", "#217d74", "#38917c", "#52a482", "#6eb786", "#8eca89", "#b0dc8c", "#d5ed90", "#fdfd96") # 关键步骤:按type和clust排序样本,确保同组样本连续 order_sample <- order(meta$type, meta$clust) met.resolv_sorted <- met.resolv[order_sample, ] meta_sorted <- meta[order_sample, ] # 构建顶部两层注释:type在上,subtype在下 # 1. Type注释:基于排序后的type确定切片范围 type_ranges <- rle(as.character(meta_sorted$type)) type_labels <- paste0("type ", type_ranges$values) type_fill <- c("#003f5c", "#ffa600")[match(type_ranges$values, c("1", "2"))] ha_type <- HeatmapAnnotation( "Type" = anno_block( gp = gpar(fill = type_fill), labels = type_labels, labels_gp = gpar(col = "white", fontsize = 12), width = unit(type_ranges$lengths / nrow(meta_sorted), "npc") ), height = unit(8, "mm") ) # 2. Subtype注释:基于排序后的clust确定切片和标签 clust_unique <- unique(meta_sorted$clust) clust_fill <- clust.col[match(clust_unique, unique(meta$clust))] ha_subtype <- HeatmapAnnotation( "Sub-Cluster" = anno_block( gp = gpar(fill = clust_fill), labels = clust_unique, labels_gp = gpar(col = "white", fontsize = 10) ), height = unit(10, "mm") ) # 合并顶部注释 ha <- ha_type + ha_subtype # 构建左侧行注释:对应热图的列(每个细胞类型一个块) la <- rowAnnotation( "Cell Type" = anno_block( gp = gpar(fill = met.immune.col), labels = colnames(met.resolv_sorted), labels_gp = gpar(col = "white", fontsize = 10), height = unit(rep(1, ncol(met.resolv_sorted)) / ncol(met.resolv_sorted), "npc") ), width = unit(20, "mm") ) # 绘制热图 pdf("Plots/heatmap_methylresolver.pdf", width = 12, height = 8) Heatmap( met.resolv_sorted, name = "SubClust", top_annotation = ha, left_annotation = la, column_title = NULL, show_row_names = FALSE ) dev.off()
说明
- 样本排序是核心:必须让同type、同clust的样本连续排列,确保
anno_block能正确识别切片数量,匹配标签长度。 - 顶部注释通过两层
HeatmapAnnotation叠加实现,无需额外调用group_block_anno函数,逻辑更清晰。 - 行注释通过指定
height参数,让每个细胞类型对应独立块,标签与列名完全匹配,彻底解决长度不匹配问题。
内容的提问来源于stack exchange,提问作者Anon
相关产品推荐
相关产品推荐

