Area Charts and Stacked Area Charts in Matplotlib

Make area charts with fill_between and stacked area charts with stackplot, show percentages, label the layers, and draw stream graphs.

To make a stacked area chart in Matplotlib, call ax.stackplot(x, [y1, y2, y3], labels=names). For a single filled area, use ax.fill_between(x, y), which shades from the line down to zero.

Quick Example

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(61)
hours = np.arange(25)
wind = 18 + 5 * np.cos(hours / 4) + rng.normal(0, 0.8, hours.size)
solar = 30 * np.clip(np.sin((hours - 6) / 12 * np.pi), 0, None)
hydro = 12 + 2 * np.sin(hours / 5)
demand = 55 + 14 * np.sin((hours - 9) / 24 * 2 * np.pi) + 6 * np.exp(-((hours - 19) / 2) ** 2)
gas = np.clip(demand - wind - solar - hydro, 0, None)

sources = [hydro, wind, solar, gas]
names = ["Hydro", "Wind", "Solar", "Gas"]
colors = ["#1d4ed8", "#14b8a6", "#facc15", "#78716c"]

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.stackplot(hours, sources, labels=names, colors=colors)
ax.set_xlim(0, 24)
ax.set_xticks(range(0, 25, 4), [f"{h:02d}:00" for h in range(0, 25, 4)])
ax.set_ylim(0, 85)
ax.set_title("Electricity generation by source over one day")
ax.set_ylabel("Gigawatts")
ax.legend(loc="upper left", ncols=4)
plt.show()
total = np.sum(sources, axis=0)

Matplotlib stacked area chart of electricity from hydro, wind, solar, and gas over 24 hours, with solar peaking at noon and gas in the evening

Solar peaks at 30 GW at noon, about 46% of generation at that hour, and gas climbs to 42 GW at 18:00 as solar drops away. The first series in the list sits at the bottom of the stack. The code targets Matplotlib 3.10 and 3.11.

stackplot accepts the series as a list, a 2D array with one row per series, or separate arguments (ax.stackplot(x, y1, y2)). All of them must have the same length as x.

Which Area Chart Should I Use?

You want to show... Use
The size of one quantity over time fill_between plus a line
A total and the parts that make it up stackplot
How each part's share changes stackplot on percentages
A few distributions that overlap fill_between with alpha
Gains and losses around a baseline fill_between with where=
The ebb and flow of many series stackplot with baseline="wiggle"

If readers need to compare individual series precisely, use a line chart with multiple lines. Only the bottom layer of a stack has a flat baseline, so the other layers are hard to judge by eye.

A Single Area Chart with fill_between

Plot the line on top of a translucent fill. ax.set_ylim(0) keeps the baseline at zero, which matters here because the filled area is read as a quantity.

weeks = np.arange(1, 53)
visitors = 800 + 14 * weeks + 220 * np.sin(weeks / 4) + rng.normal(0, 60, weeks.size)

fig, ax = plt.subplots(figsize=(8, 3.8), layout="constrained")
ax.fill_between(weeks, visitors, color="#c084fc", alpha=0.35)
ax.plot(weeks, visitors, color="#7e22ce", linewidth=2)
ax.set_xlim(1, 52)
ax.set_ylim(0)
ax.set_title("Weekly museum visitors")
ax.set_xlabel("Week")
plt.show()

Matplotlib area chart of weekly museum visitors with a purple line over a light purple fill

To fade the fill from the line toward the baseline, see gradient fills under a Matplotlib line.

100% Stacked Area Chart

stackplot has no percentage option, so divide each series by the column totals first. sales / sales.sum(axis=0) does that for an array with one row per series. PercentFormatter(xmax=1) shows the fractions as percentages.

from matplotlib.ticker import PercentFormatter

years = np.arange(2018, 2027)
sales = np.array([
    [82, 78, 66, 60, 52, 45, 38, 32, 27],   # Petrol
    [6, 8, 14, 18, 22, 25, 27, 28, 28],     # Hybrid
    [2, 4, 8, 15, 23, 31, 40, 49, 58],      # Electric
])
share = sales / sales.sum(axis=0)

fig, axes = plt.subplots(1, 2, figsize=(11, 3.8), layout="constrained")
car_colors = ["#b45309", "#84cc16", "#0891b2"]
axes[0].stackplot(years, sales, colors=car_colors)
axes[0].set_title("Cars sold (thousands)")
axes[1].stackplot(years, share, labels=["Petrol", "Hybrid", "Electric"], colors=car_colors)
axes[1].set_title("Share of sales")
axes[1].yaxis.set_major_formatter(PercentFormatter(xmax=1))
axes[1].set_ylim(0, 1)
for ax in axes:
    ax.set_xlim(2018, 2026)
fig.legend(loc="outside lower center", ncols=3)
plt.show()

Two stacked area charts of car sales by powertrain, one in thousands of cars and one as shares adding to 100 percent

The two views answer different questions. Total sales grow from 90 to 113 thousand, while the electric share goes from 2% to 51% and petrol falls from 91% to 24%.

Label the Areas Directly

Writing names inside the layers saves readers from matching colors to a legend. The middle of each layer is the cumulative sum minus half of that layer's own height. A white edgecolor separates neighboring colors.

fig, ax = plt.subplots(figsize=(8, 4.2), layout="constrained")
ax.stackplot(years, share, colors=car_colors, edgecolor="white", linewidth=1.5)
middles = np.cumsum(share, axis=0) - share / 2
for name, x, i in [("Petrol", 2019, 0), ("Hybrid", 2022, 1), ("Electric", 2025, 2)]:
    col = list(years).index(x)
    ax.text(x, middles[i, col], f"{name}\n{share[i, col]:.0%}", ha="center", va="center",
            color="white" if name != "Hybrid" else "black", fontweight="bold")
ax.set_xlim(2018, 2026)
ax.set_ylim(0, 1)
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1))
ax.set_title("Share of car sales by powertrain")
plt.show()

100 percent stacked area chart with Petrol, Hybrid, and Electric names and percentages written inside the colored layers

Overlapping Areas

To compare shapes without stacking, call fill_between once per series with a low alpha. This stays readable for two or three series.

minutes = np.linspace(0, 120, 400)
curves = {
    "Weekday": (35, 11, 1.0, "#2563eb"),
    "Saturday": (62, 17, 0.8, "#f97316"),
    "Sunday": (85, 14, 0.65, "#16a34a"),
}
fig, ax = plt.subplots(figsize=(8, 3.8), layout="constrained")
for name, (peak, spread, height, color) in curves.items():
    y = height * np.exp(-0.5 * ((minutes - peak) / spread) ** 2)
    ax.fill_between(minutes, y, color=color, alpha=0.35, label=name)
    ax.plot(minutes, y, color=color, linewidth=1.5)
ax.set_xlim(0, 120)
ax.set_ylim(0)
ax.set_yticks([])
ax.set_title("When runners finish their workout")
ax.set_xlabel("Minutes after the park opens")
ax.legend()
plt.show()

Three overlapping translucent area charts showing weekday, Saturday, and Sunday finishing times

With real observations instead of smooth curves, you'd estimate each density first, for example with a histogram or KDE in Seaborn.

Color Areas Above and Below Zero

Pass a boolean array to where and call fill_between twice. interpolate=True finds the exact crossing points, so there are no gaps where the series changes sign.

days = np.arange(180)
balance = np.cumsum(rng.normal(0.05, 1.6, days.size))

fig, ax = plt.subplots(figsize=(8, 3.8), layout="constrained")
ax.fill_between(days, balance, 0, where=balance >= 0, interpolate=True,
                color="#059669", alpha=0.6, label="Surplus")
ax.fill_between(days, balance, 0, where=balance < 0, interpolate=True,
                color="#e11d48", alpha=0.6, label="Deficit")
ax.plot(days, balance, color="#111827", linewidth=1)
ax.axhline(0, color="#111827", linewidth=1)
ax.set_xlim(0, 179)
ax.set_title("Running water balance of a reservoir")
ax.set_xlabel("Day")
ax.set_ylabel("Million litres")
ax.legend()
plt.show()

Reservoir water balance line with green fill where it is above zero and red fill where it is below

Stream Graphs with baseline="wiggle"

The baseline argument moves the bottom of the stack. "zero" is the default, "sym" centers the stack around zero, and "wiggle" and "weighted_wiggle" shift it to reduce the slopes of the layers.

months = np.arange(36)
genres = np.array([
    np.exp(-0.5 * ((months - c) / w) ** 2) * h + 1.5
    for c, w, h in [(4, 6, 9), (10, 8, 6), (17, 5, 11), (23, 9, 7), (30, 6, 10), (34, 7, 5)]
])

fig, axes = plt.subplots(1, 2, figsize=(11, 3.6), layout="constrained")
stream_colors = plt.colormaps["magma"](np.linspace(0.2, 0.85, len(genres)))
for ax, baseline in zip(axes, ["zero", "wiggle"]):
    ax.stackplot(months, genres, baseline=baseline, colors=stream_colors)
    ax.set_title(f'baseline="{baseline}"')
    ax.set_xlim(0, 35)
axes[1].set_yticks([])
plt.show()

The same six series drawn as a stacked area chart from zero and as a stream graph with a wiggle baseline

Once the baseline moves, y values no longer mean anything on their own, so hide the y ticks.

Practical Tips

  • Order layers deliberately: put the steadiest series at the bottom, since its wiggles carry into every layer above.
  • Stacking only makes sense for values that add up to a meaningful total, and negative values make a stack unreadable.
  • From pandas, df.plot.area() draws a stacked area chart with one layer per column. It raises a ValueError if a column mixes positive and negative values.
  • Fill in missing values before stacking. A gap in one layer affects the layers above it.

Similar Topics