[英]Change color of selected matplotlib histogram bin bar, given it's value
[英]Change bar color in histogram
我想根據條件顯示帶有不同 colors 條形的直方圖。 我的意思是,我想將 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
您可以在 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:
如果要按 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:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.