Skip to content
svgwaterfall

Waterfall

Which drivers explain the change from a starting total to an ending total?

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

How to read it

  1. Start at the first solid bar: the opening total.
  2. Follow the floating bars: each adds or subtracts from where the last ended.
  3. End at the closing total, and check the subtotals along the way.
  1. Callout 1: The opening total.
  2. Callout 2: A floating bar: an increase or a decrease.
  3. Callout 3: The closing total.

Watch out

  • The order of drivers changes how each looks; keep a meaningful order, such as the one used in your accounts.

Defaults

Closing total
On
Add a final bar with the ending total.
Value labels
On
Print each value on the chart.

Pinned in the code

  • Steps keep their order (declared levels, else first appearance); values are summed per step.
  • Totals with a value set the running level (bar from 0); totals without a value are subtotals at the running level; other steps add their change.
  • The closing total equals the opening total plus all changes.
  • Increases use the pass colour, decreases the fail colour; dashed connectors carry the running level.
# Waterfall — Codesplash Chart Lab (recipe "waterfall")
# controls: end=true, labels=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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"]

df = pd.read_csv("waterfall-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["driver"] = pd.Categorical(df["driver"].astype("string"), categories=["FY2025 revenue", "Price", "Volume", "Mix", "Gross", "FX", "Churn", "New logos"])

d = df.copy()
d["_step"] = d["driver"].astype(object).where(d["driver"].notna(), "(missing)").astype(str)
v = pd.to_numeric(d["change_m"], errors="coerce")
d["_v"] = v.where(np.isfinite(v))
d["_total"] = d["is_total"].astype(object) == True  # noqa: E712
seen = list(pd.unique(d["_step"]))  # first appearance
if isinstance(df["driver"].dtype, pd.CategoricalDtype):  # declared order first
    declared = [str(l) for l in df["driver"].cat.categories]
    seen = [l for l in declared if l in seen] + [s for s in seen if s not in declared]
g = d.groupby("_step", sort=False)
steps = pd.DataFrame({"value": g["_v"].sum(min_count=1), "total": g["_total"].any()}).reindex(seen)  # summed per step

rows, running = [], 0.0
for name, st in steps.iterrows():
    if st["total"]:  # totals with a value set the level; without one they are subtotals
        if pd.notna(st["value"]):
            running = st["value"]
        rows.append((name, "total" if pd.notna(st["value"]) else "subtotal", running, 0.0, running))
    else:
        delta = 0.0 if pd.isna(st["value"]) else st["value"]
        rows.append((name, "increase" if delta >= 0 else "decrease", delta, running, running + delta))
        running += delta
rows.append(("End", "total", running, 0.0, running))  # closing total
bars = pd.DataFrame(rows, columns=["step", "kind", "value", "start", "end"])
KIND_COLOR = {"increase": "#187c49", "decrease": "#c9302d", "total": PALETTE[0], "subtotal": PALETTE[0] + "8c"}

fig, ax = plt.subplots(figsize=(8, 4.5))
xs = np.arange(len(bars))
lo = bars[["start", "end"]].min(axis=1)
hi = bars[["start", "end"]].max(axis=1)
ax.bar(xs, hi - lo, bottom=lo, width=0.72, color=[KIND_COLOR[k] for k in bars["kind"]])
for i in range(len(bars) - 1):  # dashed connectors carry the running level
    ax.plot([i + 0.36, i + 0.64], [bars["end"][i]] * 2, color=plt.rcParams["axes.edgecolor"], linestyle="--", linewidth=0.8)
for i, b in bars.iterrows():
    text = f"{b.value:+,.4g}" if b.kind in ("increase", "decrease") else f"{b.value:,.4g}"
    ax.annotate(text, (i, max(b.start, b.end)), xytext=(0, 3), textcoords="offset points", ha="center", fontsize=7)
ax.axhline(0, color=plt.rcParams["axes.edgecolor"], linewidth=0.8)
ax.set_xticks(xs, bars["step"], rotation=30, ha="right")
ax.set_ylabel("change_m")
plt.show()

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