Skip to main content
 首页 » 编程设计

python之Matplotlib:如何在不循环的情况下绘制彩色点

2024年10月24日13落叶

我有一个正在绘制的 2d 点的 numpy 矩阵,我可以这样做:

xs = np.array([[0,0], [1,0], [2,2]]) 
 
for x in xs: 
    plt.plot(x[0], x[1], 'o', color="red") 

或者,无需循环,我可以这样做:

xs = np.array([[0,0], [1,0], [2,2]]) 
plt.plot(xs[:,0], xs[:,1], 'o', color="red") 

现在假设我还有一个对应颜色的数组: clrs = [0, 1, 0] mycolors = ['红色', '黑色']

所以 0 与 red 关联,1 与 black 关联。我可以使用以下方法循环绘制彩色点:

xs = np.array([[0,0], [1,0], [2,2]]) 
clrs = [0, 1, 0] 
mycolors = ['red', 'black'] 
 
for x,c in zip(xs,clrs): 
    plt.plot(x[0], x[1], 'o', color=mycolors[c]) 

没有循环我怎么能做到这一点?

请您参考如下方法:

您可以使用plt.scatter,并指定一个颜色向量:

plt.scatter(xs[:,0], xs[:,1], c=list('rk')) #r is red, k is black