Matplotlib conditional scatterplot colors

Question:

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!

Asked By: Volti

||

Answers:

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])
Answered By: JMA
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.