在 complexheatmap 中将其用于 cluster_rows 时,外部树状图不会保持相同的形式

External dendrogram does not keep the same formation when using it for cluster_rows in complexheatmap

我正在尝试使用 ComplexHeatmap 库创建带有外部树状图的热图。

df <- data.frame(genes=c("G1","G2","G3","G4","G5","G6","G7","G8","G9","G10",
                         "G11","G1","G12","G4","G15","G6","G17","G8","G1","G2"),
                 rel=c("A111SD","G422ER","A112SA","B457EE","B33","N124A","F124A",
                       "G900GG","I332LP","I332LO",
                       "M332LP","A322TR","C14SA","B467ET","Z653","R124T","F334A",
                       "G901GZ","R330TP","L982LP"))
df_dist <- stringdist::stringdistmatrix(df$rel,useNames = T)
df_hclust <- hclust(df_dist)                 
plot(df_hclust)

df$Id <- seq.int(nrow(df))
df <- spread(df,genes,Id)
rownames(df) <- df$rel
df$rel<- NULL
df[!is.na(df)] <- 1
df[is.na(df)] <- 0

if (!require("BiocManager", quietly = TRUE))
  install.packages("BiocManager")

BiocManager::install("ComplexHeatmap")
library(ComplexHeatmap)

Heatmap(as.matrix(df),cluster_rows = df_hclust,cluster_columns = F)

创建的热图与使用 plot() 构建的热图具有不同的树状图。

问题是在所有转换之后:

df$Id <- seq.int(nrow(df))
df <- spread(df,genes,Id)
rownames(df) <- df$rel
df$rel<- NULL
df[!is.na(df)] <- 1
df[is.na(df)] <- 0

data.framedf已经没有初始顺序了。 快速修复是添加以下行以恢复初始顺序:

df <- df[rownames(as.matrix(df_dist)),]

但是,我建议你避免对同一个变量重新赋值,因为它很容易导致这类问题。