Search code examples
python-3.xmatplotliberrorbar

How to show horizontal lines at tips of error bar plot using matplotlib?


I can generate an error-bar plot using the code below. The graph produced by the code shows vertical lines that represent the errors in y. I would like to have horizontal lines at the tips of these errors ("error bars") and am not sure how to do so.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1, 10, 10, dtype=int)
y = 2**x
yerr = np.sqrt(y)*10

fig, ax = plt.subplots()
ax.errorbar(x, y, yerr, solid_capstyle='projecting')
ax.grid(alpha=0.5, linestyle=':')
plt.show()
plt.close(fig)

The code generates the figure below. I've played with the solid_capstyle kwarg. Is there a specific kwarg that does what I am trying to do? Error Plot

And as an example of what I'd like, the figure below:

example solution

In case it's relevant, I am using matplotlib 2.2.2


Solution

  • The argument you are looking for is capsize= in ax.errorbar(). The default is None so the length of the cap will default to the value of matplotlib.rcParams["errorbar.capsize"]. The number you give will be the length of the cap in points:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(1, 10, 10, dtype=int)
    y = 2**x
    yerr = np.sqrt(y)*10
    
    fig, ax = plt.subplots()
    ax.errorbar(x, y, yerr, solid_capstyle='projecting', capsize=5)
    ax.grid(alpha=0.5, linestyle=':')
    plt.show()
    

    enter image description here