使用KMeans生成漂亮的聚类图

时间:2019-02-20 13:50:12

标签: python matplotlib plot cluster-analysis

我一直想在Python上使用matplotlib生成类似的图,其中有一个阴影区域,描绘了具有该区域内所有聚类点的聚类。但是,我看不出有什么想法可以实现?

情节类似于https://jakevdp.github.io/PythonDataScienceHandbook/05.11-k-means.html;但只需要在背景中放置一个阴影区域即可。

1 个答案:

答案 0 :(得分:0)

您可以使用此代码(部分取自astroML.plotting.tools):它带有两个强制性参数,即均值(即每个KMean椭圆的中心)和相关的协方差。它会生成一组不同比例的椭圆(默认情况下,一个与协方差矩阵相关联,一个大两倍,一个树倍大);它接受直接传递到matplotlib例程的参数。

from matplotlib import pyplos as plt

def draw_ellipse(mu, C, scales=[1, 2, 3], ax=None, **kwargs):
    from matplotlib.patches import Ellipse
    if ax is None:
        ax = plt.gca()

    # find principal components and rotation angle of ellipse
    sigma_x2 = C[0, 0]
    sigma_y2 = C[1, 1]
    sigma_xy = C[0, 1]

    alpha = 0.5 * np.arctan2(2 * sigma_xy,
                             (sigma_x2 - sigma_y2))
    tmp1 = 0.5 * (sigma_x2 + sigma_y2)
    tmp2 = np.sqrt(0.25 * (sigma_x2 - sigma_y2) ** 2 + sigma_xy ** 2)

    sigma1 = np.sqrt(tmp1 + tmp2)
    sigma2 = np.sqrt(tmp1 - tmp2)

    for scale in scales:
        ax.add_patch(Ellipse((mu[0], mu[1]),
                             2 * scale * sigma1, 2 * scale * sigma2,
                             alpha * 180. / np.pi,
                                  **kwargs))

您可以向其传递诸如填充色fc='blue'或alpha透明度的参数:例如

draw_ellipse(mean, covariance_matrix, scales=[2], ax=ax,
             ec='k', fc='white', alpha=0.2)