user17403496
user17403496

Reputation:

How to change histogram color based on x-axis in matplotlib

I have this histogram computed from a pandas dataframe.

enter image description here

I want to change the colors based on the x-axis values.
For example:

If the value is = 0 the color should be green
If the value is > 0 the color should be red
If the value is < 0 the color should be yellow  

I'm only concerned with the x-axis. The height of the bar doesn't matter much to me. All other solutions are for the y-axis.

Upvotes: 2

Views: 2900

Answers (2)

tdy
tdy

Reputation: 41487

For each bar patch in ax.containers[0], use set_color based on the x position:

  • get_x returns the left edge, so get the midpoint by adding half of get_width
  • x probably won't be exactly 0, so test with some buffer (0.2 in this example)

Since you asked for pandas in the comments, this example uses DataFrame.plot.hist, but you can do this with any matplotlib-based histogram/bar plot:

df = pd.DataFrame({'A': np.random.default_rng(222).uniform(-1, 1, 40)})
ax = df.plot.hist()

for bar in ax.containers[0]:
    # get x midpoint of bar
    x = bar.get_x() + 0.5 * bar.get_width()

    # set bar color based on x
    if x < -0.2:
        bar.set_color('orange')
    elif x > 0.2:
        bar.set_color('red')
    else:
        bar.set_color('green')

Upvotes: 4

Z Li
Z Li

Reputation: 4318

Just plot them one by one:

import matplotlib as mpl
import matplotlib.pyplot as plt

x = np.linspace(-1,1,10)
y = np.random.uniform(0,1,10)
width = 0.2
plt.figure(figsize = (12, 6))
cmap = mpl.cm.RdYlGn.reversed()
norm = mpl.colors.Normalize(vmin=0, vmax=10)
for x0, y0 in zip(x,y):
    plt.bar(x0, y0, width = width, color = cmap(norm(np.abs(x0*10))))

enter image description here

Upvotes: 0

Related Questions