Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib conditional scatterplot colors

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading