Search code examples
pythonpandasmatplotlibhistogram

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.


Solution

  • 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')