2013-08-03 38 views
8

Tôi muốn tạo một dendrogram trong R có các nhánh màu, giống như hình bên dưới. enter image description hereLàm thế nào để tạo một dendrogram với các chi nhánh màu?

Cho đến nay tôi sử dụng lệnh sau để tạo một dendrogram tiêu chuẩn:

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 

Làm thế nào tôi nên sửa đổi mã này để có được kết quả mong muốn?

Cảm ơn trước sự giúp đỡ của bạn.

Trả lời

-1

FigTree có thể tạo biểu đồ màu. Xem ví dụ: paper.

Để có được dữ liệu vào Figtree từ một ma trận R khoảng cách dm,

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

Bạn nên sử dụng dendrapply (help document).

Ví dụ:

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

Mà cho:

Colored dendrogram

8

Bạn có thể sử dụng dendextend gói, nhằm cho các nhiệm vụ như thế này:

# 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 

enter image description here

Bạn có thể xem nhiều ví dụ trong bản trình bày và họa tiết của gói, trong phần "sử dụng" trong URL sau: https://github.com/talgalili/dendextend