You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用factoextra和dendextend实现R聚类颜色一致及添加标签?

树状图聚类颜色匹配与标签添加问题

需求与可复现代码

绘制层次聚类的树状图时,需要让树状图的聚类颜色与factoextra包生成的轮廓图、聚类图保持一致。以下是可复现的示例代码:

library(tidyverse)
library(ggpubr)
library(dendextend)
library(FactoMineR)
library(factoextra)
library(scales)

data(iris)

# 移除物种列并标准化数据
iris.scaled <- scale(iris[, -5])
# 设定聚类数并执行层次聚类切割
k <- 5
hc.cut <- hcut(iris.scaled, k = k, hc_method = "complete")

# 可视化轮廓信息
fviz_silhouette(hc.cut)
#>   cluster size ave.sil.width
#> 1       1   42          0.45
#> 2       2    7          0.57
#> 3       3   24          0.42
#> 4       4   66          0.25
#> 5       5   11          0.34

轮廓图

# 可视化聚类结果
fviz_cluster(hc.cut, ellipse.type = "convex")+
  theme_minimal()

聚类图

# 可视化树状图(颜色不匹配!)
fviz_dend(hc.cut, cex = 0.4)
#> Warning: The `<scale>` argument of `guides()` cannot be `FALSE`. Use "none" instead as
#> of ggplot2 3.3.4.
#> ℹ The deprecated feature was likely used in the factoextra package.
#>   Please report the issue at <https://github.com/kassambara/factoextra/issues>.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.

颜色不匹配的树状图

默认生成的树状图按左右顺序分配颜色,而非原始聚类编号对应的颜色。

已实现的解决方案

通过将hcut对象转换为dendrogram对象,重新排序聚类编号并修改fviz_dend的调色板,可实现颜色匹配:

# 将hcut对象转换为dendrogram对象
dend <- as.dendrogram(hc.cut)
# 获取树状图排序后的聚类归属
clusters <- hc.cut$cluster[order.dendrogram(dend)]

# 查看默认调色板
show_col(hue_pal()(5))

默认调色板

# 按聚类编号顺序重建调色板
cols <- hue_pal()(5)[unique(clusters)]
names(cols) <- unique(clusters)

# 此方法无效:直接添加scale_colour_manual会覆盖原有颜色映射
fviz_dend(dend, k = k,  cex = 0.4) + 
  scale_colour_manual(values = cols, 
                      aesthetics = c("colour", "fill"))
#> Scale for colour is already present.
#> Adding another scale for colour, which will replace the existing scale.

无效尝试的树状图

以下三种方式可实现颜色匹配的树状图:

# 方式1:基于dendrogram对象,指定palette参数
fviz_dend(dend, k = k, palette = cols, cex = 0.4)

颜色匹配的树状图1

# 方式2:基于hcut对象,指定palette参数
fviz_dend(hc.cut, palette = cols, cex = 0.4)

颜色匹配的树状图2

# 方式3:基于hcut对象,指定k_colors参数
fviz_dend(hc.cut, k_colors = cols, cex = 0.4)

颜色匹配的树状图3

待解决问题

  1. 是否有更简便的方法,强制fviz_dend直接按原始聚类编号为树枝着色?
  2. 如何在ggplot2风格的树状图上添加聚类标签,实现类似dendextend在基础绘图中的效果?示例代码如下:
# 基础绘图中添加聚类标签的效果
dend %>% 
  color_branches(k = 5, 
                 col = cols, 
                 groupLabels = unique(clusters)) %>% 
  plot()

带聚类标签的基础树状图


内容的提问来源于stack exchange,提问作者François Gillet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:54:57