Search code examples
pythonmatplotlibploterrorbar

Matplotlib asymmetric errorbar plotting in python


Running into an error when trying to plot asymmetric errobars which range from negative values to positive values. I modified the example taken from documentation:

import numpy as np
import matplotlib.pyplot as plt

# example data
x = np.arange(0, 4, 1)
y = -0.2* x


# example error bar values that vary with x-position
error = 0.1 + 0.2 * x

# error bar values w/ different -/+ errors that
# also vary with the x-position
lower_error = -1 * error
upper_error = 4* error
asymmetric_error = [lower_error, upper_error]

plt.errorbar(x, y, yerr=asymmetric_error, fmt='.', ecolor = 'red')
plt.show()

which gives the following plot:

enter image description here

but with the following value for asymmetric error:

array([-0.1, -0.3, -0.5, -0.7]), array([0.4, 1.2, 2. , 2.8])]

This seems to follow documentation so I am not sure what could be causing this.


Solution

  • You don't need the negative in front of the lower error.

    import numpy as np
    import matplotlib.pyplot as plt
    
    # example data
    x = np.arange(0, 4, 1)
    y = -0.2* x
    
    
    # example error bar values that vary with x-position
    error = 0.1 + 0.2 * x
    
    # error bar values w/ different -/+ errors that
    # also vary with the x-position
    lower_error =  error
    upper_error =  4*error
    asymmetric_error = np.array(list(zip(lower_error, upper_error))).T
    
    plt.errorbar(x, y, yerr=asymmetric_error, fmt='.', ecolor = 'red')
    plt.show()
    

    Output:

    enter image description here