Nelly Louis
Nelly Louis

Reputation: 167

Change bar color in histogram

I would like to display an histogram with bars in different colors according to a condition. I mean, I would like to set bars which are between 2 and 5 in a different color.

I've tried this:

bins = np.linspace(0, 20, 21)

lista_float_C1 = [1,1,1,2,2,2,3,4,4,5,5,6,7,8,8,8,8,10,11,11]

colors = []

y = plt.hist(lista_float_C1, bins, alpha=0.5 )

for x in y[1]:
    if (x >= 2)&(x=<5):
        colors.append('r')
    else: 
        colors.append('b')
print(colors)    

plt.hist(lista_float_C1, bins, alpha=0.5, color = colors )
plt.show()

I get this error :

color kwarg must have one color per data set. 1 data sets and 21 colors were provided

Upvotes: 1

Views: 754

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150745

You can modify the patches after you plot them:

lista_float_C1 = [1,1,1,2,2,2,3,4,4,5,5,6,7,8,8,8,8,10,11,11]

fig,ax = plt.subplots()
ax.hist(lista_float_C1, bins, alpha=0.5 )

for p in ax.patches:
    x =  p.get_height()

    # modify this to fit your needs
    color = 'r' if (2<=x<=5) else 'b'
    p.set_facecolor(color)

plt.show()
plt.show()

Output:

enter image description here

If you want to color by bin values:

for p in ax.patches:
    # changes here
    x,y =  p.get_xy()

    color = 'r' if (2<=x<=5) else 'b'
    p.set_facecolor(color)
plt.show()

Output:

enter image description here

Upvotes: 1

Related Questions