wabash
wabash

Reputation: 839

How can I set positive values to one color and negative values to another in matplotlib?

I have a bar plot of random positive and negative values. I would like to set all negative values to the color blue and all positive values to red in the bar chart. How do you make negative values to blue and positive values to red?

This is what I have so far and tried but I get an error:

rand = np.random.randint(-2, 2, (30))
time = np.arange(1,31,1)

plt.bar(time, rand)
plt.show()

if rand < 0:
    plt.bar(time, rand,'blue')
elif rand > 0:
    plt.bar(time, rand,'red')
    plt.show()

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-110-2154dd329d10> in <module>
----> 1 if rand < 0:
      2     plt.bar(time, rand,'blue')
      3 elif rand > 0:
      4     plt.bar(time, rand,'red')
      5     plt.show()

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

Upvotes: 1

Views: 1579

Answers (2)

gboffi
gboffi

Reputation: 25023

Read about np.where

plt.bar(x, y, color=np.where(y>0, 'b', 'r'))

enter image description here

Upvotes: 2

JohanC
JohanC

Reputation: 80339

The numpy expression rand < 0 gives an array of True and False values. This can't be used for an if-test. In an if-test the whole expression needs to be either True or False.

However, the expression rand < 0 can be used as an index into an array, making a selection of only those indices in the array:

from matplotlib import pyplot as plt
import numpy as np
rand = np.random.randint(-2, 2, (30))
time = np.arange(1, 31, 1)

plt.bar(time[rand < 0], rand[rand < 0], color='tomato')
plt.bar(time[rand > 0], rand[rand > 0], color='cornflowerblue')
plt.axhline(0, color='grey', lw=0.5)
plt.show()

bar plot with different colors for negative bars

Upvotes: 2

Related Questions