Vasily A Vasily A - 20 days ago 10
R Question

order of labels in corrplot after hclust

In my dataset, variables belong to different groups and I want to assign the color for each variable:

mycolors <- rep(NA,11)
names(mycolors) <- names(mtcars)
mycolors[1:4] <- 'green' # mpg, cyl, disp, hp
mycolors[5:9] <- 'red' # drat, wt, qsec, vs, am
mycolors[10:11] <- 'blue' # gear, carb


Now I want to build a correlation matrix and color the labels:

M <- cor(mtcars)
corrplot(M, tl.col = mycolors)


no order

This works fine, but if I order it with
hclust
, labels go in different order which makes colors wrong:
enter image description here

How to get the actual order of the labels after
hclust
, so that I can re-assign colors? I tried to use the following:

myclust <- hclust(dist(M))
myclust$labels[myclust$order]


this gives the order different from the original one, but still not the same as the order used in corrplot...

Answer

Using an idea from here you can reorder your colour vector, so that it meets the order of the hclust ordered matrix.

ord <- corrMatOrder(M, order="hclust")
newcolours <- mycolors[ord]
newcolours
#   carb      wt      hp     cyl    disp    qsec      vs     mpg    drat      am 
# "blue"   "red" "green" "green" "green"   "red"   "red" "green"   "red"   "red" 
#   gear 
# "blue" 
corrplot(M, tl.col = newcolours, order = "hclust")