Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python matplotlib histogram specify different colours for different bars [duplicate]

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')
like image 358
Esme_ Avatar asked Mar 15 '18 01:03

Esme_


People also ask

How do you make each bar a different color in python?

You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.


1 Answers

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

like image 172
student Avatar answered Oct 25 '22 08:10

student