Colouring branches in a dendrogram in R

前端 未结 1 725
自闭症患者
自闭症患者 2021-01-03 09:32

Dear resident R geniuses,

I would like to colour the branches of cluster in a dendrogram where the leaves are not labelled.

I found the following script here

相关标签:
1条回答
  • 2021-01-03 10:11

    You need to set the edgePar elements of the dendrogram object.

    In the help for ?dendrapply there is an example to set the colours of the node labels. By changing just one line to point to "edgePar" and setting col, you are almost there:

    attr(n, "edgePar") <- c(a$nodePar, list(col = mycols[i], lab.font= i%%3))
    

    The full modified example:

    ## a smallish simple dendrogram
    dhc <- as.dendrogram(hc <- hclust(dist(USArrests), "ave"))
    
    ## toy example to set colored leaf labels :
    local({
      colLab <<- function(n) {
        if(is.leaf(n)) {
          a <- attributes(n)
          i <<- i+1
          attr(n, "edgePar") <-
            c(a$nodePar, list(col = mycols[i], lab.font= i%%3))
        }
        n
      }
      mycols <- grDevices::rainbow(attr(dhc21,"members"))
      i <- 0
    })
    dL <- dendrapply(dhc21, colLab)
    plot(dL) ## --> colored labels
    

    enter image description here


    You can read all about doing this by careful study of ?dendrapply and ?as.dendrogram

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