【问题标题】:assigning a unique color to the plot of clusters in python为python中的集群图分配唯一的颜色
【发布时间】:2021-02-07 03:40:53
【问题描述】:

我有一个分为 27 个集群的数据框。为了仅在一个图中绘制所有这些集群,我使用以下 for 循环:

list_of_clusters= list(set(klabels))
    
fig=plt.figure(figsize=(13,9),frameon=True,facecolor='lightgrey', edgecolor='black')
    ax = fig.add_subplot(1,1,1)
    plt.axis()
    plt.xlim([-2.5, 0.2])
    plt.ylim([-0.7, 3.3])
    plt.xlabel("log PhiZ")
    plt.ylabel("log RQI")
    
    for i in list_of_clusters:
        
        plt.scatter(
        logphizlogrqi[klabels == i, 0], logphizlogrqi[klabels == i, 1],
        s=10, cmap='hsv',
        marker='8',
        label=i+1
        )
    
    
    
    ax.yaxis.tick_right()
    ax.yaxis.set_ticks_position('both')
    plt.legend(scatterpoints=1, loc='center left',bbox_to_anchor=(-0.4, 0.5))
    plt.grid()
    plt.show()

但生成的图表不止一次使用每种颜色,如下图所示:

理想情况下,我正在寻找的图表应该如下所示(虽然颜色彼此接近,但它们只使用一次):

如果您能帮我解决我的问题,我将不胜感激

【问题讨论】:

标签: python pandas numpy matplotlib k-means


【解决方案1】:

请在seaborn的示例中添加并修复以下代码以响应评论。

添加。

import seaborn as sns

NUM_COLORS = 27

sns.reset_orig() 
colors = sns.color_palette('husl', n_colors=NUM_COLORS)

编辑

for i in list_of_clusters:
    plt.scatter(
    logphizlogrqi[klabels == i, 0], logphizlogrqi[klabels == i, 1],
    s=10, cmap='hsv',
    marker='8',
    label=i+1,
    color=colors[i] # update
    )

【讨论】:

    【解决方案2】:

    所以我想出了这个方法并且效果很好:

    from matplotlib import colors as mcolors
    import random
    
    list_of_clusters= list(set(klabels))
    
    colors = list(mcolors.CSS4_COLORS.keys())
    random.shuffle(colors)
    
    fig=plt.figure(figsize=(13,9),frameon=True,facecolor='lightgrey', edgecolor='black')
    ax = fig.add_subplot(1,1,1)
    plt.axis()
    plt.xlim([-2.5, 0.2])
    plt.ylim([-0.7, 3.3])
    plt.xlabel("log PhiZ")
    plt.ylabel("log RQI")
    
    for i in list_of_clusters:
        plt.scatter(
        logphizlogrqi[klabels == i, 0], logphizlogrqi[klabels == i, 1],
        s=10,
        marker='8',
        label=i+1,
        color=colors[i]
        )
    
    ax.yaxis.tick_right()
    ax.yaxis.set_label_position('right')
    ax.yaxis.set_ticks_position('right')
    plt.legend(scatterpoints=1, loc='center left',bbox_to_anchor=(-0.4, 0.5))
    plt.show()
    

    结果如下所示:

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 2022-07-04
      • 2013-11-19
      • 1970-01-01
      • 2016-04-29
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      相关资源
      最近更新 更多