Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

Create a Stacked Bar Chart with Negative Values in Matplotlib

Use separate positive and negative running totals to stack mixed-sign values around zero in Matplotlib.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use matplotlib.pyplot.bar() with an explicit bottom for each series. For mixed positive and negative values, track two running totals per category: positives stack upward from zero, while negatives stack downward. A single running total will put some segments on the wrong side of the baseline.

Build the chart with separate positive and negative totals

This example stacks each value on the same side of zero as its sign. The bottom array selects the starting point for each category; the totals are then updated separately for the next series.

import matplotlib.pyplot as plt
import numpy as np

labels = ["Jan", "Feb", "Mar", "Apr"]
data = {
    "Series A": np.array([12, -5, 8, -3]),
    "Series B": np.array([4, -7, -2, 6]),
    "Series C": np.array([-3, 2, 5, -4]),
}

fig, ax = plt.subplots()
pos_bottom = np.zeros(len(labels))
neg_bottom = np.zeros(len(labels))

for name, values in data.items():
    bottom = np.where(values >= 0, pos_bottom, neg_bottom)
    ax.bar(labels, values, bottom=bottom, label=name)
    pos_bottom += np.clip(values, 0, None)
    neg_bottom += np.clip(values, None, 0)

ax.axhline(0, color="black", linewidth=0.8)
ax.set_ylabel("Value")
ax.legend()
plt.show()

The loop applies the logic element by element, so one series can be positive in one category and negative in another. np.clip(values, 0, None) contributes only positive values to the upward total; np.clip(values, None, 0) contributes only negative values to the downward total.

Why bottom needs an explicit baseline

bottom tells Matplotlib where each vertical bar segment begins. It is not automatically accumulated across separate calls to bar(), so pass the appropriate baseline for every category and series. The official stacked-bar example illustrates cumulative bottoms for conventional positive stacks; the two-total approach extends that baseline behavior to mixed signs. The [Matplotlib 3.11.0 bar API reference](https://matplotlib.org/3.11.0/api/_as_gen/matplotlib.pyplot.bar.html) documents the bottom parameter.

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

Avoid common stacking errors

  • Do not use only the immediately previous series as the baseline. A stack needs the cumulative total of all earlier values on that same side of zero.
  • Do not use one sign-blind running sum. It can place a later segment on the wrong side of zero or overlap the other stack.
  • Do not change negative values to absolute values unless the chart is meant to show magnitudes rather than signed contributions; taking absolute values changes what the data means.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Make sure a stacked chart fits the comparison

A diverging stack is useful when the goal is to show signed contributions and how they accumulate above and below zero. Add a zero reference line, clear series labels, and units that identify what the values measure. If the priority is precise comparison of each individual series across categories, grouped bars may be easier to read: segments that do not start at zero are harder to compare directly.

This example uses vertical bar(). For horizontal bars, barh() has an analogous baseline parameter named left; check its API documentation before adapting the code.

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.