8

我正在执行聚类并尝试绘制结果。一个虚拟数据集是:

数据

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

集群中心

 centers = np.random.randn(4, 2)    # 4 centers, each center is a 2D point

问题

我想制作一个散点图来显示点data并根据集群标签为点着色。

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


评论

  • 我转向seaborn 0.6.0 但没有找到完成任务的 API。
  • yhat的 ggplot 可以使散点图很好,但第二个图将取代第一个图。
  • 我对matplotlibcolor中的and感到困惑,所以我想知道是否可以使用 seaborn 或 ggplot 来做。cmap
4

2 回答 2

13

您问题的第一部分可以使用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()

这导致:

在此处输入图像描述

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

于 2015-06-30T11:47:12.653 回答
2

部分问题已在此处得到解答。大纲是

plt.scatter(x, y, c=color)

引用matplotlib的文档:

c :颜色或颜色序列,可选,默认 [...] 请注意,c 不应是单个数字 RGB 或 RGBA 序列,因为它与要进行颜色映射的值数组无法区分。c 可以是一个二维数组,其中行是 RGB 或 RGBA。

因此,在您的情况下,您需要为每个集群提供一种颜色,然后根据每个点的集群分配填充颜色数组。

red = [1, 0, 0]
green = [0, 1, 0]
blue = [0, 0, 1]
colors = [red, red, green, blue, green]
于 2015-06-30T11:46:30.583 回答