你可以尝试将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))