首页 > 解决方案 > 在 2 个树状图中保留标签和图例颜色

问题描述

目标:我想在为同一数据集创建的 2 个树状图中保留标签颜色和图例颜色。

我有相同的数据集(40 个观察值),它在 2 个过程(预过滤和过滤)中转换为树状图。但是,标签颜色会根据它的聚类方式而改变(因此树状图中的标签顺序也会改变)。

这是一个代码片段:

library(dendextend)
small_mtcars <- head(mtcars)

small_mtcars

d1 = small_mtcars %>% select(mpg, cyl, disp) %>% dist() %>% hclust(method = "average") %>% as.dendrogram() 
d2 = small_mtcars %>% select(mpg, cyl, disp) %>% dist() %>% hclust(method = "complete") %>% as.dendrogram() 


par(mar = c(10,4,4,2) + 0.1)

# Plotting d1 

test <- d1 %>% 
  set("labels_cex",0.7) %>% 
  plot(main="d1")
legend("topright", legend=unique(rownames(small_mtcars)[order.dendrogram(d1)]), cex=0.75, bty="n",
       fill=seq(1,length(unique(rownames(small_mtcars)[order.dendrogram(d1)]))))

# Plotting d2 

test2 <- d2 %>% 
  set("labels_cex",0.7) %>% 
  plot(main="d2")
legend("topright", legend=unique(rownames(small_mtcars)[order.dendrogram(d2)]), cex=0.75, bty="n",
       fill=seq(1,length(unique(rownames(small_mtcars)[order.dendrogram(d2)]))))

d1_dendogram d2_dendogram

基于上面的代码片段,这是我想要实现的两件事

  1. 两个树状图的颜色图例应相同(在附加图像中,Valiant 模型在 d1_dendogram 中为绿色,但在 d2_dendogram 中为紫色)
  2. 我想用与图例相同的颜色对叶子标签进行颜色编码

提前致谢。

标签: rdendextendggdendro

解决方案


你有很多事情要在你的代码中重新做。我已经修复了它,所以现在它可以工作了。如果您有后续问题,可以将它们作为评论发布:)

library(dendextend)
library(dplyr)
small_mtcars <- head(mtcars) %>% select(mpg, cyl, disp)

small_mtcars

d1 = small_mtcars %>% dist() %>% hclust(method = "average") %>% as.dendrogram() 
d2 = small_mtcars %>% dist() %>% hclust(method = "complete") %>% as.dendrogram() 

library(colorspace)
some_colors <- rainbow_hcl(nrow(small_mtcars))

d1_col <- some_colors[order.dendrogram(d1)]
d2_col <- some_colors[order.dendrogram(d2)]

labels_colors(d1) <- d1_col
labels_colors(d2) <- d2_col

par(mfrow = c(1,2))

# Plotting d1 

the_labels <- rownames(small_mtcars)

d1 %>% 
    set("labels_cex",0.7) %>% 
    plot(main="d1", xlim = c(1,9))
legend("topright", legend=the_labels, cex=0.75, bty="n",
       fill=some_colors)

# Plotting d2 

d2 %>% 
    set("labels_cex",0.7) %>% 
    plot(main="d2", xlim = c(1,9))
legend("topright", legend=the_labels, cex=0.75, bty="n",
       fill=some_colors)

输出:

在此处输入图像描述


推荐阅读