Home > Software design >  How to change histogram color based on x-axis in matplotlib
How to change histogram color based on x-axis in matplotlib

Time:12-06

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.

CodePudding user response:

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

CodePudding user response:

For each bar patch in ax.containers[0], use

  • Related