How to change dendrogram labels in r

I have a dendrogram in R. It is based on hierarchical clustering using hclust. I color labels that are different in different colors, but when I try to change the labels of my deduction (to the data rows on which the cluster is based) using dendrogram = dendrogram %>% set("labels", dataframe$column) labels are replaced, but in the wrong positions. As an example:

My dendrogram is as follows:

  ___|___ | _|_ | | | | 1 0 2 

when I now try to change the labels as above, the labels change, but they are applied from left to right in their order in the data framework. If we assume that my original data structure looks like this:

 df: Column1 Column2 0 1 A 1 2 B 2 3 C 

what i want is the following:

  ___|___ | _|_ | | | | BA C 

But I really get:

  ___|___ | _|_ | | | | BC A 

Data clustering and its transformation into a dendrogram were performed as follows:

 > d <- stringdistmatrix(df$Column1, df$Column1) > cl <- hclust(as.dist(d)) > dend = as.dendrogram(cl) 

Can someone tell me how can I mark my dendrogram with the values โ€‹โ€‹of another column based on the index?

+5
source share
2 answers

In the cl object created by hclust , you have an element named "order" that contains the order in which the elements are in the dendrogram.

If you want to change the labels, you need to put the new labels in the same order ( cl$order ), so the "new" dendrogram is correct:

 df$column2[cl$order] 
+3
source

The dendextend package allows you to directly update dendrograms (as well as hclust) using the following:

 x <- c(1:5) dend <- as.dendrogram(hclust(dist(x))) if(!require(dendextend)) install.packages("dendextend") library("dendextend") labels(dend) labels(dend) <- c(21:25) labels(dend) 
+4
source

Source: https://habr.com/ru/post/1235546/


All Articles