Skip to main content
 首页 » 编程设计

python之如何在 3D 绘图 (Pandas) 中指定 kmeans 簇的颜色

2024年12月31日11xxx_UU

我无法用所需的彩色簇绘制图形。 每个点都属于一个特定的簇,因此每个簇都应该有特定的颜色,但如图所示,我无法获得所需的颜色。我怎样才能修改代码以获得预期的结果和一个好的集群。

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() 

Kmeans Clustering Image

请您参考如下方法:

通过一些随机生成的数据和代码中的一些更改,我认为这就是您想要的(特定集群中的每个数据点都具有相同的颜色):

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()