简体   繁体   English

更改直方图中的条形颜色

[英]Change bar color in histogram

I would like to display an histogram with bars in different colors according to a condition.我想根据条件显示带有不同 colors 条形的直方图。 I mean, I would like to set bars which are between 2 and 5 in a different color.我的意思是,我想将 2 到 5 之间的条设置为不同的颜色。

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:您可以在 plot 之后修改补丁:

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: Output:

在此处输入图像描述

If you want to color by bin values:如果要按 bin 值着色:

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: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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