2017-12-09 18 views
0

与えられた樹状図オブジェクト、指定された数のクラスターおよび色のベクトルに基づいて、樹枝状虫の枝を着色するためにR functionを書きたいと思います。 dendextendの代わりにbase Rを使用します。同様の質問へhttps://stackoverflow.com/a/18036096/7064628:この回答から正確なコード使用ベースを使用して樹形図のブランチを色分けする機能R

上記のコードで

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

は、それらを手動で色を変更するために枝を選択する必要があります。私はkの最高の枝を見つけ、色を変更する機能を持っていたいと思っています。これまでは、最高のサブブランチを繰り返し検索することを試みましたが、それは不必要に難しいようです。すべてのブランチの高さを抽出する方法があった場合は、kが最も高く、サブブランチのそれぞれについてedgeParを変更すると、すばらしいことになります。

答えて

0

dendextend Rパッケージは、これらのタスク用に設計されています。樹状図の枝の色を変更するための多くのオプションがthe vignetteにあります。例えば

par(mfrow = c(1,2)) 
dend <- USArrests %>% dist %>% hclust(method = "ave") %>% as.dendrogram 
d1=color_branches(dend,k=5, col = c(3,1,1,4,1)) 
plot(d1) # selective coloring of branches :) 
d2=color_branches(d1,5) 
plot(d2) 

enter image description here

+0

は、あなたの答えをありがとう!私はこれが「デデジット・エクステンション」なくしてもできると思っていました。何か案は? – ira

関連する問題