Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 57 ยท Core Chart Types

Error Bars and Uncertainty

Show uncertainty honestly in Matplotlib with errorbar, asymmetric errors, fill_between bands, a bootstrap interval, eventplot and stem, all runnable live.

A single number on a chart looks precise, but almost every measured number comes with doubt. A survey has a margin of error, a lab measurement has instrument noise, and an average of ten samples wobbles more than an average of ten thousand. If you plot only the central value, the reader assumes certainty that does not exist. Showing uncertainty is not decoration: it changes which conclusions are fair.

This lesson covers the tools Matplotlib gives you for that job: errorbar for points with bars, fill_between for bands around a curve, and a small bootstrap example that computes an interval from raw data. It finishes with eventplot and stem, two chart types for discrete events and discrete values. It builds on line plots and bar charts.

Ways to show doubt

Error bars A whisker above and below each point.
Bands A shaded region around a curve.
Resampling Compute the interval from the data itself.

Pick the form that matches how many points you have.

1 / 2

Your first errorbar

ax.errorbar(x, y, yerr=...) draws markers at (x, y) and a vertical bar of yerr above and below each one. A single number or an array of the same length as y both work. Use capsize to add small end caps so the bar ends are easy to see.

Python Symmetric error bars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

fmt is the usual format string for the markers and line (see colors, styles and markers); use fmt="o" for points only, which is the honest choice when the line between points has no meaning. ecolor colors the bars separately, which is useful when the bars should be quieter than the data.

You can also draw horizontal errors with xerr, or both at once. That fits measurements where both quantities are uncertain, such as a position recorded with a timing error.

Asymmetric errors

Some uncertainty is not symmetric. A count cannot go below zero, and a ratio of positive numbers has a long tail upward. For these, pass yerr as a 2 by N array: the first row is how far to go down from each point, the second how far to go up. Both rows are positive distances, not absolute positions.

Python Asymmetric errors from lower and upper limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The most common mistake is passing the limits themselves, such as yerr=[lower_limit, upper_limit]. Matplotlib then draws bars that are far too long, and it may even raise an error about negative values. Always subtract the estimate first, as the code above does.

A negative value in yerr raises a ValueError. If your lower and upper limits are absolute positions, convert them to distances before plotting.

Bands with fill_between

When you have a smooth curve with many points, bars become a forest of whiskers. A shaded band is cleaner. ax.fill_between(x, lower, upper, alpha=0.25) fills the area between two curves. Use the same color as the line, with low alpha, so the band reads as part of the line.

Python A confidence band around a curve

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two nested bands with different opacity are a compact way to show an inner and an outer range, such as 50% and 95%. If the band is a prediction interval and not a confidence interval, say so in the label: the two answer different questions.

A bootstrap interval

Sometimes there is no formula for the uncertainty of the number you care about, such as a median. The bootstrap gets one by resampling your own data: draw many samples of the same size with replacement, compute the statistic on each, and take the middle 95% of the results. Because the shape of the sample distribution is not forced, the interval can be asymmetric, and errorbar handles that.

Python Bootstrap the median of three groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The seed makes the picture reproducible. If two intervals overlap heavily, the data do not support the claim that those groups differ. If they do not overlap, that is evidence of a difference, though the proper test is a separate step.

Showing the raw data too

An interval hides the sample. With few points, plot the points as well, so a reader can see a single outlier or a bimodal group. A little horizontal jitter keeps them from stacking. Jitter is purely cosmetic: it moves points sideways only, and you must not add it to the y values.

Discrete data: eventplot and stem

Not everything is a curve. ax.eventplot(positions) draws a short vertical tick for each event, one row per sequence, which suits spike trains, log timestamps or alert times. Pass a list of arrays, one per row.

ax.stem(x, y) draws a vertical line from a baseline up to each value with a marker at the top. It communicates that the data are discrete samples, as with a digital signal or a histogram of counts, and not a continuous curve.

Python eventplot and stem side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Showing uncertainty honestly

A few habits keep error displays truthful:

  • Say what the bar is (SD, standard error, 95% interval) in the axis label, legend or caption.
  • Use the same definition across a figure. Mixing SD in one panel and standard error in another invites wrong comparisons.
  • Show the sample size when it is small, for example n = 8 in the title or tick label.
  • Do not hide the data. Add points or a strip of raw values when you can.
  • Mind the baseline. Error bars on a bar chart with a truncated axis exaggerate differences, as discussed in bar charts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In ax.errorbar(x, y, yerr=err), what should a 2 by N err array contain?

    Asymmetric errors are given as distances from the point: row 0 goes down, row 1 goes up. Passing absolute limits draws the wrong lengths.
  2. 2. Why prefer fill_between over many error bars for a smooth curve with 200 points?

    Both display the same idea, but 200 whiskers are cluttered. A translucent band follows the curve and stays readable.
  3. 3. What does the bootstrap do in this lesson?

    Each resample gives one value of the statistic. The percentiles of those values form an interval without needing a formula.
  4. 4. Which chart suits a list of timestamps of events for several servers?

    eventplot draws one tick per event, one row per sequence, which is exactly the shape of timestamp logs.

Summary

  • errorbar(x, y, yerr=, xerr=) draws bars; capsize adds caps and fmt controls the markers.
  • Asymmetric errors use a 2 by N array of positive distances, never absolute limits.
  • fill_between(x, lo, hi, alpha=...) draws bands; nested bands show inner and outer ranges.
  • A bootstrap resamples with replacement and takes percentiles, which gives intervals for any statistic.
  • eventplot draws ticks for event times and stem draws discrete samples.
  • Always state what the bar means and show the raw data or sample size when you can.

Next, put several charts on one figure in Multiple Subplots.