从树状图

时间:2015-10-29 22:37:19

标签: r dendrogram dendextend ggdendro

我正在使用此链接根据类别绘制带有彩色标签的漂亮树形图。 第二个答案是我在这个使用以下代码的链接(Tree cut and Rectangles around clusters for a horizontal dendrogram in R)中看到的内容:

d <- dist(t(mat[,3:ncol(mat)]), method = "euclidean")
H.fit <- hclust(d, method="ward")
groups <- cutree(H.fit, k=16) # cut tree into  clusters
 hcdata<- dendro_data(H.fit, type="rectangle")
  hcdata$labels <- merge(x = hcdata$labels, y = pm_gtex_comb,  by.x = "label", by.y = "sample",all=TRUE)
 ggplot() + 
 geom_segment(data=segment(hcdata), aes(x=x, y=y, xend=xend, yend=yend)) + 
 geom_text(data=label(hcdata), aes(x, y, label=label, hjust=0, color=cluster), 
        size=3) +
 geom_rect(data=rect, aes(xmin=X1-.3, xmax=X2+.3, ymin=0, ymax=ymax), 
        color="red", fill=NA)+
 geom_hline(yintercept=0.33, color="blue")+
 coord_flip() + scale_y_reverse(expand=c(0.2, 0)) + 
 theme_dendro()

我想切出一些群集,因为我有16个群集,有145个标签,因此我只能查看几个群集,因为我只想对其中几个群集进行聚焦/剪切/放大。是否有任何群集在hclust对象上做这个的方法。这只是为了有一个很好的可视化,因为图形变得混乱了145个标签。因为我想根据标签颜色,我认为ggdendro非常适合。

例如,在此链接中,如果您查看3)放大树形图 http://gastonsanchez.com/blog/how-to/2012/10/03/Dendrograms.html

1 个答案:

答案 0 :(得分:2)

您可以在prune包中找到dendextend(可lots of other nifty things}:

library(dendextend)
hc <- hclust(dist(USArrests), "ave")
clusters <- cutree(hc, k=3)
par(mfrow=c(1,2), mar=c(6, 4, 2, 3))
plot(as.dendrogram(hc), main="regular")
plot(dend <- prune(as.dendrogram(hc), names(clusters[clusters==1])), 
     ylim=range(hc$height), main="without cluster #1")

或者如果你坚持使用ggdendro:

ggdendro::ggdendrogram(dend) 

也可以使用dendextend创建ggplot2图:

library(dendextend)
ggd1 <- as.ggdend(dend)
library(ggplot2)
ggplot(ggd1)