r - 在 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)]))))
基于上面的代码片段,这是我想要实现的两件事
- 两个树状图的颜色图例应相同(在附加图像中,Valiant 模型在 d1_dendogram 中为绿色,但在 d2_dendogram 中为紫色)
- 我想用与图例相同的颜色对叶子标签进行颜色编码
提前致谢。
解决方案
你有很多事情要在你的代码中重新做。我已经修复了它,所以现在它可以工作了。如果您有后续问题,可以将它们作为评论发布:)
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)
输出:
推荐阅读
- python - 当条目小部件没有聚焦时,我将如何隐藏列表框小部件?
- css - Font Awesome(在 Chrome 中)的三个警告,即“完整性不匹配”、“适当的 `as` 值”和“请求凭据不匹配”
- hadoop - 检索使用 hadoop distcp 复制的数据大小
- objective-c - 如何处理同时触发的多个警报
- python - 如何使用约束启动 numpy 数组
- c++ - 未分配默认字段初始化的值
- typescript - 如何在 vue.config.js 中添加 source-map-loader
- entity-framework - 带有 ef 核心的 Linq
- amcharts - amCharts 4 - 如何确定光标是否正在显示?
- scala - Spark滑动窗口性能