gpt4 book ai didi

r - 在 R 中切割树状图

转载 作者:行者123 更新时间:2023-12-04 21:10:53 24 4
gpt4 key购买 nike

我试图将这个树状图分成 3 组:(T24、T1、T17 等)、(T12、T15、T6 等)和(T2、T8、T3、T9)

enter image description here

我曾尝试使用 cutree(hc, k=3, h=400) ,但它继续制作相同的组。任何帮助是极大的赞赏。这是我的代码。

#temps must have date/time as column headers, not row headers
load(temps)
distMatrix <- dist(temps)
#create label colors
labelColors = c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3", "#FF7F00", "#FFFF33")
# cut dendrogram in 3 clusters
clusMember = cutree(hc, k=3, h=400)
colLab <- function(n) {
if (is.leaf(n)) {
a <- attributes(n)
labCol <- labelColors[clusMember[which(names(clusMember) == a$label)]]
attr(n, "nodePar") <- c(a$nodePar, lab.col = labCol)
}
n
}
hcd = as.dendrogram(hc)
clusDendro = dendrapply(hcd, colLab)
plot(clusDendro, main = "Cluster Analysis")

最佳答案

从我们无权访问数据的意义上说,您的示例不可重现。
我只能说你应该看看dendextend R package .它提供了切割树状图以及给标签和分支着色的功能。 Quick Introduction手册展示了labels_colors等功能的基本使用和 color_branches用于生成这样的图:

enter image description here

在您的情况下,由于您的分支似乎处于相同的高度,您不太可能直接控制它们的切割。你可以做的是使用 branches_attr_by_clusters专门控制您关心的子集群的颜色。下面是一个例子:

x <- c(1:3, 6:8)
dend <- as.dendrogram(hclust(dist(x), method = "ave"))
library(dendextend)
labels(dend) <- x[order.dendrogram(dend)]

# due to the ties - there is specific reason to have this be these 3 clusters:
cutree(dend, k = 3)[order.dendrogram(dend)]

par(mfrow = c(1,2))
dend1 <- color_branches(dend, k = 3)
dend1 <- color_labels(dend1, k = 3)
plot(dend1, main = "default cuts by cutree")
# let's force it to be another 3 clusters:
dend2 <- branches_attr_by_clusters(dend, c(1, 2,2, 3,3,3), c("gold", "darkgreen", "blue"))
# coloring the labels is actually the easiest part:
labels_colors(dend2) <- c("gold", "darkgreen", "blue")[c(1, 2,2, 3,3,3)]
plot(dend2, main = "Manual cuts")

enter image description here

关于r - 在 R 中切割树状图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34934198/

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