14

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 black (the actual bars and colour is determined by other parts of the code).

I can change the colour of all the bars using the color option, but I would like to be able to give a list of colours that are used.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(1000)
plt.hist(data,color = 'r')
2
  • If you know how many bins there are and what color they should be then hist accepts a list of colors
    – DavidG
    Mar 15, 2018 at 9:17
  • @DavidG can you show me how? I tried to do this and it didn't work.
    – Esme_
    Mar 19, 2018 at 2:46

1 Answer 1

34

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 in range(0,3):
    patches[i].set_facecolor('b')
for i in range(3,5):    
    patches[i].set_facecolor('r')
for i in range(5, len(patches)):
    patches[i].set_facecolor('black')

plt.show()

Result:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.