保留2个树状图中的标签和图例颜色

时间:2018-07-18 20:39:57

标签: r dendextend ggdendro

目标:我想在为同一数据集创建的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. 我想使用与图例相同的颜色对叶子标签进行颜色编码

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要在代码中做很多事情。我已经将其修复,因此现在可以使用。如果您有后续问题,可以发表评论:)

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)

输出:

enter image description here