0

我想R function根据给定的树状图对象、指定的簇数和颜色向量为树状图中的分支着色。我想使用base R而不是dendextend.

使用此答案中的确切代码: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每个分支的高度,那就太棒了。

4

1 回答 1

1

dendextend R 包专为这些任务而设计。您可以在小插图中看到用于更改树状图分支颜色的许多选项。

例如:

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) 

在此处输入图像描述

于 2017-12-10T07:19:49.167 回答