如何修改R语言热图的距离计算与聚类连接方式?
修改热图的距离计算与聚类方法
问题原因
你之前设置hclustfun="single"失败,是因为heatmap()的distfun和hclustfun参数需要传入函数对象,而非字符串。默认的distfun是function(x) dist(x, method="euclidean"),hclustfun是function(x) hclust(x, method="complete"),必须通过自定义函数来修改方法。
完整示例代码
先补充数据集转换步骤(原代码中milk_matrix需要从milk数据框转为矩阵),再修改距离和聚类方法:
library("flexclust") data(milk) # 将数据框转换为矩阵 milk_matrix <- as.matrix(milk) # 修改为曼哈顿距离(Manhattan)+ 单链接聚类(Single linkage) hm3 <- heatmap(milk_matrix, scale="column", main="Heat map of the Composition of Mammals' Milk", xlab= "Nutrient", ylab = "Animal", cexRow = 0.6, cexCol = 1.1, col=heat.colors(10), # 自定义距离函数:曼哈顿距离 distfun = function(x) dist(x, method = "manhattan"), # 自定义聚类函数:单链接法 hclustfun = function(x) hclust(x, method = "single")) legend(x= "bottomright", legend=c("min", "med", "max"), cex = 0.6, fill=heat.colors(3))
其他可选非默认组合
如果想尝试其他设置,可替换以下参数:
- 距离方法:可选
"manhattan"、"maximum"、"canberra"、"binary"等(来自dist()函数的method参数) - 聚类方法:可选
"average"、"ward.D2"、"median"、"centroid"等(来自hclust()函数的method参数)
比如换成皮尔逊相关距离+平均链接聚类:
# 自定义皮尔逊相关距离函数 cor_dist <- function(x) as.dist(1 - cor(t(x))) hm3 <- heatmap(milk_matrix, scale="column", main="Heat map (Correlation Distance + Average Linkage)", xlab= "Nutrient", ylab = "Animal", cexRow = 0.6, cexCol = 1.1, col=heat.colors(10), distfun = cor_dist, hclustfun = function(x) hclust(x, method = "average"))
内容的提问来源于stack exchange,提问作者Rosie Lomas
相关产品推荐
相关产品推荐

