Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 57 ยท Core Chart Types

Bar Charts

Draw bar charts with Matplotlib: bar and barh, grouped and stacked bars, error bars, bar_label, sorting and why bars must start at zero.

A bar chart compares one number across a handful of categories: sales per region, votes per candidate, errors per module. The length of each bar is the value, and our eyes are very good at comparing lengths that share a baseline. That is why the bar chart is the most dependable chart you can draw.

In this lesson you will draw vertical and horizontal bars, group and stack several series, add error bars and value labels, and learn the one rule that keeps bar charts honest. It assumes you know the object-oriented pattern (fig, ax = plt.subplots()).

Four bar charts you will draw

Simple One bar per category.
Grouped Bars side by side to compare series.
Stacked Bars piled up to show a total.
Horizontal barh for long labels.

All four use the same few calls.

1 / 2

The basics: ax.bar

ax.bar(x, height) draws one bar per item. If x holds strings, Matplotlib treats them as categories and places the bars at positions 0, 1, 2 and so on, labelling the ticks for you.

Python A simple bar chart

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.

ax.bar returns a BarContainer, a list-like object holding one Rectangle per bar. You can keep it to label, recolor or inspect the bars later. The width argument is a fraction of the space between bar centers, so 0.6 leaves gaps and 1.0 makes the bars touch.

Colors can be a single value or a list with one color per bar. Use that sparingly, for example to highlight the one bar your story is about and keep the rest gray.

Horizontal bars with barh

When category names are long, they overlap or need rotating on the x axis. Turn the chart sideways with ax.barh(y, width). Now the labels have room to be read left to right.

Notice the arguments: the bars are positioned along y, and their length is the second argument. Keyword names change too (width becomes the bar length and height the thickness), so it is easiest to pass the two lists positionally.

Python
ax.barh(names, values)
ax.invert_yaxis()   # first item at the top instead of the bottom

Matplotlib puts the first category at the bottom by default, because the y axis grows upward. ax.invert_yaxis() puts the first category on top, which matches how people read a list.

Sorting before plotting

Categories with no natural order should be sorted by value. A sorted chart answers "which is biggest, which is smallest" at a glance, while an alphabetical one makes the reader hunt. Matplotlib will not sort for you; sort the data first.

Python A sorted horizontal bar chart with value labels

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.

ax.bar_label(container) writes each bar's value at its tip. Use padding to move the label away from the bar, fmt="%.1f" to control the number format, and label_type="center" to put it inside the bar. Direct labels often let you drop the axis entirely.

Grouped bars

To compare several series across the same categories, draw one bar per series at each category, shifted sideways. Matplotlib has no "grouped" option, so you do the arithmetic: put the categories at np.arange(n), pick a bar width, and offset each series by a multiple of that width.

For k series, the bars of series i sit at x + (i - (k - 1) / 2) * width. That centers the whole group on the tick.

Python Grouped bars by offset

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 details to remember. First, once x is numeric you must set the tick labels yourself, which ax.set_xticks(positions, labels) does in a single call. Second, keep the total group width (k * width) below 1, or neighbouring groups will collide.

Stacked bars

A stacked bar shows how a total splits into parts. The first series is drawn from zero; each next series uses bottom= to start where the previous one ended. Keep a running total as you go.

Python Stacked bars with bottom

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.

Stacked bars have a weakness: only the bottom segment sits on a shared baseline, so only it is easy to compare across bars. If the reader needs to compare the middle or top series, use grouped bars or separate small charts instead. Negative values need two stacks (one for positives, one for negatives) or the layers overlap.

Error bars on bars

When each bar is an average or an estimate, show its uncertainty with yerr (or xerr for barh). Pass one number per bar for symmetric errors. capsize adds small end caps that make the bars easier to see.

Python
ax.bar(groups, means, yerr=stds, capsize=4, color="lightsteelblue")

Say in the caption or axis label what the error bar means (standard deviation, standard error, a 95 percent interval). Readers cannot guess. The error bars lesson covers this in depth, including asymmetric errors.

Keep the baseline at zero

A bar encodes its value as length, measured from the baseline. If you cut the axis, say to start at 90, then a bar of 95 looks half the length of a bar of 100, though the real difference is five percent. The chart tells a story the data does not.

Python Truncated versus honest axis

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.

If small differences really matter, a dot plot or line chart (which does not encode value as length) can use a non-zero axis legitimately. For bars, start at zero, and if the differences vanish, that is the real answer. The design lesson returns to this theme.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ax.bar(['a', 'b', 'c'], [3, 5, 2]) do with the string x values?

    Matplotlib supports categorical axes: strings become evenly spaced positions with matching tick labels.
  2. 2. How do you start the second layer of a stacked bar chart where the first layer ends?

    ax.bar has no stacked option. The bottom argument shifts each bar's base, so you pass the running total of the layers below.
  3. 3. Three series are drawn as grouped bars of width 0.25 around tick positions x. Where do the bars of the first series go?

    The offset is (i - (k - 1) / 2) * width. For i = 0 and k = 3 that is -1 * 0.25, so the first bar sits at x - 0.25 and the group is centered on x.
  4. 4. Why should the y axis of a bar chart start at zero?

    Readers judge bars by length from the baseline. A truncated axis makes small differences look huge, which misleads.

Summary

  • ax.bar(x, heights) draws vertical bars; ax.barh(y, widths) draws horizontal ones, ideal for long labels (add ax.invert_yaxis() to read top to bottom).
  • String x values become categories; for numeric positions use ax.set_xticks(positions, labels).
  • Grouped bars are offset by (i - (k - 1) / 2) * width; stacked bars use bottom= with a running total.
  • ax.bar_label(container) writes values on the bars; yerr and capsize show uncertainty.
  • Sort unordered categories by value, and always start bar axes at zero.

Next, move from categories to pairs of numbers in Scatter Plots.