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

K-means聚类可视化轴标签问题:如何将行号替换为球员名称?

问题:K-means聚类可视化轴显示行号而非球员名称

我参考K-means聚类教程运行基础代码时一切正常:

library(tidyverse)  # 数据处理
library(cluster)    # 聚类算法
library(factoextra) # 聚类算法与可视化

distance <- get_dist(df)
fviz_dist(distance, gradient = list(low = "#00AFBB", mid = "white", high = "#FC4E07"))

但使用IPL数据集运行以下代码时,可视化图表的轴上显示的是行号而非PLAYER列的球员名称:

ipl <- read.csv("https://query.data.world/s/3kadbuzyj25jwe42k6tgij56gscept?dws=00000", header=TRUE, stringsAsFactors=FALSE)
ipl <- na.omit(ipl)

distanceipl <- get_dist(ipl)
fviz_dist(distanceipl, gradient = list(low = "#00AFBB", mid = "white", high = "#FC4E07"))

解决方案1:用ggplot2的scale_*_discrete设置轴标签

提取PLAYER列的内容作为轴标签,在fviz_dist生成的图表后添加scale_x_discrete和scale_y_discrete来替换默认的行号:

# 提取球员名称作为标签
player_labels <- ipl$PLAYER

# 生成距离图并替换轴标签
fviz_dist(distanceipl, gradient = list(low = "#00AFBB", mid = "white", high = "#FC4E07")) +
  scale_x_discrete(labels = player_labels) +
  scale_y_discrete(labels = player_labels)

解决方案2:将球员名称设为数据框行名

把PLAYER列的值赋值给数据框的行名,之后fviz_dist会自动识别行名并作为轴标签显示:

# 将PLAYER列设置为数据框行名
rownames(ipl) <- ipl$PLAYER

# 重新计算距离并绘图
distanceipl <- get_dist(ipl)
fviz_dist(distanceipl, gradient = list(low = "#00AFBB", mid = "white", high = "#FC4E07"))

内容的提问来源于stack exchange,提问作者damo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:07:33