How to colour the labels of a dendrogram by an additional factor variable in R

后端 未结 2 1345
忘了有多久
忘了有多久 2020-12-10 16:42

I have produced a dendrogram after running hierarchical clustering analysis in R using the below code. I am now trying to colour the labels according to another factor varia

相关标签:
2条回答
  • 2020-12-10 16:47

    Try

    # ... your code
    colLab <- function(n) {
      if(is.leaf(n)) {
        a <- attributes(n)
        attr(n, "label") <- labs[a$label]
        attr(n, "nodePar") <- c(a$nodePar, lab.col = varCol[a$label]) 
      }
      n
    }
    plot(dendrapply(hcd, colLab))
    

    (via)

    0 讨论(0)
  • 2020-12-10 16:58

    For coloring your labels, it would be the easiest to use the labels_colors function from the dendextend package. For example:

    # install.packages("dendextend")
    library(dendextend)
    
    small_iris <- iris[c(1, 51, 101, 2, 52, 102), ]
    dend <- as.dendrogram(hclust(dist(small_iris[,-5])))
    # Like: 
    # dend <- small_iris[,-5] %>% dist %>% hclust %>% as.dendrogram
    
    # By default, the dend has no colors to the labels
    labels_colors(dend)
    par(mfrow = c(1,2))
    plot(dend, main = "Original dend")
    
    # let's add some color:
    colors_to_use <- as.numeric(small_iris[,5])
    colors_to_use
    # But sort them based on their order in dend:
    colors_to_use <- colors_to_use[order.dendrogram(dend)]
    colors_to_use
    # Now we can use them
    labels_colors(dend) <- colors_to_use
    # Now each state has a color
    labels_colors(dend) 
    plot(dend, main = "A color for every Species")
    

    For more details on the package, you can have a look at its vignette.

    enter image description here

    0 讨论(0)
提交回复
热议问题