gpt4 book ai didi

R基于k绘制上部树状图

转载 作者:行者123 更新时间:2023-12-03 15:53:14 26 4
gpt4 key购买 nike

我正在使用 hclust() 基于 R 中 20,000 行 x 169 列的数据集对距离矩阵进行聚类。当我将聚类对象转换为树状图并绘制整个树状图时,很难阅读,因为它太大了,即使我将它输出为相当大的 pdf。

df <- as.data.frame(matrix(abs(rnorm(3380000)), nrow = 20000))
mydist <- vegdist(df)
my.hc <- hclust(mydist, method = "average")
hcd <- as.dendrogram(my.hc)

pdf("hclust_plot.pdf", width = 40, height = 15)
plot(hcd)
dev.off()

我想指定要截断树状图的簇数 (k),然后仅绘制树状图在 k 个分割点上方的上部。我知道我可以根据使用函数 cut() 指定的高度 (h) 绘制上部。

pdf("hclust_plot2.pdf", width = 40, height = 15)
plot(cut(hcd, h = 0.99)$upper)
dev.off()

我也知道我可以使用 dendextend 包为包含 k 个组的树状图着色。

library(dendextend)
pdf("hclust_plot3.pdf", width = 40, height = 15)
plot(color_branches(hcd, k = 44))
dev.off()

但是对于我的数据集,这个树状图过于密集,甚至无法读取哪个组是哪种颜色。有没有一种方法可以通过指定 k 而不是 h 来仅绘制树状图在切点上方的上部?或者有没有办法在给定 k 的情况下获得树状图的 h 值?

最佳答案

您可以使用 the dendextend package 中的 heights_per_k.dendrogram 函数, 以获得各种 k 切割的高度。

例如:

## Not run: 
hc <- hclust(dist(USArrests[1:4,]), "ave")
dend <- as.dendrogram(hc)

library(dendextend)
dend_h <- heights_per_k.dendrogram(dend)
par(mfrow = c(1,2))
plot(dend)
plot(dend, ylim = c(dend_h["3"], dend_h["1"]))

enter image description here

在你的情况下:

set.seed(2016-01-16)
df <- as.data.frame(matrix(abs(rnorm(2*20000)), nrow = 20000))
mydist <- dist(df)
my.hc <- hclust(mydist, method = "average")
hcd <- as.dendrogram(my.hc)

library(dendextend)
library(dendextendRcpp)
dend_h <- heights_per_k.dendrogram(hcd) # (this can take some time)
plot(hcd, ylim = c(dend_h["43"], dend_h["1"]))

enter image description here

关于R基于k绘制上部树状图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34819641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com