Frequently asked questions

Tal Galili

2021-05-08

Introduction

Questions are often taken from here the stackoverflow dendrogram tag.

How to colour the labels of a dendrogram by an additional factor variable

Asked (https://stackoverflow.com/questions/27485549/how-to-colour-the-labels-of-a-dendrogram-by-an-additional-factor-variable-in-r)[here].

Solution: use the labels_colors function.

# install.packages("dendextend")
library(dendextend)

dend <- as.dendrogram(hclust(dist(USArrests[1:5,])))
# Like: 
# dend <- USArrests[1:5,] %>% dist %>% hclust %>% as.dendrogram

# By default, the dend has no colors to the labels
labels_colors(dend)
## NULL
par(mfrow = c(1,2))
plot(dend, main = "Original dend")

# let's add some color:
labels_colors(dend) <- 1:5
# Now each state has a color
labels_colors(dend) 
##   Arkansas    Arizona California    Alabama     Alaska 
##          1          2          3          4          5
plot(dend, main = "A color for every state")