[英]Preserving label and legend color across 2 dendograms
Objective: I would like to preserve label color and legend color across 2 dendograms created for the same dataset. 目标:我想在为同一数据集创建的2个树状图中保留标签颜色和图例颜色。
I have the same dataset (40 observations) that is converted into a dendogram in 2 processes (pre-filtered and filtered). 我有相同的数据集(40个观测值),可通过2个过程(预过滤和过滤)将其转换为树状图。 However, the label colors get changed based on how it gets clustered (and therefore the order of labels in the dendogram gets changed). 但是,标签颜色根据其聚类方式而改变(因此,树状图中的标签顺序也会改变)。
Here is a code snippet: 这是一个代码片段:
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 d1_dendogram d2_dendogram
Based on the code snippet above, here are the 2 things I want to achieve 根据上面的代码片段,这是我要实现的两件事
Thanks in advance. 提前致谢。
You have many things to re-do in your code. 您需要在代码中做很多事情。 I've fixed it so now it works. 我已经将其修复,因此现在可以使用。 If you have followup questions, you can post them as a comment :) 如果您有后续问题,可以发表评论:)
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)
OUTPUT: OUTPUT:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.