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

多变量数据集K-means聚类结果散点图可视化方案咨询

多变量聚类可视化常用方案

1. 高维特征降维后散点图可视化

这是最通用的方案,先将所有输入聚类的特征维度降到2/3维,再按聚类标签着色,可保留大部分原始数据的聚类分布信息。常用降维方法可选PCA(线性、速度快)、t-SNE(非线性、适合展示局部聚类结构)、UMAP(兼顾全局结构和速度)。
示例代码:

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# 提取所有参与聚类的特征列,可根据实际特征名调整
feature_cols = ['disgusted', 'angry', 'fearful', 'happy', 'sad', 'surprised', 'neutral']
X = noevent_cluster[feature_cols]
# 用PCA降到2维
pca = PCA(n_components=2, random_state=42)
X_2d = pca.fit_transform(X)
# 绘制散点图,按kmeans_4聚类结果着色
c = noevent_cluster['kmeans_4']
fig, ax = plt.subplots()
scatter = ax.scatter(X_2d[:,0], X_2d[:,1], c=c)
legend1 = ax.legend(*scatter.legend_elements(), loc="upper right", title="Clusters")
ax.add_artist(legend1)
ax.set_xlabel('PCA特征1')
ax.set_ylabel('PCA特征2')
plt.show()

如果想要更好的局部聚类区分效果,可以把PCA替换为sklearn.manifold.TSNE或者umap.UMAP即可。

2. 平行坐标图

可以直观展示每个聚类在所有特征维度上的取值分布差异,适合对比不同聚类的特征模式。
示例代码:

import plotly.express as px
feature_cols = ['disgusted', 'angry', 'fearful', 'happy', 'sad', 'surprised', 'neutral']
fig = px.parallel_coordinates(noevent_cluster, 
                              dimensions=feature_cols,
                              color='kmeans_4',
                              color_continuous_scale=px.colors.diverging.Tealrose)
fig.show()

该方案生成的是交互式图表,可直接框选查看特定区间的数据分布,适合排查不同聚类的特征差异。

3. 散点图矩阵(Pairplot)

如果你的特征数量在10个以内,可以直接绘制所有特征两两组合的散点图矩阵,按聚类标签着色,能同时看到不同特征对下的聚类区分效果。
示例代码:

import seaborn as sns
feature_cols = ['disgusted', 'angry', 'fearful', 'happy', 'sad', 'surprised', 'neutral']
# 把聚类标签转为分类类型方便着色
plot_df = noevent_cluster[feature_cols + ['kmeans_4']].copy()
plot_df['kmeans_4'] = plot_df['kmeans_4'].astype('category')
sns.pairplot(plot_df, hue='kmeans_4', corner=True)
plt.show()

4. 聚类中心雷达图

如果想要看每个聚类的平均特征模式,可以先计算每个聚类在所有特征上的均值,再绘制雷达图对比。
示例代码:

import numpy as np
feature_cols = ['disgusted', 'angry', 'fearful', 'happy', 'sad', 'surprised', 'neutral']
# 计算每个聚类的特征均值
cluster_centers = noevent_cluster.groupby('kmeans_4')[feature_cols].mean().reset_index()
# 雷达图配置
labels = np.array(feature_cols)
num_vars = len(labels)
# 计算角度
angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()
angles += angles[:1] # 闭合图形
fig, ax = plt.subplots(figsize=(6,6), subplot_kw=dict(polar=True))
# 逐个绘制聚类的雷达线
for idx, row in cluster_centers.iterrows():
    values = row[feature_cols].tolist()
    values += values[:1]
    ax.plot(angles, values, label=f'聚类{row["kmeans_4"]}')
    ax.fill(angles, values, alpha=0.25)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(labels)
ax.legend(loc='upper right', bbox_to_anchor=(1.3, 1))
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 06:54:07