2016-01-22 30 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