使用base R为树状图中的分支着色的函数

使用base R为树状图中的分支着色的函数,r,plot,dendrogram,hclust,dendextend,R,Plot,Dendrogram,Hclust,Dendextend,我想根据给定的树状图对象、指定数量的簇和颜色向量,为树状图中的分支着色编写R函数。我想使用base R而不是dendextend 使用此答案中的确切代码:对于类似问题: # 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

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

使用此答案中的确切代码:对于类似问题:

# 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)
#生成数据
种子集(12345)
desc.1R软件包是为这些任务而设计的。在中可以看到许多用于更改树状图分支颜色的选项

例如:

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) 
par(mfrow=c(1,2))
密度%dist%%>%hclust(method=“ave”)%%>%as.dengram
d1=颜色分支(密度,k=5,col=c(3,1,1,4,1))
地块(d1)#树枝选择性着色:)
d2=颜色分支(d1,5)
地块(d2)

谢谢您的回答!不过,我希望这可以在没有Dendestend的情况下完成。有什么想法吗?