2017-12-09 21 views
0

주어진 흙 드로 그램 객체, 지정된 수의 클러스터 및 색상 벡터를 기반으로하는 덴도 그램에 가지를 채색하기 위해 R function을 쓰고 싶습니다. dendextend 대신 base R을 사용하고 싶습니다.밑줄을 사용하여 덴도 그램 플롯에서 가지를 색칠하는 기능 R

이 답변에서 정확한 코드를 사용 : https://stackoverflow.com/a/18036096/7064628 비슷한 질문에 :

위의 코드에서
# 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

는 답변 주셔서 감사합니다! 나는 이것이 'dendextend'없이 끝나기를 바랐다. 어떤 아이디어? – ira