Home > database >  Matplotlib conditional scatterplot colors
Matplotlib conditional scatterplot colors

Time:11-28

I'm trying to change the colors of the points in a scatterplot to red based on the condition x > 0. Here's what I have:

x = np.random.rand(100,1)
y = np.random.rand(100,1)

plt.scatter(x, y, c=['r' if x > 0 else 'b' for v in x])

I get the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

When I try to change the color value from x to x.any() or x.all() as such, I get the following error:

plt.scatter(x, y, c=['r' if x.all() > 0 else 'b' for v in x.all()])

TypeError: 'numpy.bool_' object is not iterable

Any idea how to get past this error? Thank you!

CodePudding user response:

There is a mistake in the comprehesion list in the first code block. Try the following:

plt.scatter(x, y, c=['r' if v > 0 else 'b' for v in x])

However, you will see all the values in red as the function np.random.rand() returns positive values (between 0 and 1). To confirm that it is working you can use this modification:

plt.scatter(x, y, c=['r' if v > 0.5 else 'b' for v in x])
  • Related