如何创建有色分支的树状图?如何创建有色分支的树状图?(How to create a dendrog

2019-05-12 05:43发布

我想创建在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

我应该如何修改这个代码,以获得期望的结果呢?

在此先感谢您的帮助。

Answer 1:

您可以使用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

你可以看到在包的介绍和护身符许多例子,在以下网址的“用法”一节中: https://github.com/talgalili/dendextend



Answer 2:

您应该使用dendrapply ( 帮助文档 )。

例如:

# 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)

这使:



Answer 3:

FigTree可以使色彩树状图。 见例如,该论文 。

为了从R距离矩阵数据放入FigTree dm

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


文章来源: How to create a dendrogram with colored branches?