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

如何在R的ComplexHeatmap中使用Bray-Curtis距离配合ward.D2聚类

解决方案

ComplexHeatmap完全支持传入预计算的距离对象或自定义距离计算函数,不需要替换为其他热图包,以下是可直接运行的修正方案:

步骤1:加载依赖包

library(vegan)
library(ComplexHeatmap)
library(grid)

步骤2:两种实现方式

方式1:预计算距离矩阵(灵活可控)

和你原有思路一致,仅修正了未定义fontsize的问题,同时补充了ward.D2适配的可选处理:

# 模拟鱼类计数数据(实际使用时替换为你的真实数据即可)
data <- matrix(rpois(30, 0.9), ncol = 6, nrow = 5)
colnames(data) <- c("2004W", "2004D", "2005W", "2005D", "2006W", "2006D")

# 定义字体大小参数(原代码未定义导致报错)
fontsize <- 1.1

# 预计算Bray-Curtis距离
d1 <- vegdist(log(data+1), method = "bray") 
d2 <- vegdist(t(log(data+1)), method = "bray")

# 【可选,统计更严谨】严格适配ward.D2的统计假设,使用平方后的距离
# d1 <- as.dist(as.matrix(d1)^2)
# d2 <- as.dist(as.matrix(d2)^2)

# 绘制热图
Heatmap(data,
  row_names_side = "left",
  row_dend_side = "left",
  column_names_side = "bottom",
  row_names_gp = gpar(cex=fontsize, fontface = "bold"),
  column_names_gp = gpar(cex=0.9, fontface = "bold"),
  row_dend_width = unit(4, "cm"),
  column_dend_height = unit(3, "cm"),
  rect_gp = gpar(col = "grey"),
  column_title = "Year/Season",
  column_names_rot = 35,
  row_title = "Site",
  clustering_distance_rows = d1,
  clustering_distance_columns = d2,
  clustering_method_rows = "ward.D2",
  clustering_method_columns = "ward.D2",
  row_km = 3,
  column_km = 4
)

方式2:直接传入自定义距离函数(代码更简洁)

不需要提前计算距离对象,函数会自动对行列数据计算Bray-Curtis距离:

data <- matrix(rpois(30, 0.9), ncol = 6, nrow = 5)
colnames(data) <- c("2004W", "2004D", "2005W", "2005D", "2006W", "2006D")
fontsize <- 1.1

Heatmap(data,
  row_names_side = "left",
  row_dend_side = "left",
  column_names_side = "bottom",
  row_names_gp = gpar(cex=fontsize, fontface = "bold"),
  column_names_gp = gpar(cex=0.9, fontface = "bold"),
  row_dend_width = unit(4, "cm"),
  column_dend_height = unit(3, "cm"),
  rect_gp = gpar(col = "grey"),
  column_title = "Year/Season",
  column_names_rot = 35,
  row_title = "Site",
  # 直接传入距离计算函数
  clustering_distance_rows = function(x) vegdist(log(x+1), method = "bray"),
  clustering_distance_columns = function(x) vegdist(t(log(x+1)), method = "bray"),
  clustering_method_rows = "ward.D2",
  clustering_method_columns = "ward.D2",
  row_km = 3,
  column_km = 4
)

注意事项

  • 若你的数据不需要做log转换,删除代码中的log( +1)逻辑即可
  • 模拟数据仅为演示用,你的真实47行站点、32列季节数据完全支持上述参数设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 13:36:00