【问题标题】:How to make a scatter plot for clustering in Python如何在 Python 中为聚类制作散点图
【发布时间】:2015-09-17 04:18:21
【问题描述】:

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

数据

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 可以使散点图很好,但第二个图将取代第一个。
  • 我对 ma​​tplotlib 中的 colorcmap 感到困惑,所以我想知道是否可以使用 seaborn 或 ggplot 来实现。

【问题讨论】:

  • 可以在Then I want to superimpose the center points on the same scatter plot, in another shape (e.g. 'X') and a fifth color (as there are 4 clusters).上更具体

标签: python matplotlib seaborn python-ggplot


【解决方案1】:

您的问题的第一部分可以使用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一样为它们指定任何你想要的颜色

【讨论】:

  • 非常感谢。我想我应该通读 matplotlib 的文档。
【解决方案2】:

部分问题已回答here。大纲是

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]

【讨论】:

    猜你喜欢
    • 2014-08-24
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 2019-12-21
    • 2018-12-21
    • 2020-05-07
    相关资源
    最近更新 更多