Skip to content
svgbrushablearea-stacked

Stacked area

How does the mix of a total change over time?

Demo data · seed 20261101 · 210 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read the top edge for the total.
  2. Read the band thickness for each series; the bottom band shares a flat baseline.
  3. Switch to 100% to see the mix change without the total's growth.
  1. Callout 1: Top edge: the total.
  2. Callout 2: Bottom band: the easiest series to read, because its baseline is flat.
  3. Callout 3: Upper bands ride on the ones below; read their thickness.

Watch out

  • Upper bands look like they grow whenever the bands below grow. Compare thickness, not height.

Defaults

100 % stacked
Off
Show each series as a share of the total, so you compare the mix rather than the size.
Series shown
6
How many series to show; the rest are grouped.
Range 2 to 8, step 1

Pinned in the code

  • Value per (time, series) = sum of the value column (row count when none); times are the distinct x values.
  • Series ordered by total, largest at the bottom; beyond the limit they are pooled as “Other” (grey).
  • 100 %: each series divided by the time point's total.
  • Only the bottom series has a common baseline: compare upper layers with care, or use small multiples.
# Stacked area — Codesplash Chart Lab (recipe "area-stacked")
# controls: percent=false, series=6
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("area-stacked-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

OTHER = "#9aa0a6"  # pooled levels
d = df[df["month"].notna()].copy()
d["_s"] = d["product_line"].astype(object).where(d["product_line"].notna(), "(missing)").astype(str)
d["_v"] = d["revenue_k"].where(np.isfinite(d["revenue_k"]), 0).fillna(0)  # value summed per time and series
totals = d.groupby("_s")["_v"].sum()
if isinstance(df["product_line"].dtype, pd.CategoricalDtype):  # declared order, else largest total first
    declared = [str(l) for l in df["product_line"].cat.categories]
    ranked = [l for l in declared if l in totals.index] + [s for s in totals.index if s not in declared]
else:
    ranked = sorted(totals.index, key=lambda s: (-totals[s], s))
keep = ranked[: 6 - 1] if len(ranked) > 6 else ranked  # beyond the limit → "Other"
series = keep + (["Other"] if len(ranked) > len(keep) else [])
d["_s"] = d["_s"].where(d["_s"].isin(keep), "Other")
wide = d.pivot_table(index="month", columns="_s", values="_v", aggfunc="sum", fill_value=0).reindex(columns=series, fill_value=0).sort_index()
colors = [OTHER if s == "Other" else PALETTE[i % len(PALETTE)] for i, s in enumerate(series)]
hatches = [SERIES_HATCHES[7 if s == "Other" else i % 8] for i, s in enumerate(series)]  # texture per layer, as in the app

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.stackplot(wide.index, wide.T.to_numpy(), labels=series, colors=colors, alpha=0.9, hatch=hatches, hatchcolor=HATCH_INK, linewidth=0)  # first series at the bottom
ax.set_xlabel("month")
ax.set_ylabel("revenue_k")
ax.legend(title="product_line", loc="upper left", bbox_to_anchor=(1.01, 1))
plt.show()

Needs pandas, numpy, matplotlib · reads area-stacked-demo.csv · app theme from the optional codesplash helper