2017-09-13 50 views
3

我正在試圖對我的結果進行聚類。我進入3簇與標籤名稱一起使用matplotlib:在Python中使用Clustering進行散點圖着色和標註

Y_sklearn - 2維數組包含X和Y座標

ent_names - 包含標籤名稱

我不得不顯示散點圖邏輯如下:

from sklearn.cluster import KMeans 
model = KMeans(n_clusters = 3) 
model.fit(Y_sklearn) 
plt.scatter(Y_sklearn[:,0],Y_sklearn[:,1], c=model.labels_); 
plt.show() 

現在上面的代碼確實顯示散點圖如下: enter image description here

然而,隨着這個情節,我也想顯示標籤名稱。我想是這樣的,但它只能顯示所有顏色:

with plt.style.context('seaborn-whitegrid'): 
    plt.figure(figsize=(8, 6)) 
    for lab, col in zip(ent_names, 
        model.labels_): 
     plt.scatter(Y_sklearn[y==lab, 0], 
       Y_sklearn[y==lab, 1], 
       label=lab, 
       c=model.labels_) 
    plt.xlabel('Principal Component 1') 
    plt.ylabel('Principal Component 2') 
    plt.legend(loc='lower center') 
    plt.tight_layout() 
    plt.show() 

回答

1

你在同一軸線ax密謀把散點圖在一起就像這個例子:

import matplotlib.pyplot as plt 
import numpy as np 

XY = np.random.rand(10,2,3) 

labels = ['test1', 'test2', 'test3'] 
colors = ['r','b','g'] 

with plt.style.context('seaborn-whitegrid'): 
    plt.figure(figsize=(8, 6)) 
    ax = plt.gca() 

    i=0 
    for lab,col in zip(labels, colors): 
     ax.scatter(XY[:,0,i],XY[:,1,i],label=lab, c=col) 
     i+=1 

    plt.xlabel('Principal Component 1') 
    plt.ylabel('Principal Component 2') 
    plt.legend(loc='lower center') 
    plt.tight_layout() 
    plt.show() 

enter image description here

+0

感謝@Serenity的迴應。然而,我的數組包含列表中的元素的每個輪流2個元素如:Y_sklearn 缺貨[81]: 陣列([[1.24746319,-0.29333667], [0.66606617,-1.14079266], [-0.59427804,-0.80379676] , ..., [0.43926165,0.998754353], [0.82787763,-1.52125022], [-1.62969128,-0.40198059]])。因此它給出了錯誤 –

+0

我的數組就是一個例子。你必須把你的數組分散開來,比如'Y_sklearn [y == lab,0],Y_sklearn [y == lab,1]'。主要目標是繪製在同一個軸上。你必須調用'ax.scatter'而不是'plt.scatter'。 – Serenity

相關問題