【问题标题】:Function to color branches in dendrogram plot using base R使用base R在树状图中为分支着色的函数
【发布时间】:2018-05-23 11:40:27
【问题描述】:

我想写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,那就太棒了。

【问题讨论】:

    标签: r plot dendrogram hclust dendextend


    【解决方案1】:

    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) 
    

    【讨论】:

    • 感谢您的回答!我希望这可以在没有dendextend 的情况下完成。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2012-09-02
    • 2015-07-15
    • 2020-06-02
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多