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

求助:使用dendextend的color_branches后热图分支颜色异常

问题

尝试使用dendextend包的color_branches()函数为ComplexHeatmap绘制的热图树状图分支上色时,出现部分叶节点呈现混合颜色的异常。相关代码如下:

column_dend = hclust(dist(t(data)))
row_dend = hclust(dist((data)))
row_dend = color_branches(row_dend, k = 2)

ht<-Heatmap(as.matrix(data),
            name = "legend",
            cluster_rows = row_dend,
            cluster_columns = column_dend,
            na_col = 'black',
            column_names_rot = 45,
            col = circlize::colorRamp2(c(-1, 0, 1), c("#56B4E9", "#FFFFFF", "#FF7400")),
            show_row_names = F,
            show_column_names = F,
            use_raster = F,
            heatmap_width = unit(1.5, "cm")*ncol(data),
            column_names_gp = grid::gpar(fontsize = 13),
            row_names_gp = grid::gpar(fontsize = 1))

ht = draw(ht)
原因分析与解决方法
  • 核心原因:dendextend::color_branches()返回的是dendrogram对象,ComplexHeatmap的cluster_rows参数虽支持传入该类型,但二者在树状图渲染的细节处理上存在兼容性问题——color_branches()会给分支添加颜色属性,而ComplexHeatmap在渲染叶节点附近的短分支时,会出现颜色叠加绘制的情况,最终导致叶节点呈现混合色。

  • 解决办法:

    1. 改用ComplexHeatmap原生分支上色方式,无需依赖dendextend:
      绘制热图后,通过decorate_row_dend()函数为行树状图分支上色,示例代码如下:
      column_dend = hclust(dist(t(data)))
      row_dend = hclust(dist(data))
      
      ht<-Heatmap(as.matrix(data),
                  name = "legend",
                  cluster_rows = row_dend,
                  cluster_columns = column_dend,
                  na_col = 'black',
                  column_names_rot = 45,
                  col = circlize::colorRamp2(c(-1, 0, 1), c("#56B4E9", "#FFFFFF", "#FF7400")),
                  show_row_names = F,
                  show_column_names = F,
                  use_raster = F,
                  heatmap_width = unit(1.5, "cm")*ncol(data),
                  column_names_gp = grid::gpar(fontsize = 13),
                  row_names_gp = grid::gpar(fontsize = 1))
      
      ht = draw(ht)
      # 为行树状图分支上色
      decorate_row_dend("ht", {
        dend = current_dendrogram()
        dend = color_branches(dend, k = 2)
        grid::grid.draw(dend)
      })
      
    2. 若坚持使用dendextend处理结果,可调整树状图的叶节点悬挂长度,避免短分支导致的颜色叠加:
      row_dend = hclust(dist(data))
      row_dend = as.dendrogram(row_dend)
      row_dend = color_branches(row_dend, k = 2)
      # 调整叶节点悬挂长度,数值可按需调整
      row_dend = hang.dendrogram(row_dend, hang = 0.1)
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 22:05:29