如何为Python中的聚类绘制散点图

Zel*_*ong 2 python matplotlib python-ggplot seaborn

我正在进行聚类,并尝试绘制结果。虚拟数据集为:

数据

import numpy as np

X = np.random.randn(10)
Y = np.random.randn(10)
Cluster = np.array([0, 1, 1, 1, 3, 2, 2, 3, 0, 2])    # Labels of cluster 0 to 3
Run Code Online (Sandbox Code Playgroud)

集群中心

 centers = np.random.randn(4, 2)    # 4 centers, each center is a 2D point
Run Code Online (Sandbox Code Playgroud)

我想作一个散点图,以data根据聚类标签显示点并为点着色。

然后,我想将center点分散在同一散点图上,以另一种形状(例如“ X”)和第五种颜色(因为有4个簇)叠加。


评论

  • 我转向seaborn 0.6.0,但没有找到完成任务的API。
  • yhat的ggplot可以使散点图更好,但第二个图将替换第一个。
  • 我在matplotlibcolorcmap中感到困惑,所以我想知道是否可以使用seaborn或ggplot来做到这一点。

The*_*tor 7

问题的第一部分可以使用colorbar并指定颜色为Cluster数组来完成。我已经模糊地理解了您的问题的第二部分,但是我相信这就是您想要的。

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(10)
y = np.random.randn(10)
Cluster = np.array([0, 1, 1, 1, 3, 2, 2, 3, 0, 2])    # Labels of cluster 0 to 3
centers = np.random.randn(4, 2) 

fig = plt.figure()
ax = fig.add_subplot(111)
scatter = ax.scatter(x,y,c=Cluster,s=50)
for i,j in centers:
    ax.scatter(i,j,s=50,c='red',marker='+')
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.colorbar(scatter)

fig.show()
Run Code Online (Sandbox Code Playgroud)

结果是:

在此处输入图片说明

其中您的“中心”已使用+标记显示。您可以按照相同的方式为它们指定想要的任何颜色x and y