按簇的R树形图

时间:2017-03-24 13:51:20

标签: r hierarchical-clustering dendrogram

我使用R绘制层次聚类的树形图。

我已经实现了~3000个元素的层次聚类。相应树的情节显然超级凌乱。这些3000个元素使用cutree函数聚类在20个组中。我想要的是按簇绘制树(即在每个簇发起的节点处截断,由cluster =>具有20个终端叶的树)。

由于

0

1 个答案:

答案 0 :(得分:1)

您可以尝试将ylim缩减到相应的高度:

随机数据:

set.seed(123)
testdata <- matrix(rnorm(300), ncol=3)
testcah <- hclust(dist(testdata))

从第一次到最后一次合并,cah的每一步的高度都在testdata$heights。例如,如果您想要5个组,则需要知道最后一个高度之前的第4个:

floor_y <- rev(testcah$height)[5-1]

然后,将您的对象作为树形图,您只能在您需要的部分上绘制它:

testdend <- as.dendrogram(testcah)
plot(testdend, ylim=c(floor_y, attributes(testdend)$height))

如果您想使用群集标记分支&#39;标签,由cutree定义,您需要获取标签(通过重新排序cutree结果)并找到将它们放在x axis的位置。这些信息可以通过&#34;分解&#34;树形图以完成所需的midpoints

首先,获取(全部)叶子的标签:

testlab <- cutree(testcah, 5)[testcah$order]

然后我们使用递归函数来找到位于所需高度的子树形图的中点:

find_x <- function(dendro, ordrecah, cutheight){
            if(!is.null(attributes(dendro)$leaf)) { # if the dendrogram is a leaf, just get its position in the global dendrogram
                return(which(ordrecah==attributes(dendro)$label))
            } else {
                if(attributes(dendro)$height<cutheight){ # if we're under the height threshold, get the midpoint
                    return(attributes(dendro)$midpoint)
                } else { # if we're above the height threshold, pass the function on the 2 subparts of the dendrogram
                    return(c(find_x(dendro[[1]], ordrecah, cutheight), find_x(dendro[[2]], ordrecah, cutheight)))
                }
            }
           }

因此我们可以通过以下方式获得中点或叶位:

test_x <- find_x(testdend, testcah$order, floor_y)

但是中点对应于最左边的叶子和节点之间的距离,因此,如果群集中有多个成员,我们需要将距离从1添加到最左边的叶子。

length_clus <- rle(testlab)$lengths # get the number of members by cluster
test_x[length_clus > 1] <- (test_x + head(c(1, cumsum(length_clus)+1), -1))[length_clus > 1]

最后,将标签放在图上:

mtext(side=1, at=test_x, line=0, text=unique(testlab))

enter image description here