Fequish
Fequish

Reputation: 715

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?

Upvotes: 2

Views: 228

Answers (1)

CT Zhu
CT Zhu

Reputation: 54380

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

enter image description here

Upvotes: 2

Related Questions