Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A stacked bar chart in Matplotlib fails in one of two ways: the code raises an exception, or it runs and the bars overlap or sit in the wrong place. Both usually come from the same source, which is how each layer’s starting position (bottom) and its values (height) are passed to ax.bar(). Matplotlib does not stack bars automatically. You build the stack yourself by telling each new layer where the layer below it ends.

How Matplotlib stacks bars

Every call to ax.bar() draws bars starting from a baseline. The bottom parameter sets that baseline. It is the y coordinate of the bottom edge of each bar, and it defaults to zero. To stack a second series on top of a first, pass the first series’ heights as the second series’ bottom. For a third series, the bottom must be the sum of the first and second series, bar by bar. The matplotlib.pyplot.bar documentation defines x and height as float or array-like values, and bottom as a scalar or a sequence with one value per bar.

The Matplotlib gallery example Stacked bar chart (shown in the 3.6.2 documentation) uses exactly this pattern for two series. Its second bar call receives the first series’ values as bottom. The same idea extends to any number of layers.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A working pattern for two or more layers

The following script stacks three series. The cumulative baselines are computed with NumPy arrays, so first + second adds element by element.

import matplotlib.pyplot as plt
import numpy as np

labels = ["A", "B", "C"]
first = np.array([2, 3, 4])
second = np.array([1, 2, 1])
third = np.array([3, 1, 2])

fig, ax = plt.subplots()
ax.bar(labels, first, label="First")
ax.bar(labels, second, bottom=first, label="Second")
ax.bar(labels, third, bottom=first + second, label="Third")
ax.legend()
plt.show()

Each layer’s bottom is the running total of every layer beneath it. If you add a fourth series, its bottom becomes first + second + third.

Diagnosing the error from its symptom

The symptom tells you which part of the call to check. The table below maps the most common cases to their causes.

Symptom Likely cause Fix
The call raises a shape or broadcasting error The bottom or height sequence has a different number of values from the x categories Confirm that len(labels), len(height) and len(bottom) are equal
The call raises a shape error, but the lengths look right when printed Two Python lists were added with +, which concatenates them instead of summing element by element Convert the series to NumPy arrays before adding, or sum with [a + b for a, b in zip(first, second)]
Bars are drawn on top of each other instead of stacked Every layer uses the default bottom=0, or a layer’s baseline is the previous layer’s values rather than their running total Pass the cumulative sum of all earlier layers as bottom
A segment is missing or a bar has a gap A value is NaN in one series, so that segment is not drawn and the next layer’s baseline is undefined at that position Replace missing values with 0 before stacking, or decide explicitly how to treat them
Horizontal bars do not stack The code uses bottom, which applies to vertical bars Use ax.barh() and pass the running total as left

Common errors and how to fix them

Shape mismatch between bars and baselines

Each sequence passed to ax.bar() must have one value per category. If bottom is shorter or longer than x, the call fails. For example, ax.bar(labels, second, bottom=[2, 3]) gives two baselines for three bars. Check the lengths directly before the call:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
print(len(labels), len(second), len(first))

All three numbers must match.

List addition that silently changes length

This is the most frequent cause of a shape error in code that otherwise looks correct. If first and second are plain Python lists, first + second does not add the values. It joins the two lists into one list twice as long. Matplotlib then receives six baselines for three bars. Use NumPy arrays, as in the example above, or build the baseline explicitly:

bottom_for_third = [a + b for a, b in zip(first, second)]

Overlapping bars that do not raise an error

When the code runs but the chart looks wrong, the baseline of the affected layer is almost always zero or incorrect. Print the baseline values for each layer and compare them with the heights of the layers below. For a stack to be correct, each bar’s bottom edge must equal the top edge of the bar beneath it.

Missing values

NaN values are not drawn as zero-height bars. Their segments disappear, and any layer stacked on top of them inherits an undefined baseline. If a missing value should count as zero in the stack, fill it before plotting:

first = np.nan_to_num(first, nan=0.0)

Horizontal stacked bars

bottom positions a vertical bar. For a horizontal bar chart, use ax.barh(), where the baseline is the left parameter:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ax.barh(labels, first, label="First")
ax.barh(labels, second, left=first, label="Second")
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What to include when asking for help

A general description such as “stacked bar chart error” does not identify which of the causes above applies. A question that can be answered quickly contains:

  • The complete traceback, including the line number of the ax.bar() call that raised it
  • The values of x, each height and each bottom, or a small sample with a few categories
  • The Matplotlib version, which you can print with import matplotlib; print(matplotlib.__version__)
  • A description of what you expected the chart to show, so that a stacking mistake can be separated from an intended layout

If the code runs without an exception, the fastest check is to print the cumulative baselines and compare them with the bar tops.

Behaviour described on this page follows the Matplotlib bar API and the stacked bar example in the 3.6.2 documentation. Newer releases may document additional options, so check the current matplotlib.pyplot.bar page if your version differs.

The examples here were written for explanation and were not run against a specific Matplotlib release.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.