Reputation: 45
I am using this link to plot a nice dendrogram with colored labels as per the categories. The second answer is what I am looking at in this link (Tree cut and Rectangles around clusters for a horizontal dendrogram in R )which uses the code below:
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()
I want to cut out some of the clusters as I have 16 clusters,with 145 labels so that I can view only few clusters as I want to focus/cut-out/zoom in only on couple of them.Is there any way to do this on hclust object .This is only for having a nice visualization as the figure gets messy with 145 labels.Since I want to color as per the labels,I think ggdendro suits pretty well.
For example in this link ,if you look at 3)Zooming-in on dendrograms http://gastonsanchez.com/blog/how-to/2012/10/03/Dendrograms.html
Upvotes: 1
Views: 1262
Reputation: 54287
You could try prune
from the package dendextend
(which can do 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")
or if you insist on ggdendro:
ggdendro::ggdendrogram(dend)
A ggplot2 plot can be created also by using dendextend:
library(dendextend)
ggd1 <- as.ggdend(dend)
library(ggplot2)
ggplot(ggd1)
Upvotes: 2