Vasily A Vasily A - 8 months ago 89
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
, labels go in different order which makes colors wrong:
enter image description here

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

myclust <- hclust(dist(M))

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

Answer Source

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]
#   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")