Felix Hoffmann
Felix Hoffmann

Reputation: 332

Matplotlib: Adjusting z-levels of errorbars in barchart

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')

produces

enter image description here

I want the errorbars of the green values to be covered by the blue bars.

I thought adjusting the z-levels of the plots should achieve that (this is why I'm using .bar and .errorbar separately in the first place):

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)

This givesenter image description here

I wasn't able to find a combination of zorders that works. How do I properly adjust the z-levels of errorbars in a Matplotlib barchart?

Upvotes: 3

Views: 221

Answers (1)

xnx
xnx

Reputation: 25508

I think you have to set the z-order of the caplines separately (they are one of the three objects returned by 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

Upvotes: 2

Related Questions