svgfunnel
Funnel
Where do people drop out of a multi-step process?
How to read it
- Read top to bottom: each row is a stage.
- Read the share on the right against the first stage.
- Read the step conversion for the biggest drop between neighbours.
- Callout 1: The first stage: everyone who started.
- Callout 2: The biggest narrowing: the step to investigate.
- Callout 3: Overall share, and share of the previous stage.
Watch out
- It compares counts at one time. Users still in progress can look like drop-off unless you fix a window.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Stages in declared level order (else first appearance); value = sum of the count column or rows per stage.
- Overall conversion = stage / first stage; step conversion = stage / previous stage.
- Bar width ∝ value on a linear scale (not area); connectors show the step loss.
- A funnel assumes each stage is a subset of the previous one; check that the counts never increase.
# Funnel — Codesplash Chart Lab (recipe "funnel")
# controls: defaults
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("funnel-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["stage"] = pd.Categorical(df["stage"].astype("string"), categories=["Visited", "Viewed product", "Added to cart", "Checkout", "Purchased"])
d = df[df["stage"].notna()].copy()
d["_k"] = d["stage"].astype(str)
d["_v"] = 1.0 # no value column: count rows
sums = d.groupby("_k", sort=False)["_v"].sum() # first-appearance order
if isinstance(df["stage"].dtype, pd.CategoricalDtype): # declared order first
declared = [str(l) for l in df["stage"].cat.categories]
sums = sums.reindex([l for l in declared if l in sums.index] + [s for s in sums.index if s not in declared])
f = sums.rename("value").rename_axis("stage").reset_index()
f["overall"] = f["value"] / f["value"].iloc[0] # conversion from the first stage
f["step"] = (f["value"] / f["value"].shift(1)).fillna(1.0) # conversion from the previous stage
fig, ax = plt.subplots(figsize=(8, 4.5))
y = np.arange(len(f))[::-1] # first stage on top
ax.barh(y, f["value"], left=-f["value"] / 2, color=PALETTE[0], height=0.72) # width ∝ value, centred
for yi, r in zip(y, f.itertuples()):
ax.text(0, yi, f"{r.value:,.0f}", ha="center", va="center", color="white", fontsize=8, fontweight="bold")
ax.text(f["value"].max() / 2 * 1.04, yi, f"{r.overall:.1%} of first · {r.step:.1%} of previous", va="center", fontsize=7.5)
ax.set_yticks(y, f["stage"])
ax.set_xticks([])
ax.set_xlim(-f["value"].max() / 2 * 1.05, f["value"].max() * 1.15)
ax.grid(False)
plt.show()Needs pandas, numpy, matplotlib · reads funnel-demo.csv · app theme from the optional codesplash helper
# Funnel — Codesplash Chart Lab (recipe "funnel")
# controls: defaults
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("funnel-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["stage"] = pd.Categorical(df["stage"].astype("string"), categories=["Visited", "Viewed product", "Added to cart", "Checkout", "Purchased"])
d = df[df["stage"].notna()].copy()
d["_k"] = d["stage"].astype(str)
d["_v"] = 1.0 # no value column: count rows
sums = d.groupby("_k", sort=False)["_v"].sum() # first-appearance order
if isinstance(df["stage"].dtype, pd.CategoricalDtype): # declared order first
declared = [str(l) for l in df["stage"].cat.categories]
sums = sums.reindex([l for l in declared if l in sums.index] + [s for s in sums.index if s not in declared])
fig = go.Figure(go.Funnel(y=list(sums.index), x=sums.to_numpy(), marker_color=PALETTE[0],
textinfo="value+percent initial+percent previous")) # overall and step conversion
fig.show()Needs pandas, numpy, plotly · reads funnel-demo.csv · app theme from the optional codesplash helper
# Funnel — Codesplash Chart Lab (recipe "funnel")
# controls: defaults
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("funnel-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["stage"]] <- factor(df[["stage"]], levels = c("Visited", "Viewed product", "Added to cart", "Checkout", "Purchased"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
k <- as.character(df[["stage"]])
v <- rep(1, length(k)) # no value column: count rows
v[!is.finite(v)] <- 0
ok <- !is.na(k)
ord <- c(intersect(levels(df[["stage"]]), k[ok]), setdiff(unique(k[ok]), levels(df[["stage"]]))) # declared order first
sums <- tapply(v[ok], k[ok], sum)[ord]
f <- data.frame(stage = names(sums), value = as.numeric(sums))
f$overall <- f$value / f$value[1] # conversion from the first stage
f$step <- f$value / c(f$value[1], head(f$value, -1)) # conversion from the previous stage
f$y <- rev(seq_len(nrow(f))) # first stage on top
wmax <- max(f$value)
p <- ggplot(f) +
geom_rect(aes(xmin = -value / 2, xmax = value / 2, ymin = y - 0.36, ymax = y + 0.36), fill = cs_cat[1]) + # width ∝ value, centred
geom_text(aes(x = 0, y = y, label = format(round(value), big.mark = ",")), colour = "white", size = 2.8, fontface = "bold") +
geom_text(aes(x = wmax / 2 * 1.04, y = y, label = sprintf("%.1f%% of first · %.1f%% of previous", 100 * overall, 100 * step)), hjust = 0, size = 2.5) +
scale_y_continuous(breaks = f$y, labels = f$stage) +
scale_x_continuous(limits = c(-wmax / 2 * 1.05, wmax * 1.2)) +
labs(x = NULL, y = NULL) +
theme_cs +
theme(axis.text.x = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)Needs ggplot2 · reads funnel-demo.csv · app theme from the optional codesplashr helper
-- Funnel — Codesplash Chart Lab (recipe "funnel")
-- controls: defaults
-- value per stage (declared order) with overall and step conversion
WITH s AS (SELECT *, row_number() OVER () AS _row FROM read_csv('funnel-demo.csv')),
lv(level, rk) AS (VALUES ('Visited', 1), ('Viewed product', 2), ('Added to cart', 3), ('Checkout', 4), ('Purchased', 5)),
stages AS (
SELECT s."stage"::VARCHAR AS stage,
count(*) AS value,
coalesce(min(lv.rk), 1e9 + min(s._row)) AS ord
FROM s
LEFT JOIN lv ON lv.level = s."stage"::VARCHAR
WHERE s."stage" IS NOT NULL
GROUP BY 1
)
SELECT stage, value,
value / first_value(value) OVER (ORDER BY ord) AS overall_rate,
value / coalesce(lag(value) OVER (ORDER BY ord), value) AS step_rate,
coalesce(lag(value) OVER (ORDER BY ord) - value, 0) AS lost
FROM stages
ORDER BY ord;Needs duckdb · reads funnel-demo.csv