matplotlib 如何识别具有相似颜色属性的点?

sq1bmfud  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(93)

我试图将具有相似颜色的点连接起来,并将它们作为一组显示在图中。样本数据如下所示-

x = np.array([0,1,2,3,4])
y = np.array([[0.0, 1.0, 1.4, 3.0, 4.0],
              [1.0, 1.4, 1.9, 2.1, 3.0],
              [0.9, 1.0, 1.4, 3.0, 3.1],
              [0.3, 1.0, 1.4, 3.0, 3.7],
              [0.1, 1.0, 1.4, 3.0, 3.9]])

color = [[1,0,0.02], [0.01,.91,0], [0,1,0], [0,0.04,1], [1,.91,0],
         [0,1,0.01], [0.00,1,0], [1,.91,0], [1,0.01,0], [0,0,1],
         [1,.91,0.00], [0.03,1,0], [0,1,0], [0,0.00,1], [1,0,0],
         [1,.91,0.03], [0.05,1,0], [0,1,0], [0,0.03,1], [1,0,0],
         [1,.91,0.00], [0.01,.91,0], [0,1,0], [0,0.03,1], [1,0,0]]

用这些数据做一个散点图,看起来像这样-

plt.scatter(np.repeat(x, y.shape[1]), y, s=12, c=color)
plt.plot(x,y,'k',lw=0.7)

我想让它像这样-

我们的想法是用相似的颜色来分组。我如何在matplotlib中做到这一点?

ss2ws0br

ss2ws0br1#

你可以用scipy来创建颜色簇,但是绿色会被链接起来:

from scipy.cluster.vq import kmeans2
clusters, indexer = kmeans2(color, 4, minit="++") # adjust if needed

d = {}
for ix, iy, idx in zip(np.repeat(x, y.shape[1]), y.flatten(), indexer):
    d.setdefault(tuple(clusters[idx]), []).append([ix, iy])
    
for ic, ixy in d.items():
    plt.plot(*zip(*ixy), lw=0.7, color=ic, marker="o", ms=6)

plt.show();

输出量:

相关问题