python - 如何在 3D 绘图(熊猫)中指定 kmeans 簇的颜色?
问题描述
我无法用所需的彩色集群绘制图形。每个点都属于一个特定的集群,因此每个集群应该有特定的颜色,但如图所示,我无法获得所需的颜色。如何修改代码以获得预期的结果和漂亮的集群。
pca_ = PCA(n_components=3)
X_Demo_fit_pca = pca_.fit_transform(Demo_df_Processed)
kmeans_PCA = KMeans(n_clusters=4, init='k-means++', max_iter= 300, n_init= 10, random_state= 3)
y_kmeans_PCA = kmeans_PCA.fit_predict(X_Demo_fit_pca)
y_kmeans_PCA
Demo_df_Processed.head()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X_Demo_fit_pca[:,0],X_Demo_fit_pca[:,1],X_Demo_fit_pca[:,2], c=y,
edgecolor='k', s=40, alpha = 0.5)
ax.set_title("First three PCA directions")
ax.set_xlabel("Educational_Degree")
ax.set_ylabel("Gross_Monthly_Salary")
ax.set_zlabel("Claim_Rate")
ax.dist = 10
ax.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], kmeans.cluster_centers_[:,2],
s = 100, c = 'r', label = 'Centroid')
plt.autoscale(enable=True, axis='x', tight=True)
plt.show()
解决方案
通过一些随机生成的数据和代码中的一些更改,我认为这就是您想要的(特定集群中的每个数据点具有相同的颜色):
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# randomly generate some data with 4 distinct clusters, use your own data here
Demo_df_Processed = pd.DataFrame(np.random.randint(-2100,-2000,size=(100, 4)), columns=list('ABCD'))
Demo_df_Processed = Demo_df_Processed.append(pd.DataFrame(np.random.randint(-600,-500,size=(100, 4)), columns=list('ABCD')))
Demo_df_Processed = Demo_df_Processed.append(pd.DataFrame(np.random.randint(500,600,size=(100, 4)), columns=list('ABCD')))
Demo_df_Processed = Demo_df_Processed.append(pd.DataFrame(np.random.randint(2000,2100,size=(100, 4)), columns=list('ABCD')))
pca_ = PCA(n_components=3)
X_Demo_fit_pca = pca_.fit_transform(Demo_df_Processed)
kmeans_PCA = KMeans(n_clusters=4, init='k-means++', max_iter= 300, n_init= 10, random_state= 3)
y_kmeans_PCA = kmeans_PCA.fit_predict(X_Demo_fit_pca)
y_kmeans_PCA
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X_Demo_fit_pca[:,0],X_Demo_fit_pca[:,1],X_Demo_fit_pca[:,2],
c=y_kmeans_PCA, cmap='viridis',
edgecolor='k', s=40, alpha = 0.5)
ax.set_title("First three PCA directions")
ax.set_xlabel("Educational_Degree")
ax.set_ylabel("Gross_Monthly_Salary")
ax.set_zlabel("Claim_Rate")
ax.dist = 10
ax.scatter(kmeans_PCA.cluster_centers_[:,0], kmeans_PCA.cluster_centers_[:,1],
kmeans_PCA.cluster_centers_[:,2],
s = 300, c = 'r', marker='*', label = 'Centroid')
plt.autoscale(enable=True, axis='x', tight=True)
plt.show()
推荐阅读
- sql - NOT IN 操作 ORACLE SQL 中的困惑
- flutter - 为什么会出现白屏?扑
- android - 我的 android 位置管理器修复是来自手机信号塔还是 wi-fi
- arrays - VBA:如何使用 for 循环将数组添加到锯齿状数组
- python - 没有权限删除glob?
- php - CodeIgniter 在我的查询中添加换行符
- python - 如何创建一个循环,将每次迭代保存在不同的变量中?
- static-libraries - Github Pages 未加载特定文件夹
- r - R rugarch 包。错误:参数名称与规范不匹配
- python - Pandas .fillna() 不能与 .sample() 一起使用