[英]hclust() with cutree…how to plot the cutree() cluster in single hclust()
我將我的hclust()樹與cutree()分成幾組。 現在我想要一個函數將幾個組成員hclust()作為hclust()...還可以:
我將一棵樹切成168組,我想要168棵hclust()樹...我的數據是1600 * 1600矩陣。
我的數據太多了,所以我舉一個例子
m<-matrix(1:1600,nrow=40)
#m<-as.matrix(m) // I know it isn't necessary here
m_dist<-as.dist(m,diag = FALSE )
m_hclust<-hclust(m_dist, method= "average")
plot(m_hclust)
groups<- cutree(m_hclust, k=18)
現在我要繪制18棵樹...一組中的一棵樹。 我已經嘗試了很多
我提前警告您,對於這么大的樹木,可能大多數解決方案的運行速度都會有些慢。 但是這是一種解決方案(使用dendextend R包):
m<-matrix(1:1600,nrow=40)
#m<-as.matrix(m) // I know it isn't necessary here
m_dist<-as.dist(m,diag = FALSE )
m_hclust<-hclust(m_dist, method= "complete")
plot(m_hclust)
groups <- cutree(m_hclust, k=18)
# Get dendextend
install.packages.2 <- function (pkg) if (!require(pkg)) install.packages(pkg);
install.packages.2('dendextend')
install.packages.2('colorspace')
library(dendextend)
library(colorspace)
# I'll do this to just 4 clusters for illustrative purposes
k <- 4
cols <- rainbow_hcl(k)
dend <- as.dendrogram(m_hclust)
dend <- color_branches(dend, k = k)
plot(dend)
labels_dend <- labels(dend)
groups <- cutree(dend, k=4, order_clusters_as_data = FALSE)
dends <- list()
for(i in 1:k) {
labels_to_keep <- labels_dend[i != groups]
dends[[i]] <- prune(dend, labels_to_keep)
}
par(mfrow = c(2,2))
for(i in 1:k) {
plot(dends[[i]],
main = paste0("Tree number ", i))
}
# p.s.: because we have 3 root only trees, they don't have color (due to a "missing feature" in the way R plots root only dendrograms)
讓我們在“更細”的樹上再做一次:
m_dist<-dist(mtcars,diag = FALSE )
m_hclust<-hclust(m_dist, method= "complete")
plot(m_hclust)
# Get dendextend
install.packages.2 <- function (pkg) if (!require(pkg)) install.packages(pkg);
install.packages.2('dendextend')
install.packages.2('colorspace')
library(dendextend)
library(colorspace)
# I'll do this to just 4 clusters for illustrative purposes
k <- 4
cols <- rainbow_hcl(k)
dend <- as.dendrogram(m_hclust)
dend <- color_branches(dend, k = k)
plot(dend)
labels_dend <- labels(dend)
groups <- cutree(dend, k=4, order_clusters_as_data = FALSE)
dends <- list()
for(i in 1:k) {
labels_to_keep <- labels_dend[i != groups]
dends[[i]] <- prune(dend, labels_to_keep)
}
par(mfrow = c(2,2))
for(i in 1:k) {
plot(dends[[i]],
main = paste0("Tree number ", i))
}
# p.s.: because we have 3 root only trees, they don't have color (due to a "missing feature" in the way R plots root only dendrograms)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.