【问题标题】:How to create a dendrogram with colored branches?如何创建带有彩色树枝的树状图?
【发布时间】:2013-08-04 20:34:47
【问题描述】:

我想在 R 中创建一个带有彩色分支的树状图,如下所示。

到目前为止,我使用以下命令来创建标准树状图:

d <- dist(as.matrix(data[,29]))   # find distance matrix 
 hc <- hclust(d)                # apply hirarchical clustering 
 plot(hc,labels=data[,1], main="", xlab="") # plot the dendrogram

我应该如何修改此代码以获得所需的结果?

提前感谢您的帮助。

【问题讨论】:

    标签: r classification dendrogram dendextend


    【解决方案1】:

    您应该使用dendrapply (help document)。

    例如:

    # Generate data
    set.seed(12345)
    desc.1 <- c(rnorm(10, 0, 1), rnorm(20, 10, 4))
    desc.2 <- c(rnorm(5, 20, .5), rnorm(5, 5, 1.5), rnorm(20, 10, 2))
    desc.3 <- c(rnorm(10, 3, .1), rnorm(15, 6, .2), rnorm(5, 5, .3))
    
    data <- cbind(desc.1, desc.2, desc.3)
    
    # Create dendrogram
    d <- dist(data) 
    hc <- as.dendrogram(hclust(d))
    
    # Function to color branches
    colbranches <- function(n, col)
      {
      a <- attributes(n) # Find the attributes of current node
      # Color edges with requested color
      attr(n, "edgePar") <- c(a$edgePar, list(col=col, lwd=2))
      n # Don't forget to return the node!
      }
    
    # Color the first sub-branch of the first branch in red,
    # the second sub-branch in orange and the second branch in blue
    hc[[1]][[1]] = dendrapply(hc[[1]][[1]], colbranches, "red")
    hc[[1]][[2]] = dendrapply(hc[[1]][[2]], colbranches, "orange")
    hc[[2]] = dendrapply(hc[[2]], colbranches, "blue")
    
    # Plot
    plot(hc)
    

    这给出了:

    【讨论】:

      【解决方案2】:

      您可以使用dendextend 包,针对这样的任务:

      # install the package:
      if (!require('dendextend')) install.packages('dendextend'); library('dendextend')
      
      ## Example:
      dend <- as.dendrogram(hclust(dist(USArrests), "ave"))
      d1=color_branches(dend,k=5, col = c(3,1,1,4,1))
      plot(d1) # selective coloring of branches :)
      d2=color_branches(d1,k=5) # auto-coloring 5 clusters of branches.
      plot(d2)
      # More examples are in ?color_branches
      

      您可以在以下 URL 的“使用”部分中的演示文稿和小插图中看到许多示例:https://github.com/talgalili/dendextend

      【讨论】:

        【解决方案3】:

        FigTree 可以制作彩色树状图。例如,请参见 paper

        要从 R 距离矩阵dm 将数据导入 FigTree,

        library(ape)
        z <- as.phylo(hclust(as.dist(dm)))
        write.nexus(z, file="output.nex")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-07
          • 2019-12-17
          • 2016-04-05
          • 1970-01-01
          • 2020-05-22
          • 2017-10-15
          • 1970-01-01
          相关资源
          最近更新 更多