如何在ComplexHeatmap顶部注释色块中央添加分组标签
解决方法
不用column_km的话,可通过**自定义注释(custom annotation)**实现手动指定列顺序下的分组标签添加,核心思路是先定位每个分组的列区间,再在对应色块中央绘制标签。以下提供两种可行方案:
方案一:整合色块与标签的自定义注释
直接替换原有简单注释,在自定义函数中同时绘制分组色块和标签:
# 1. 先获取每个分组对应的列索引及中心位置 group_cols <- split(seq_along(order.ffpe$V1), order.ffpe$V1) group_centers <- sapply(group_cols, function(x) mean(x)) group_names <- names(group_cols) group_colors <- c("Group1" = "#c2a5cf", "Group2" = "#a6dba0", "Group3" = "#fdae61") # 2. 定义自定义注释函数 custom_group_anno <- function(index) { pushViewport(viewport(xscale = c(0, length(index)), yscale = c(0, 1))) # 遍历每个分组,绘制色块+标签 for(g in group_names) { cols <- group_cols[[g]] # 绘制分组色块 grid.rect(x = (min(cols)-0.5 + max(cols)+0.5)/2, width = max(cols)-min(cols)+1, y = 0.5, height = 1, gp = gpar(fill = group_colors[g], col = NA)) # 在色块中央绘制标签 grid.text(g, x = group_centers[g], y = 0.5, gp = gpar(fontsize = 10)) } popViewport() } # 3. 创建顶部注释 top.ann.ffpe <- HeatmapAnnotation( Group = anno_custom(custom_group_anno), show_legend = FALSE, show_annotation_name = FALSE, simple_anno_size = unit(0.2, "cm") )
方案二:保留原有色块注释,叠加文本注释
如果想保留原有简单注释的逻辑,可新增一层仅绘制文本的自定义注释:
# 1. 计算每个分组的中心位置 group_centers <- sapply(split(seq_along(order.ffpe$V1), order.ffpe$V1), mean) group_names <- names(group_centers) # 2. 定义文本注释函数 text_anno <- function(index) { pushViewport(viewport(xscale = c(0, length(index)), yscale = c(0, 1))) for(i in seq_along(group_names)) { grid.text(group_names[i], x = group_centers[i], y = 0.5, gp = gpar(fontsize = 10)) } popViewport() } # 3. 创建叠加式顶部注释 top.ann.ffpe <- HeatmapAnnotation( Group = order.ffpe$V1, Text = anno_custom(text_anno, height = unit(0.2, "cm")), # 高度与色块注释一致 show_legend = FALSE, show_annotation_name = FALSE, simple_anno_size = unit(0.2, "cm"), col = list(Group = c("Group1" = "#c2a5cf", "Group2" = "#a6dba0", "Group3" = "#fdae61")) )
说明
- 两种方案均基于
grid包的绘图函数实现,无需依赖聚类逻辑 - 可通过调整
gpar(fontsize)参数修改标签大小,simple_anno_size调整注释高度
内容的提问来源于stack exchange,提问作者user2300940
相关产品推荐
相关产品推荐

