简体   繁体   中英

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

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:

在此处输入图像描述

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM