# R树状图亲子簇

##### 问题描述投票：2回答：2

``````# Load data
data(USArrests)

# Compute distances and hierarchical clustering
dd <- dist(scale(USArrests), method = "euclidean")
hc <- hclust(dd, method = "ward.D2")

par(mfrow = c(2,2))
# Plot the obtained dendrogram
plot(hc, cex = 0.6, hang = -1)
rect.hclust(hc, k = 2, border = 2:5)

plot(hc, cex = 0.6, hang = -1)
rect.hclust(hc, k = 4, border = 2:5)

plot(hc, cex = 0.6, hang = -1)
rect.hclust(hc, k = 8, border = 2:5)

plot(hc, cex = 0.6, hang = -1)
rect.hclust(hc, k = 12, border = 2:5)
``````

``````# Cut tree into 4 groups
sub_grp1 <- cutree(hc, k = 2)
sub_grp2 <- cutree(hc, k = 4)
sub_grp3 <- cutree(hc, k = 8)
sub_grp4 <- cutree(hc, k = 12)

USArrests\$sub_grp1 = sub_grp1
USArrests\$sub_grp2 = sub_grp2
USArrests\$sub_grp3 = sub_grp3
USArrests\$sub_grp4 = sub_grp4
``````

r cluster-analysis hierarchical-clustering
##### 2个回答
1

``````library(clustree)
data(USArrests)

# Compute distances and hierarchical clustering
dd <- dist(scale(USArrests), method = "euclidean")
hc <- hclust(dd, method = "ward.D2")

Ks = c(1,2,4,6,8)
clus_results = sapply(Ks,function(i){
cutree(hc,i)
})

colnames(clus_results) = paste0("K",Ks)
clustree(clus_results, prefix = "K")
``````

0

``````## Convert to a phylo,  then to igraph
library(ape)
PH = as.phylo(hc)
IG = as.igraph(PH)

## Make a nice layout
LO = layout_as_tree(IG)
LO2 = LO[,2:1]
LO2[,1] = LO2[,1]*6

## plot
plot(IG, layout=LO2, vertex.size=80, edge.arrow.size=0.5,
rescale=F, vertex.label.cex = 0.8,
xlim=range(LO2[,1]), ylim=range(LO2[,2]))
``````