Search code examples
pythonmatplotlibbar-charterrorbar

How to Conditionally Change Color of Error Bars


How can I make only the left part of the error-bar whisker (which overlaps with the red horizontal bar) white instead of black for better legibility?

I tried to add a white edge to the black whisker, but this does not look quite like I had expected.

enter image description here

MWE:


import matplotlib.pyplot as plt
cm = 1/2.54 # for inches-cm conversion

fig, axes = plt.subplots(
        num = 'main',
        nrows = 2,
        ncols = 1,
        sharex=True,
        dpi = 300,
        figsize=(16.5*cm, 5*cm)
    )

axes[0].set_xlim(0,100)
axes[0].set_ylim(-1,1)

axes[0].barh(
    y = 0,
    width = 30,
    height = 1.5,
    align='center',
    color = 'red',
    edgecolor = 'black'
)
axes[0].errorbar(
    x = 30,
    y = 0,
    xerr = [[4], [65]],
    fmt = 'none',
    capsize = 2,
    ecolor = 'black',
    elinewidth = 1,
)

Solution

  • IIUC, you can loop over each pair bar/error and set_color to white and also make hlines :

    from matplotlib.patches import Rectangle
    
    containers = axes[0].containers
    
    for bc, ebc in zip(containers[::2], containers[1::2]):
        
        for art in bc:
            if isinstance(art, Rectangle):
                x, w = art.get_x(), art.get_width()
                
        _, (left_ebcvline, _), _ = ebc
    
        left_ebcvline.set_color("white")
        
        axes[0].hlines(left_ebcvline._y, left_ebcvline._x, x+w, color="white")
    

    enter image description here