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

时间:2016-04-14 08:33:15

标签: r visualization hierarchical-clustering dendrogram dendextend

从问题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) 

生成树状图,如下所示:enter image description here 但是,我想将树枝朝向根部着色,直到当前分支中的所有树叶具有相同的标签。即使有一个不匹配的开关到默认的黑色。我希望得到的树形图看起来像enter image description here

我想要的与使用color_branches之类的

略有不同
x.clust.dend <-color_branches(x.clust.dend,k=3)

因为它根据自己的群集而不是基于某些外部标签而着色。

1 个答案:

答案 0 :(得分:1)

您正在寻找的功能是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)

enter image description here

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