【问题标题】:R dendrogram by cluster集群的 R 树状图
【发布时间】:2017-03-24 13:51:19
【问题描述】:

我正在使用 R 绘制层次聚类的树状图。

我已经实现了约 3000 个元素的层次聚类。对应的树的情节显然超级乱。使用 cutree 函数将这 3000 个元素聚集在 20 个组中。我想要的是按集群绘制树(即在每个集群起源的节点处被截断,由集群适当地标记 => 具有 20 个终端叶子的树)。

谢谢

哦。

【问题讨论】:

标签: r hierarchical-clustering dendrogram


【解决方案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))

如果您想用cutree 定义的集群标签来标记分支,您需要获取标签(通过重新排序cutree 结果)并找到将它们放在x axis 旁边的位置。这些信息可以通过“分解”树状图得到所需的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))

【讨论】:

  • 谢谢凯丝。但是,与 cutree 函数相比,您如何判断哪个集群是哪个集群?你会如何标记情节?
  • @Oselm 请查看编辑以放置集群标签
猜你喜欢
  • 1970-01-01
  • 2015-07-05
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 2019-02-13
  • 2020-03-15
  • 1970-01-01
相关资源
最近更新 更多