Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

horizontal dendrogram in R with labels

I am trying to draw a dendrogram from the hclust function output. I hope the dendrogram is horizontally arranged instead of the default, which can be obtain by (for example)

require(graphics)
hc <- hclust(dist(USArrests), "ave")
plot(hc)

I tried to use as.dendrogram() function like plot(as.dendrogram(hc.poi),horiz=TRUE) but the result is without meaningful labels:

enter image description here

If I use plot(hc.poi,labels=c(...)) which is without the as.dendrogram(), I can pass the labels= argument, but now the dendrogram is vertical instead of horizontal. Is there a way to simultaneously arrange the dendrogram horizontally and assign user-specified labels? Thanks!

Update: as an example from the USArrests dataset, suppose I wanna use the abbreviations of the first two letters of the state names as labels, so that I wanna somehow pass labs into the plotting function:

labs = substr(rownames(USArrests),1,2)

which gives

 [1] "Al" "Al" "Ar" "Ar" "Ca" "Co" "Co" "De" "Fl" "Ge" "Ha"
[12] "Id" "Il" "In" "Io" "Ka" "Ke" "Lo" "Ma" "Ma" "Ma" "Mi"
[23] "Mi" "Mi" "Mi" "Mo" "Ne" "Ne" "Ne" "Ne" "Ne" "Ne" "No"
[34] "No" "Oh" "Ok" "Or" "Pe" "Rh" "So" "So" "Te" "Te" "Ut"
[45] "Ve" "Vi" "Wa" "We" "Wi" "Wy"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using dendrapply you can customize your dendro as you like.

enter image description here

colLab <- function(n) {
  if(is.leaf(n)) {
    a <- attributes(n)
    attr(n, "label") <- substr(a$label,1,2)             #  change the node label 
    attr(n, "nodePar") <- c(a$nodePar, lab.col = 'red') #   change the node color
  }
  n
}

require(graphics)
hc <- hclust(dist(USArrests), "ave")
clusDendro <- as.dendrogram(hc)
clusDendro <- dendrapply(clusDendro, colLab)
op <- par(mar = par("mar") + c(0,0,0,2))
plot(clusDendro,horiz=T)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...