svgwaterfall
Waterfall
Which drivers explain the change from a starting total to an ending total?
How to read it
- Start at the first solid bar: the opening total.
- Follow the floating bars: each adds or subtracts from where the last ended.
- End at the closing total, and check the subtotals along the way.
- Callout 1: The opening total.
- Callout 2: A floating bar: an increase or a decrease.
- 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
# Waterfall — Codesplash Chart Lab (recipe "waterfall")
# controls: end=true, labels=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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"}
measure = {"total": "absolute", "subtotal": "total", "increase": "relative", "decrease": "relative"}
fig = go.Figure(go.Waterfall(
x=bars["step"], y=[0 if k == "subtotal" else v for k, v in zip(bars["kind"], bars["value"])],
measure=[measure[k] for k in bars["kind"]],
# the closing total is an "absolute" bar at the running level
increasing=dict(marker_color=KIND_COLOR["increase"]), decreasing=dict(marker_color=KIND_COLOR["decrease"]),
totals=dict(marker_color=KIND_COLOR["total"]), connector=dict(line=dict(dash="dash", width=1)),
textposition="outside", texttemplate=["%{delta:+,.4g}" if k in ("increase", "decrease") else "%{final:,.4g}" for k in bars["kind"]],
))
fig.update_layout(yaxis_title="change_m", showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads waterfall-demo.csv · app theme from the optional codesplash helper
# Waterfall — Codesplash Chart Lab (recipe "waterfall")
# controls: end=true, labels=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("waterfall-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["is_total"]] <- as.logical(df[["is_total"]])
df[["driver"]] <- factor(df[["driver"]], levels = c("FY2025 revenue", "Price", "Volume", "Mix", "Gross", "FX", "Churn", "New logos"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
step <- as.character(df[["driver"]])
step[is.na(step)] <- "(missing)"
v <- suppressWarnings(as.numeric(df[["change_m"]]))
v[!is.finite(v)] <- NA
is_total <- df[["is_total"]] %in% TRUE
ord <- c(intersect(levels(df[["driver"]]), step), setdiff(unique(step), levels(df[["driver"]]))) # declared order first
rows <- list()
running <- 0
for (s in ord) {
vals <- v[step == s]
value <- if (any(!is.na(vals))) sum(vals, na.rm = TRUE) else NA # summed per step
if (any(is_total[step == s])) { # totals with a value set the level; without one they are subtotals
if (!is.na(value)) running <- value
rows[[length(rows) + 1]] <- data.frame(step = s, kind = if (is.na(value)) "subtotal" else "total", value = running, start = 0, end = running)
} else {
delta <- if (is.na(value)) 0 else value
rows[[length(rows) + 1]] <- data.frame(step = s, kind = if (delta >= 0) "increase" else "decrease", value = delta, start = running, end = running + delta)
running <- running + delta
}
}
rows[[length(rows) + 1]] <- data.frame(step = "End", kind = "total", value = running, start = 0, end = running) # closing total
bars <- do.call(rbind, rows)
bars$i <- seq_len(nrow(bars))
kind_color <- c(increase = "#187c49", decrease = "#c9302d", total = cs_cat[1], subtotal = grDevices::adjustcolor(cs_cat[1], 0.55))
p <- ggplot(bars) +
geom_rect(aes(xmin = i - 0.36, xmax = i + 0.36, ymin = pmin(start, end), ymax = pmax(start, end), fill = kind)) +
geom_segment(data = bars[-nrow(bars), ], aes(x = i + 0.36, xend = i + 0.64, y = end, yend = end), linetype = "dashed", linewidth = 0.3) +
geom_text(aes(x = i, y = pmax(start, end), label = ifelse(kind %in% c("increase", "decrease"), sprintf("%+.4g", value), sprintf("%.4g", value))), vjust = -0.5, size = 2.5) +
geom_hline(yintercept = 0, linewidth = 0.3) +
scale_fill_manual(values = kind_color, name = NULL) +
scale_x_continuous(breaks = bars$i, labels = bars$step) +
labs(x = NULL, y = "change_m") +
theme_cs +
theme(axis.text.x = element_text(angle = 30, hjust = 1))
print(p)Needs ggplot2 · reads waterfall-demo.csv · app theme from the optional codesplashr helper
-- Waterfall — Codesplash Chart Lab (recipe "waterfall")
-- controls: end=true, labels=true
-- bridge geometry: per-step sums in declared order; totals with a value reset the running level
WITH s AS (SELECT *, row_number() OVER () AS _row FROM read_csv('waterfall-demo.csv')),
lv(level, rk) AS (VALUES ('FY2025 revenue', 1), ('Price', 2), ('Volume', 3), ('Mix', 4), ('Gross', 5), ('FX', 6), ('Churn', 7), ('New logos', 8)),
steps AS (
SELECT coalesce(s."driver"::VARCHAR, '(missing)') AS step,
sum(CASE WHEN isfinite(s."change_m") THEN s."change_m" END) AS value,
bool_or(coalesce(s."is_total", false)) AS is_total,
coalesce(min(lv.rk), 1e9 + min(s._row)) AS ord
FROM s
LEFT JOIN lv ON lv.level = s."driver"::VARCHAR
GROUP BY 1
),
g AS (SELECT *, sum(CASE WHEN is_total AND value IS NOT NULL THEN 1 ELSE 0 END) OVER (ORDER BY ord) AS grp FROM steps),
r AS (
SELECT *,
coalesce(max(CASE WHEN is_total AND value IS NOT NULL THEN value END) OVER (PARTITION BY grp), 0)
+ sum(CASE WHEN is_total THEN 0 ELSE coalesce(value, 0) END) OVER (PARTITION BY grp ORDER BY ord) AS level_end
FROM g
)
SELECT step,
CASE WHEN is_total AND value IS NOT NULL THEN 'total' WHEN is_total THEN 'subtotal'
WHEN coalesce(value, 0) >= 0 THEN 'increase' ELSE 'decrease' END AS kind,
CASE WHEN is_total THEN level_end ELSE coalesce(value, 0) END AS change,
CASE WHEN is_total THEN 0 ELSE level_end - coalesce(value, 0) END AS start,
level_end AS "end"
FROM r
ORDER BY ord;Needs duckdb · reads waterfall-demo.csv