Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Dendrogram leaves

I want to modify the properties of the leaves in a dendrogram produced from plot of an hclust object. Minimally, I want to change the colors, but any help you can provide will be appreciated.

I did try to google the answer, but but every solution that I saw seemed alot harder than what I would have guessed.

like image 657
Btibert3 Avatar asked Jan 18 '11 03:01

Btibert3


2 Answers

A while ago, Joris Meys kindly provided me with this snippet of code that changes the color of leaves. Modify it to reflect your attributes.

clusDendro <- as.dendrogram(Clustering)
labelColors <- c("red", "blue", "darkgreen", "darkgrey", "purple")

## function to get colorlabels
colLab <- function(n) {
   if(is.leaf(n)) {
       a <- attributes(n)
       # clusMember - a vector designating leaf grouping
       # labelColors - a vector of colors for the above grouping
       labCol <- labelColors[clusMember[which(names(clusMember) == a$label)]]
       attr(n, "nodePar") <- c(a$nodePar, lab.col = labCol)
   }
   n
}

## Graph
clusDendro <- dendrapply(clusDendro, colLab)
op <- par(mar = par("mar") + c(0,0,0,2))
plot(clusDendro,
     main = "Major title",
     horiz = T, type = "triangle", center = T)

par(op)
like image 67
Roman Luštrik Avatar answered Sep 22 '22 01:09

Roman Luštrik


Here is a solution for this question using a new package called "dendextend", built exactly for this sort of thing.

You can see many examples in the presentations and vignettes of the package, in the "usage" section in the following URL: https://github.com/talgalili/dendextend

Here is the solution for this question:

# define dendrogram object to play with:
dend <- as.dendrogram(hclust(dist(USArrests[1:3,]), "ave"))
# loading the package
install.packages('dendextend') # it is now on CRAN
library(dendextend)# let's add some color:
labels_colors(dend) <- 2:4
labels_colors(dend)
plot(dend)

enter image description here

like image 26
Tal Galili Avatar answered Sep 18 '22 01:09

Tal Galili