Dear resident R geniuses,
I would like to colour the branches of cluster in a dendrogram where the leaves are not labelled.
I found the following script here
You need to set the edgePar
elements of the dendrogram object.
In the help for ?dendrapply
there is an example to set the colours of the node labels. By changing just one line to point to "edgePar"
and setting col
, you are almost there:
attr(n, "edgePar") <- c(a$nodePar, list(col = mycols[i], lab.font= i%%3))
The full modified example:
## a smallish simple dendrogram
dhc <- as.dendrogram(hc <- hclust(dist(USArrests), "ave"))
## toy example to set colored leaf labels :
local({
colLab <<- function(n) {
if(is.leaf(n)) {
a <- attributes(n)
i <<- i+1
attr(n, "edgePar") <-
c(a$nodePar, list(col = mycols[i], lab.font= i%%3))
}
n
}
mycols <- grDevices::rainbow(attr(dhc21,"members"))
i <- 0
})
dL <- dendrapply(dhc21, colLab)
plot(dL) ## --> colored labels
You can read all about doing this by careful study of ?dendrapply
and ?as.dendrogram