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

如何在R的ComplexHeatmap中显示离散值图例中的缺失值?

如何让ComplexHeatmap图例保留缺失的离散值标签

问题背景

使用ComplexHeatmap展示1-10的离散值矩阵时,因部分值(7、8、9)被设为NA或替换为1,图例中自动隐藏了这些缺失值的对应条目,希望强制让1-10所有值都显示在图例里。

原代码如下:

library(ComplexHeatmap)

discrete_mat = matrix(sample(1:10, 100, replace = TRUE), 10, 10)
discrete_mat[discrete_mat==7]<-NA
discrete_mat[discrete_mat==8]<-1
discrete_mat[discrete_mat==9]<-1

pal <- colorRampPalette(c("skyblue", "yellow", "orange", "darkred"))(10)
colors = structure(pal, names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))

Heatmap(discrete_mat,
    name = "Legend", 
    col = colors,
    cluster_rows = FALSE, # 关闭行聚类
    cluster_columns = FALSE
)

解决方案

默认情况下,ComplexHeatmap的图例只会展示矩阵中实际存在的离散值。要强制显示所有1-10的标签,只需在Heatmap()函数中添加heatmap_legend_param参数,手动指定图例的刻度和标签为所有预设的颜色名称即可。

修改后的完整代码:

library(ComplexHeatmap)

discrete_mat = matrix(sample(1:10, 100, replace = TRUE), 10, 10)
discrete_mat[discrete_mat==7]<-NA
discrete_mat[discrete_mat==8]<-1
discrete_mat[discrete_mat==9]<-1

pal <- colorRampPalette(c("skyblue", "yellow", "orange", "darkred"))(10)
colors = structure(pal, names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))

Heatmap(discrete_mat,
    name = "Legend", 
    col = colors,
    cluster_rows = FALSE, 
    cluster_columns = FALSE,
    # 强制指定图例显示所有1-10的标签
    heatmap_legend_param = list(
        at = names(colors),
        labels = names(colors)
    )
)

关键说明

  • heatmap_legend_param$at:指定图例要显示的刻度值,这里直接用颜色向量的名称(即1-10)
  • heatmap_legend_param$labels:对应刻度的显示标签,和at保持一致即可

这样修改后,即使矩阵中没有7、8、9这些值,图例也会完整显示1-10所有条目及其对应颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:30:10