matplotlib散点图np.choose值错误

0 投票
1 回答
1169 浏览
提问于 2025-04-18 09:11

我正在做k均值聚类,并尝试绘制多个聚类。

我有以下代码,其中X是我的数据点数组:

centroids, ks = kmeans2(X,3) 
colors = ['r', 'g', 'b']
plt.scatter(X[:,0],X[:,1], c=np.choose(ks, colors))
plt.show() 

当我尝试绘制3个聚类时,一切都很好在这里输入图片描述

但是当我尝试绘制4个聚类时,出现了一个错误,提示:

plt.scatter(X[:,0],X[:,1], c=np.choose(ks, colors))
  File "/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 297, in choose
    return choose(choices, out=out, mode=mode)
ValueError: invalid entry in choice array

1 个回答

1

你需要有至少 n 种颜色来对应 n 个组。如果你有很多组,并且希望每个组都有不同的颜色,我建议使用 Paired 这种颜色映射。

In [223]:
#An example of generation 10 different colors.
import matplotlib.cm as cmap
cmap.Paired(np.linspace(0,1,10)) #returns rgba values for 10 different colors.
Out[223]:
array([[ 0.65098041,  0.80784315,  0.89019608,  1.        ],
       [ 0.24138409,  0.55454056,  0.67164939,  1.        ],
       [ 0.49101116,  0.77181086,  0.38794312,  1.        ],
       [ 0.72287582,  0.61176473,  0.45751636,  1.        ],
       [ 0.90200693,  0.16495195,  0.17131873,  1.        ],
       [ 0.9931411 ,  0.71752404,  0.38066898,  1.        ],
       [ 0.93071896,  0.56470589,  0.27973857,  1.        ],
       [ 0.57217994,  0.42994234,  0.70173012,  1.        ],
       [ 0.8785544 ,  0.8418762 ,  0.60081509,  1.        ],
       [ 0.69411767,  0.34901962,  0.15686275,  1.        ]])

撰写回答