2016-01-22 26 views
1

我使用cutree()将我的hclust()树聚类为若干组。现在我想一个函数来hclust()几个groupmembers作为hclust()... ALSO:hclust()与cutree ...如何在单个hclust()中绘制cutree()集群

我砍一棵树到168组,我想168 hclust()树木... 我的数据是1600 * 1600矩阵。

我的数据是tooooo大,所以我给你举个例子

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棵树......一棵树,一个组。我已经尝试了很多...

回答

4

我提醒你,对于如此大的树木,可能大多数解决方案会有点慢。但这里是一个解决方案(使用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) 

enter image description here

让我们再次做一个 “更好的” 树:

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) 

enter image description here