# How to Plot Error Bars in Matplotlib with errorbar

> How to plot error bars in Matplotlib with ax.errorbar: yerr, xerr, capsize and styling, SD vs SEM vs 95% CI, asymmetric errors, error bars on bar charts, and errorevery.

Source: https://www.pythoncharts.com/matplotlib/matplotlib-error-bars/ | Published: 2026-11-26 | Author: Alex Scott | Category: Matplotlib | Tags: matplotlib, error-bars, errorbar, yerr, confidence-intervals, uncertainty

To plot error bars in Matplotlib, call `ax.errorbar(x, y, yerr=errors, fmt="o", capsize=5)`. `yerr` is the distance from each point to the end of its bar (use `xerr` for horizontal bars), `fmt` styles the points and connecting line, and `capsize` adds the end caps. Bar charts take `yerr` directly.

## Quick Example

This plots group means with 95% confidence intervals, computed from 12 seedlings at each light level.

```python
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

rng = np.random.default_rng(44)
light = np.array([2, 4, 6, 8, 10, 12])
growth = np.array([rng.normal(3 + 9 * (1 - np.exp(-h / 4.5)), 1.4, 12) for h in light])
mean = growth.mean(axis=1)
sem = growth.std(axis=1, ddof=1) / np.sqrt(growth.shape[1])
ci95 = stats.t.ppf(0.975, df=growth.shape[1] - 1) * sem

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.errorbar(light, mean, yerr=ci95, fmt="o-", color="#166534",
            ecolor="#4ade80", elinewidth=2, capsize=5, capthick=2)
ax.set_title("Seedling growth by daily light (mean ± 95% CI)")
ax.set_xlabel("Hours of light per day")
ax.set_ylabel("Growth after two weeks (cm)")
plt.show()
```

![Matplotlib line plot of mean seedling growth against hours of light with green 95 percent confidence interval error bars and caps](https://www.pythoncharts.com/matplotlib/matplotlib-error-bars/images/matplotlib-error-bars-quick-example.png)

Mean growth rises from 6.7 cm at 2 hours of light to 11.0 cm at 8 hours, then roughly levels off. The code targets Matplotlib 3.10 and 3.11.

## errorbar Parameters

| Parameter | What it does | Default |
|---|---|---|
| `yerr`, `xerr` | Error sizes: a number, an array of length N, or shape `(2, N)` | none |
| `fmt` | Marker and line style, e.g. `"o"` or `"s--"`; `"none"` draws only the bars | line, no marker |
| `ecolor` | Error bar color | same as the line |
| `elinewidth` | Error bar line width | same as the line |
| `capsize` | Cap length in points | `0` (no caps) |
| `capthick` | Cap thickness | |
| `errorevery` | Draw bars on every Nth point | `1` |
| `uplims`, `lolims` | Mark values as upper or lower limits | `False` |

The values in `yerr` are distances, not endpoints. If you have lower and upper bounds, subtract the center first. Negative values raise `ValueError: 'yerr' must not contain negative values`.

## Standard Deviation, Standard Error, or Confidence Interval?

Matplotlib draws whatever numbers you pass, so say which one you used in the title or caption.

```python
sd = growth.std(axis=1, ddof=1)
fig, axes = plt.subplots(1, 3, figsize=(10, 3.4), sharey=True, layout="constrained")
for ax, err, name in zip(axes, [sd, sem, ci95],
                         ["Standard deviation", "Standard error", "95% confidence interval"]):
    ax.errorbar(light, mean, yerr=err, fmt="o", color="#1e3a8a", capsize=4)
    ax.set_title(name)
    ax.set_xlabel("Hours of light")
axes[0].set_ylabel("Growth (cm)")
plt.show()
```

![The same group means with three kinds of error bars: standard deviation bars are widest, standard error bars narrowest, and 95 percent confidence intervals in between](https://www.pythoncharts.com/matplotlib/matplotlib-error-bars/images/matplotlib-error-bars-sd-sem-ci.png)

| Error bar | Answers | Shrinks with more data? |
|---|---|---|
| Standard deviation | How spread out are individual values? | No |
| Standard error | How precisely is the mean estimated? | Yes |
| 95% confidence interval | What range of means is consistent with the data? | Yes |

With 12 samples per group, the t-based 95% interval is about 2.2 times the standard error. Use `ddof=1` for the sample standard deviation, since NumPy defaults to `ddof=0`. For statistics where there's no simple formula, such as a median or a ratio, see [bootstrap confidence intervals in Python](https://www.pythoncharts.com/ab-testing/bootstrap-confidence-interval-python/).

## Asymmetric and Horizontal Error Bars

For different lengths on each side, pass an array of shape `(2, N)`: the first row is the distance below (or left), the second the distance above (or right). Here it shows the 25th to 75th percentile around each median.

```python
stages = ["Design", "Build", "Test", "Review", "Release"]
samples = [rng.lognormal(np.log(m), 0.45, 60) for m in [6, 14, 8, 3, 2]]
median = np.array([np.median(s) for s in samples])
q25 = np.array([np.percentile(s, 25) for s in samples])
q75 = np.array([np.percentile(s, 75) for s in samples])
asym = np.vstack([median - q25, q75 - median])

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.errorbar(median, stages, xerr=asym, fmt="D", color="#9d174d",
            ecolor="#f9a8d4", elinewidth=5, markersize=8)
ax.invert_yaxis()
ax.set_xlim(0)
ax.set_title("Days per project stage: median and middle 50%")
ax.set_xlabel("Days")
ax.grid(axis="x", alpha=0.4)
plt.show()
```

![Horizontal dot plot of median days per project stage with asymmetric interquartile range bars; the Build stage is longest and most variable](https://www.pythoncharts.com/matplotlib/matplotlib-error-bars/images/matplotlib-error-bars-asymmetric.png)

Build is the slowest stage, with a median of 14.4 days and a middle range of about 10 to 21. To show full distributions instead, use [box plots](https://www.pythoncharts.com/matplotlib/box-plots-matplotlib/).

## Add Error Bars to a Bar Chart

`ax.bar` accepts `yerr` and `capsize`. Styling for the error lines goes in the `error_kw` dictionary.

```python
sites = ["Farm A", "Farm B", "Farm C", "Farm D"]
control = np.array([4.1, 3.6, 5.0, 4.4])
treated = np.array([4.9, 4.2, 5.2, 5.6])
control_err = np.array([0.30, 0.35, 0.28, 0.32])
treated_err = np.array([0.33, 0.30, 0.36, 0.29])
x = np.arange(len(sites))
w = 0.38

fig, ax = plt.subplots(figsize=(8, 4.2), layout="constrained")
error_style = {"elinewidth": 1.6, "capthick": 1.6}
ax.bar(x - w / 2, control, w, yerr=control_err, capsize=5, error_kw=error_style,
       color="#a8a29e", label="Control")
ax.bar(x + w / 2, treated, w, yerr=treated_err, capsize=5, error_kw=error_style,
       color="#ea580c", label="New fertilizer")
ax.set_xticks(x, sites)
ax.set_title("Wheat yield by site (error bars: 95% CI)")
ax.set_ylabel("Tonnes per hectare")
ax.set_ylim(0, 7)
ax.legend(ncols=2)
plt.show()
```

![Grouped bar chart of wheat yield at four farms for control and new fertilizer, with error bars on every bar](https://www.pythoncharts.com/matplotlib/matplotlib-error-bars/images/matplotlib-error-bars-bar.png)

Don't read significance off overlap alone. Two 95% intervals can overlap slightly while the difference between the means is still significant. To compare groups, plot the difference and its interval, as in [A/B test analysis in Python](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/). If your data is already in pandas, see [adding error bars to DataFrame plots](https://www.pythoncharts.com/pandas/pandas-error-bars/).

## Too Many Error Bars: errorevery or fill_between

On dense data the bars merge into a solid block. `errorevery=10` keeps every tenth one, and `fill_between` draws a shaded band, which usually reads best for continuous series.

```python
t = np.linspace(0, 10, 120)
level = 50 + 12 * np.sin(t / 1.6) + rng.normal(0, 0.6, t.size)
uncertainty = 2 + 0.45 * t

fig, axes = plt.subplots(1, 3, figsize=(11, 3.4), sharey=True, layout="constrained")
axes[0].errorbar(t, level, yerr=uncertainty, color="#0369a1", capsize=2)
axes[0].set_title("Every point: unreadable")
axes[1].errorbar(t, level, yerr=uncertainty, color="#0369a1", capsize=3, errorevery=10)
axes[1].set_title("errorevery=10")
axes[2].plot(t, level, color="#0369a1")
axes[2].fill_between(t, level - uncertainty, level + uncertainty,
                     color="#0369a1", alpha=0.2, linewidth=0)
axes[2].set_title("fill_between band")
plt.show()
```

![Three versions of a noisy series with uncertainty: error bars on every point, error bars on every tenth point, and a shaded confidence band](https://www.pythoncharts.com/matplotlib/matplotlib-error-bars/images/matplotlib-error-bars-dense.png)

More on bands in [Line Chart with Confidence Interval in Python](https://www.pythoncharts.com/python/line-chart-with-confidence-interval/).

## Show Upper or Lower Limits with Arrows

When a measurement is only a bound, such as a value below an instrument's detection limit, `uplims` replaces the symmetric bar with a downward arrow. It takes a Boolean array, so you can flag individual points.

```python
element = np.arange(1, 8)
conc = np.array([8.2, 6.5, 2.0, 5.1, 1.5, 7.4, 3.9])
err = np.array([0.7, 0.6, 0.8, 0.5, 0.6, 0.8, 0.5])
below_detection = np.array([False, False, True, False, True, False, False])

fig, ax = plt.subplots(figsize=(8, 3.8), layout="constrained")
ax.errorbar(element, conc, yerr=err, uplims=below_detection, fmt="s",
            color="#374151", capsize=4)
ax.set_xticks(element, [f"S{i}" for i in element])
ax.set_ylim(0, 10)
ax.set_title("Samples S3 and S5 are upper limits")
ax.set_ylabel("Concentration (µg/L)")
plt.show()
```

![Scatter of sample concentrations with error bars, where samples S3 and S5 have downward arrows marking them as upper limits](https://www.pythoncharts.com/matplotlib/matplotlib-error-bars/images/matplotlib-error-bars-limits.png)

## Practical Tips

- `capsize` is `0` by default. Set it per call, or globally with `plt.rcParams["errorbar.capsize"] = 4`.
- To draw bars over points you've already plotted with `scatter`, use `ax.errorbar(..., fmt="none", zorder=0)`.
- On a log axis, a symmetric error larger than the value reaches zero or below and the lower bar runs off the plot. Use asymmetric errors computed on the log scale.
- With only a handful of observations per group, plot the raw points as well. A mean and a bar can hide a lot.

## Similar Topics

- [How to Add Error Bars to Pandas DataFrame Plots](https://www.pythoncharts.com/pandas/pandas-error-bars/)
- [Line Chart with Confidence Interval in Python](https://www.pythoncharts.com/python/line-chart-with-confidence-interval/)
- [Bootstrap Confidence Intervals in Python](https://www.pythoncharts.com/ab-testing/bootstrap-confidence-interval-python/)
