【问题标题】:plot kmeans clusters with legend and marker to each cluster and color绘制带有图例和标记的 kmeans 簇到每个簇和颜色
【发布时间】:2022-11-05 20:03:50
【问题描述】:

我想为 K-means 聚类结果制作一个图,每个聚类都有不同的颜色、不同的标记和图例。您能否建议一个脚本来绘制该图?

df 是特征 x、y、z 的数据集,不同的 kmeans 以下列方式作为特征结果:

df['c2']=kmeans2_lables_
df['c3']=kmeans3_lables_

我尝试使用此代码,但它不起作用并且没有标记。

def draw_figures(clust_col):
    lables={2:{0:'Low',1:'High'},3:{0:'Medium',1:'Low',2:'High'},5:{0:'Very High',1:'Very Low',2:'High',3:'Medium',4:'Low'}}
    cdict = {0: 'r', 1: 'b', 2: 'g',3:'c',4:'y'}
    #group=range(clust_col)
    fig, ax = plt.subplots()
    for g in np.unique(df[clust_col]):
        ix = np.where(df[clust_col] == g)
        ax.scatter(df[ix]['f'], df[ix]['avg'], c = cdict[g], label = labels[clust_col][g], s = 100)
    ax.legend()
    plt.show()

【问题讨论】:

    标签: matplotlib seaborn k-means


    【解决方案1】:

    我已经接近您使用以下代码提出的问题:

    cmap = matplotlib.cm.get_cmap('Dark2', 4)
    
    plt.scatter(X[:,0], X[:,1], alpha=.4, c=kmeans.labels_, cmap=cmap)
    plt.axis('equal')
    plt.colorbar(ticks=[])
    plt.show()
    

    检查绘制的结果here

    我正在做的是用cmap = matplotlib.cm.get_cmap('Dark2', 4) 选择一个离散的颜色图,然后我指出要使用它将cmap=cmap 添加到plt.scatter

    我用plt.colorbar 添加颜色条,但用ticks=[] 擦除令人困惑的刻度。

    在寻找类似的解决方案时,我发现了这个:matplotlib scatter plot with color label and legend specified by c option 这也可能对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-03-29
      • 1970-01-01
      • 2014-01-01
      • 2019-01-30
      • 2020-10-29
      • 2022-09-28
      • 2021-12-08
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多