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

如何生成相异矩阵热图并按聚类排序?R技术问询

解决分类变量聚类热图的两个问题

问题1:基于Daisy相异矩阵绘制热图(原生heatmap()兼容方案)

原生heatmap()确实要求输入为数值矩阵,而daisy()输出的是dist类对象,我们只需要把相异矩阵转换成对称数值矩阵,再配合symm参数就能适配:

library(cluster)
# 生成Gower相异矩阵
daisy_dist <- daisy(your_data, metric = "gower")
# 转换为对称数值矩阵
dist_matrix <- as.matrix(daisy_dist)

# 绘制热图,开启对称模式匹配相异矩阵特性
heatmap(dist_matrix, 
        symm = TRUE, 
        distfun = function(x) as.dist(x), # 把矩阵转回dist格式供聚类使用
        hclustfun = hclust,
        main = "Gower相异矩阵热图",
        cexRow = 0.4, cexCol = 0.4) # 根据266个观测值调整字体大小,避免重叠

注意:热图中颜色越深代表相异度越高,如果想直观展示相似度,可以对矩阵取反(1 - dist_matrix,Gower距离本身范围是0-1,取反后数值越大相似度越高)。

问题2:添加聚类分组的可视化(图例/颜色标记)

原生heatmap()没有内置聚类图例功能,但我们可以手动在图上补充标记,步骤如下:

步骤1:先完成热图绘制并获取排序信息

# 先完成聚类和分组
hc <- hclust(daisy_dist, method = "ward.D2") # 替换成你实际用的聚类方法
cluster_groups <- cutree(hc, k = 4) # 分成4类

# 调整绘图边距,给左侧的聚类颜色条留空间
par(mar = c(5, 8, 4, 2))

# 绘制热图,同时获取行的实际排序顺序(热图会重新排序行)
heatmap_out <- heatmap(dist_matrix, 
                       symm = TRUE,
                       Rowv = as.dendrogram(hc),
                       Colv = "Rowv",
                       distfun = function(x) as.dist(x),
                       reorderfun = function(d, w) reorder(d, cluster_groups), # 用你的排序逻辑
                       cexRow = 0.4, cexCol = 0.4,
                       labRow = FALSE, # 隐藏行标签,避免和颜色条冲突
                       plot = FALSE) # 先不绘图,获取排序信息

# 实际绘图
heatmap(dist_matrix, 
        symm = TRUE,
        Rowv = as.dendrogram(hc),
        Colv = "Rowv",
        distfun = function(x) as.dist(x),
        reorderfun = function(d, w) reorder(d, cluster_groups),
        cexRow = 0.4, cexCol = 0.4,
        labRow = FALSE)

步骤2:添加聚类颜色条和图例

# 获取热图中实际的行排序
row_order <- rev(heatmap_out$rowInd)
# 对应排序后的聚类分组
ordered_clusters <- cluster_groups[row_order]

# 定义4个聚类的颜色
cluster_colors <- c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3")

# 在热图左侧添加聚类颜色条
image(x = 1, y = 1:length(row_order), 
      z = matrix(ordered_clusters, ncol=1),
      col = cluster_colors,
      axes = FALSE, xlab = "", ylab = "",
      add = TRUE)

# 在左侧添加聚类标签
axis(side = 2, at = seq(1, length(row_order), length.out=4), 
     labels = paste("Cluster", 1:4), 
     line = 4, cex.axis = 0.8)

# 在右上角添加图例
legend("topright", 
       legend = paste("Cluster", 1:4),
       fill = cluster_colors,
       cex = 0.8)

这样就能在热图上清晰区分4个聚类的分组了,颜色条和热图的行顺序完全对应。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:37:32