对于 R 中的树状图,如何在根据簇为分支着色的同时添加自定义文本?

问题描述 投票:0回答:0

我有这个树状图:

hc <- hclust(dist_s, method = 'average')

起初,我用dendextend展示它:

dend = as.dendrogram(hc)
par(mar = c(3, 2, 2, 8)) 
dend %>% 
  set("labels_cex", 0.9) %>% 
  set("branches_k_color", 
             value = c("#E69F00", "#56B4E9", "#009E73"), k = 3) %>% 
  plot(main = "Hierarchical clustering", horiz= TRUE)

我需要添加自定义副标题来解释示例,例如脚注文本。有一些解决方案,所以我的第一个问题是:如何使用 dendextend 做到这一点?

我能够使用 ggplot 添加此文本。但是使用这种方法我无法根据集群分配为分支着色。所以补充的问题是:如何正确地将分支颜色映射到集群。

我不知道哪种方法更容易修复。

这些是我使用 ggplot 进行的试验,添加的文本正确,但着色有问题。

dend_data <- dendro_data(as.dendrogram(hc), type = "rectangle")

cluster_colors <- c("orange", "green", "blue") 
clusters <- c(1, 2, 2, 3, 3, 3, 3)  # cluster assignments

#where to add the clusters column?
dend_data$segments$cluster <- clusters

p <- ggplot(dend_data$segments) + 
  ggtitle("Hierarchical clustering") +
  geom_segment(aes(x = x, y = y, xend = xend, yend = yend, color = factor(cluster)))+
  scale_colour_manual(values = cluster_colors) +
  geom_text(data = dend_data$labels, aes(x, y, label = label),
            hjust = 1, angle = 90, size = 3)+
  geom_text(x = x_coord, y = y_coord,
            label = "this is my custom text",
            size = 3, color = "black")

我知道要将颜色映射到聚类,我的数据中有必要有一列将每个样本分配给一个聚类。我这里有这个专栏:

clust_df <- mutate(as.data.frame(tpms), cluster = cut)

在 clust_df$cluster 中我可以得到这个信息,但是在 dend_data 中,我不知道在哪里可以找到它或在哪里添加它。在上面的 ggplot 代码中,我试图将它添加到 dend_data$segments,但出现以下错误:

$<-.data.frame
(
*tmp*
, cluster, value = c(1, 2, 2, 3, 3, 3, : 替换有 7 行,数据有 24 我还尝试将其添加到 $labels:

#[...]
dend_data$labels$cluster <- clusters
#[...]
  geom_segment(aes(x = x, y = y, xend = xend, yend = yend, color = factor(labels$cluster)))+
#[...]

但后来我得到了错误:

geom_segment(aes(x = x, y = y, xend = xend, yend = yend, color = factor(labels$cluster))) 错误:

第一层出现错误。

labels$cluster
错误导致: “闭包”类型的对象不是子集

像这样:

geom_segment(aes(x = x, y = y, xend = xend, yend = yend, color = factor(dend_data_s$labels$cluster)))+

我得到错误:

geom_segment(aes(x = x, y = y, xend = xend, yend = yend, color = factor(dend_data_s$labels$cluster))) 错误:

第一层出现错误。

check_aesthetics()
错误导致: 美学必须是长度 1 或与数据相同 (24) 修复以下映射:
colour

dend_data 对象如下所示: dend_data

我也尝试过添加彩色矩形并根据集群为标签着色,但最终遇到了类似的问题。

最后但同样重要的是,我能够通过这种方式添加彩色矩形:

rect.hclust(dendr_l, k = 3, border = c("orange", "green", "blue"))

但是我无法添加自定义文本。

r ggplot2 hierarchical-clustering dendrogram hclust
© www.soinside.com 2019 - 2024. All rights reserved.