Adela Adela - 25 days ago 8
R Question

Clusters labels in dendrogram

I'm wondering - is there any way how to add labels of clusters into dendrogram. See simple example:

hc = hclust(dist(mtcars))
plot(hc, hang = -1)
rect.hclust(hc, k = 3, border = "red")

Desired output should look like this:

Thanks for any suggestions!

Answer Source

You need to get the coordinates of the place to put your clusters' labels:

First axis:
As you are calling rect.hclust, you might as well assign the result so you can use it to find the beginning of clusters (the first one begins at 1 the 2nd at 1 + the length of the first, etc.

rh <- rect.hclust(hc, k = 3, border = "red")
beg_clus <- head(cumsum(c(1, lengths(rh))), -1)

Second axis:
You just want to be above the red rectangle, which is at the middle of the height where you have k-1 clusters and the height where you have k clusters. Let's say you're aiming at 4/5 of the distance instead of 1/2:

y_clus <- weighted.mean(rev(hc$height)[2:3], c(4, 1))

Putting the labels:

text(x=beg_clus, y=y_clus, col="red", labels=LETTERS[1:3], font=2)

enter image description here