Skip to content Skip to sidebar Skip to footer

Python Matplotlib Histogram Specify Different Colours For Different Bars

I want to colour different bars in a histogram based on which bin they belong to. e.g. in the below example, I want the first 3 bars to be blue, the next 2 to be red, and the rest

Solution 1:

One way may be similar to approach in other answer:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
data = np.random.rand(1000)

N, bins, patches = ax.hist(data, edgecolor='white', linewidth=1)

for i inrange(0,3):
    patches[i].set_facecolor('b')
for i inrange(3,5):    
    patches[i].set_facecolor('r')
for i inrange(5, len(patches)):
    patches[i].set_facecolor('black')

plt.show()

Result:

enter image description here

Post a Comment for "Python Matplotlib Histogram Specify Different Colours For Different Bars"