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(开发者_如何学Pythonas.dist(mat),method="single"))
cutplot.dendrogram(cc,h=20)
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)
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
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
精彩评论