October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Make a Stacked Bar Chart with Pandas

Create a stacked bar plot in Pandas with `stacked=True`. Learn how to arrange the DataFrame, select columns, use horizontal bars, and customize the Matplotlib axes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use df.plot.bar(stacked=True) to make a vertical stacked bar plot from a DataFrame: each row becomes a category, and each numeric column becomes a colored segment. For horizontal bars, use df.plot.barh(stacked=True).

Make a basic stacked bar plot

Arrange the DataFrame with one category per row and one series per numeric column. Then pass stacked=True explicitly; stacking is not the default for bar plots. The Pandas visualization guide shows both vertical and horizontal stacked bars.

As an Amazon Associate I earn from qualifying purchases.

ax = df.plot.bar(stacked=True)

Here is a complete example with regions as categories and products as the stacked series:

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.
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {
        "Product A": [12, 18, 10],
        "Product B": [8, 7, 14],
        "Product C": [5, 9, 6],
    },
    index=["North", "South", "West"],
)

ax = df.plot.bar(stacked=True, figsize=(8, 5))
ax.set(title="Sales by region", xlabel="Region", ylabel="Units")
ax.legend(title="Product")
plt.tight_layout()
plt.show()

Because no x or y is specified, Pandas uses the index for category labels and plots the numeric columns. This is an illustrative example; replace the sample values and labels with your data.

Choose the categories and values

If your category labels are stored in a column rather than the index, name that column with x and specify the value columns with y. The DataFrame plotting API accepts a column label or position for x and y.

ax = df.plot.bar(
    x="region",
    y=["Product A", "Product B", "Product C"],
    stacked=True,
)

Keep each category on a row and each component in a separate column. If the data is oriented the other way around, transpose it before plotting with df.T, then check that the resulting index and column labels correspond to the categories and series you intend to show.

Use horizontal bars for long labels

Switch to barh when category names are long or are easier to scan vertically:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ax = df.plot.barh(stacked=True)

The same row-and-column arrangement applies. The orientation changes the axis layout, not which values are stacked.

Customize colors, labels, and layout

For the ordinary single-plot case, Pandas returns a Matplotlib Axes, so you can keep the returned object and use Matplotlib methods to adjust the chart. The API documents the return type and plotting options in its plotting reference.

  • Set series colors: pass a mapping so colors remain tied to column names, for example color={"Product A": "#4472C4", "Product B": "#ED7D31", "Product C": "#70AD47"}.
  • Clarify the axes: use ax.set_title(), ax.set_xlabel(), and ax.set_ylabel() to describe the category and units.
  • Clarify the legend: use ax.legend(title="Product") to identify the stacked series.
  • Improve spacing: call plt.tight_layout() before displaying or saving the figure when labels or the legend need room.

For example, add color={"Product A": "#4472C4", "Product B": "#ED7D31", "Product C": "#70AD47"} to the df.plot.bar() call in the worked example. The plotting API also permits a single color or a sequence of colors. With subplots=True, the API returns an array of Axes rather than one Axes, so customization must target the appropriate subplot.

Rank #4
Sale
Pandas Journal (Diary, Notebook)
  • Crisp writing pages are perfect for personal reflections, sketching, or for recording favorite quotations or poems.
  • Premium 120 gsm paper takes pen or pencil beautifully.
  • Paper is acid free and of archival quality.
  • Light gray lines subtly guide your writing.
  • An inside back cover pocket expands to hold notes, cards, mementos, and more.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Know when a stacked chart is the right choice

A stacked bar chart shows each category’s combined total and how its components contribute to that total. The bottom series shares a baseline across categories, but the interior segments do not; that makes precise comparisons between those interior values harder.

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

Quick Recap

SaleBestseller No. 4
Pandas Journal (Diary, Notebook)
Pandas Journal (Diary, Notebook)
Premium 120 gsm paper takes pen or pencil beautifully.; Paper is acid free and of archival quality.
$10.99
Bestseller No. 5
Pandas Funny GIS/Programming/Python T-Shirt, Men, Black, Small
Pandas Funny GIS/Programming/Python T-Shirt, Men, Black, Small
Funny design. Import pandas as pd, an all too familiar python code.; Lightweight, Classic fit, Double-needle sleeve and bottom hem
$19.99
Best Value
Pandas Funny GIS/Programming/Python T-Shirt, Men, Black, Small
  • Funny design. Import pandas as pd, an all too familiar python code.
  • Featuring a familiar python code, this will get a laugh from all the nearby programmers and GIS professionals.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
  • Use a stacked bar when the overall total and its composition both matter.
  • Use grouped bars when readers need to compare each series’ values across categories more precisely.
  • Use a 100% normalized stacked chart when the main question is each series’ share of a whole rather than the absolute totals. State how the values were normalized so readers do not mistake shares for raw amounts.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.