简体   繁体   中英

Matplotlib: how to plot colored points without looping?

I have a numpy matrix of 2d points that I am plotting, which I can do like this:

xs = np.array([[0,0], [1,0], [2,2]])

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

Or, without looping I can just do:

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

Now suppose I also have an array of corresponding colors: clrs = [0, 1, 0] mycolors = ['red', 'black']

So 0 is associated with red and 1 is associated with black . I can plot the colored points in a loop using:

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])

How can I do this without the loop?

You can use plt.scatter , and specify a color vector:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM