使用Python中的Clustering对ScatterPlot进行着色和标注

时间:2017-09-13 10:49:31

标签: python matplotlib seaborn

我正在尝试对结果进行聚类。我使用matplotlib进入3个簇以及标签名称:

Y_sklearn - 二维数组包含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 个答案:

答案 0 :(得分: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

相关问题