简体   繁体   English

如何创建带有彩色分支的树状图?

[英]How to create a dendrogram with colored branches?

I would like to create a dendrogram in R which has colored branches, like the one shown below. 我想在R中创建一个有色分支的树状图,如下图所示。 在此处输入图片说明

So far I used following commands to create a standard dendrogram: 到目前为止,我使用以下命令来创建标准树状图:

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

How should I modify this code to obtain desired result ? 我应该如何修改此代码以获得所需的结果?

Thanks in advance for your help. 在此先感谢您的帮助。

You could use the dendextend package, aimed for tasks such as this: 您可以使用针对以下任务的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

在此处输入图片说明

You can see many examples in the presentations and vignettes of the package, in the "usage" section in the following URL: https://github.com/talgalili/dendextend 在以下URL的“用法”部分中,您可以在该包的演示文稿和小插图中看到许多示例: https : //github.com/talgalili/dendextend

You should use dendrapply ( help document ). 您应该使用dendrapply帮助文档 )。

For instance: 例如:

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

Which gives: 这使:

彩色树状图

FigTree can make color dendrograms. FigTree可以制作彩色树状图。 See for example, this paper . 例如参见本文

To get data into FigTree from an R distance matrix dm , 为了将数据从R距离矩阵dm获取到FigTree中,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM