Skip to main content
 首页 » 编程设计

python之Matplotlib:如何使用 pylab.bar() 将误差线着色为与条形相同的颜色

2024年11月01日8mengfanrong

我希望能够为我的错误栏着色与栏颜色相同的颜色。但是,根据我下面的代码,这并没有发生。

# Plot 
x = sig['Glycan Name_Seal'] 
y_seal = sig['Average RFU_Seal'] 
yerr_seal = sig['StDev_Seal'] 
 
y_human = sig['Average RFU_Human'] 
yerr_human = sig['StDev_Human'] 
 
barwidth=0.5 
alpha=1 
 
plt.figure(0, figsize=(18,6)) 
plt.bar(left=sig.index,  
        color=['blue', 'blue'], height=y_seal, width=barwidth, yerr=yerr_seal, label='Seal', alpha=alpha) 
plt.bar(left=sig.index + barwidth,  
        color=['red', 'red'], height=y_human, width=barwidth, yerr=yerr_human, label='Human', alpha=alpha) 
plt.ylim(0,2500) 
plt.ylabel('Average RFU', fontsize=14) 
plt.xlabel('Glycan Number', fontsize=14) 
plt.xlim(0, 56) 
plt.title('Pre-Complexed p-value < 0.01', fontsize=18) 
plt.legend(fontsize=16) 
 
# Add a vertical line to distinguish alpha(2,3) and alpha(2,6) 
plt.plot([1, 1], [0, 2500], color="black", linewidth=2) 
plt.plot([9, 9], [0, 2500], color="black", linewidth=2) 
plt.plot([11, 11], [0, 2500], color="black", linewidth=2) 
 
# Add the texts greek alpha(2,3) and alpha(2,6) 
plt.annotate(r"$\alpha$(2,6)", (3.5, 2250), fontsize=14) 
plt.annotate(r"$\alpha$(2,3)", (29, 2250), fontsize=14) 
plt.annotate("asialoglycan", xy=(0.25, 1950), xytext=(2, 1950), arrowprops=dict(arrowstyle="->", linewidth=2), fontsize=14) 
plt.annotate(r"$\alpha$(2,3) and $\alpha$(2,6)", xy=(10, 1850), xytext=(12, 1850), arrowprops=dict(arrowstyle="->", linewidth=2), fontsize=14) 
 
plt.savefig('Average RFU Plot.pdf') 

结果是 Seal 数据显示为蓝色条和蓝色误差条,而 Human 数据显示为红色条和绿色误差条。

是否可以使Human 数据显示为红色错误条?

请您参考如下方法:

尝试在有问题的情节中设置 ecolor='red'。我建议在您的第一个图中也设置 ecolor='blue' ,因为看起来您只是在那里得到蓝色错误栏,因为这是它们循环的第一个颜色。参见 the documentation for plt.bar了解更多详情。

这是在调用 plt.bar 时完成的:

plt.bar(..., ecolor='red', ...)