akash
akash

Reputation: 41

How do I label the terminal nodes of a cut dendrogram?

I used the following code to cut the dendrogram at a particular height.The problem I'm having is that when I cut a dendrogram, I can't figure out how to add labels to the nodes.How can I cut a dendrogram with labels using R program?

library(Heatplus)
cc=as.dendrogram(hclust(as.dist(mat),method="single"))
cutplot.dendrogram(cc,h=20)

Upvotes: 4

Views: 3048

Answers (3)

A_Skelton73
A_Skelton73

Reputation: 1190

cc$labels

This is a vector of all the elements in the dendogram.

cc$labels <- myVector

You can add in your own vector to change the labels

Upvotes: -1

Tal Galili
Tal Galili

Reputation: 25376

Here is a modified solution for what Andrie wrote, but 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:
dhc <- as.dendrogram(hc <- hclust(dist(USArrests), "ave"))
chc <- cut(dhc, h=20)$upper
# loading the package
require(dendextend)# let's add some color:
# change labels with a simple assignment:
labels(chc) <- paste("Custom", 1:22, sep="_")
plot(chc)

For installing the package (since I have yet to upload it to CRAN), use:

####################
## installing dendextend for the first time:

if (!require('installr')) install.packages('installr'); require('installr')
## install.Rtools() # run this if you are using Windows and don't have Rtools
require2(devtools)
install_github('dendextend', 'talgalili')
require2(Rcpp)
install_github('dendextendRcpp', 'talgalili')

Best, Tal

Upvotes: 0

Andrie
Andrie

Reputation: 179558

After a fair amount of digging into the help documentation for ?dendrogram, I stumbled on the dendrapply function that contains an example to do something very similar. Here is your solution, based on a modification of the example in ?dendrapply:

Create dendrogram and cut at height h=20:

dhc <- as.dendrogram(hc <- hclust(dist(USArrests), "ave"))
chc <- cut(dhc, h=20)$upper

Define a vector with the newLabels, and a function newLab that modifies an individual node label. Then pass this to dendrapply:

newLabels <- paste("Custom", 1:22, sep="_")

local({
      newLab <<- function(n) {
        if(is.leaf(n)) {
          a <- attributes(n)
          i <<- i+1
          attr(n, "label") <- newLabels[i]
        }
        n
      }
      i <- 0
    })

nhc <- dendrapply(chc, newLab)
labels(nhc)
 [1] "Custom_1"  "Custom_2"  "Custom_3"  "Custom_4"  "Custom_5"  "Custom_6" 
 [7] "Custom_7"  "Custom_8"  "Custom_9"  "Custom_10" "Custom_11" "Custom_12"
[13] "Custom_13" "Custom_14" "Custom_15" "Custom_16" "Custom_17" "Custom_18"
[19] "Custom_19" "Custom_20" "Custom_21" "Custom_22"

plot(nhc)

enter image description here

Upvotes: 6

Related Questions