颜色树状图基于外部标签向根分支,直到标签匹配

Color dendrogram branches based on external labels uptowards the root until the label matches

根据问题 Color branches of dendrogram using an existing column,我可以为树状图的叶子附近的树枝着色。代码:

x<-1:100
dim(x)<-c(10,10)
set.seed(1)
groups<-c("red","red", "red", "red", "blue", "blue", "blue","blue", "red", "blue")
x.clust<-as.dendrogram(hclust(dist(x)))

x.clust.dend <- x.clust
labels_colors(x.clust.dend) <- groups
x.clust.dend <- assign_values_to_leaves_edgePar(x.clust.dend, value = groups, edgePar = "col") # add the colors.
x.clust.dend <- assign_values_to_leaves_edgePar(x.clust.dend, value = 3, edgePar = "lwd") # make the lines thick
plot(x.clust.dend) 

生成树状图,如下所示: 但是,我想为根部的分支上色,直到当前分支中的所有叶子都具有相同的标签。即使有一个单一的不匹配切换到黑色的默认颜色。我希望生成的树状图看起来像

我想要的与使用 color_branches 类似

没什么不同
x.clust.dend <-color_branches(x.clust.dend,k=3)

因为它根据自己的簇着色,而不是根据某些外部标签。

您要查找的函数是branches_attr_by_clusters。使用方法如下:

library(dendextend)

x <- 1:100
dim(x) <- c(10, 10)
set.seed(1)
groups <- c("red","red", "red", "red", "blue", "blue", "blue","blue", "red", "blue")
dend <- as.dendrogram(hclust(dist(x)))

clusters <- as.numeric(factor(groups, levels = c("red", "blue")))
dend2 <-
  branches_attr_by_clusters(dend , clusters, values = groups)
plot(dend2)

创建此函数最初是为了显示 dynamicTreeCut 的结果。参见 the vignette for another example