我想根据条件显示带有不同颜色条形的直方图。 我的意思是,我想将2到5之间的条形设置为不同的颜色。
我已经尝试过了:
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()
我收到此错误:
color kwarg must have one color per data set. 1 data sets and 21 colors were provided
答案 0 :(得分:1)
您可以在绘制补丁后对其进行修改:
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()
输出:
如果要按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()
输出: