Matplotlib:在条形图中调整错误栏的z级别

时间:2015-04-15 16:14:06

标签: python matplotlib

import pylab as pl
import numpy as np

x = np.arange(4)
y1, y2 = [1,2,1,1], [2,3,1,1.5]


pl.bar(x+0.2,y2, width=0.45, color='g')
pl.errorbar(x+0.4,y2,fmt=None, yerr=0.75, ecolor='r', 
            lw=2, capsize=10., mew = 3)

pl.bar(x,y1,width=0.45)
pl.errorbar(x+0.2,y1,fmt=None, yerr=0.5, ecolor='r', 
            lw=2, capsize=10., mew = 3)

pl.savefig('err.png')

产生

enter image description here

我希望绿色值的错误栏由蓝色条 覆盖

我认为调整绘图的z水平应该达到(这就是为什么我首先单独使用.bar和.errorbar):

pl.bar(x+0.2,y2, width=0.45, color='g', zorder=1)
pl.errorbar(x+0.4,y2,fmt=None, yerr=0.75, ecolor='r', 
            lw=2, capsize=10., mew = 3, zorder=1)

pl.bar(x,y1,width=0.45, zorder=2)
pl.errorbar(x+0.2,y1,fmt=None, yerr=0.5, ecolor='r', 
            lw=2, capsize=10., mew = 3, zorder=2)

这会给enter image description here

我无法找到有效的zorders组合。如何在Matplotlib条形图中正确调整错误栏的z级别?

1 个答案:

答案 0 :(得分:2)

我认为你必须分别设置上限的z顺序(它们是pylab.errorbar返回的三个对象之一:

import pylab as pl
import numpy as np

x = np.arange(4)
y1, y2 = [1,2,1,1], [2,3,1,1.5]


pl.bar(x+0.2,y2, width=0.45, color='g', zorder=1)
_, caplines, _ = pl.errorbar(x+0.4,y2,fmt=None, yerr=0.75, ecolor='r', 
            lw=2, capsize=10., mew = 3, zorder=2)

pl.bar(x,y1,width=0.45, zorder=3)
pl.errorbar(x+0.2,y1,fmt=None, yerr=0.5, ecolor='r', 
            lw=2, capsize=10., mew = 3, zorder=4)

for capline in caplines:
    capline.set_zorder(2)

pl.savefig('err.png')

enter image description here