svgsequence-sankey
Journey flow
Where do journeys go from each step to the next?
How to read it
- Read columns left to right as steps in a journey.
- Read ribbon width as how many journeys take that move.
- Look for the widest paths and for the (end) nodes, where journeys stop.
- Callout 1: The first step: where journeys start.
- Callout 2: A wide ribbon: a common move.
- Callout 3: Journeys that stop here.
Watch out
- It shows moves between adjacent steps; longer patterns aren't visible, and rare paths get collapsed.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
- Nodes are "step: event" pairs; within a step, the most frequent events are on top, then Other, then (end).
- Only the most frequent events get their own colour; the rest are grouped as Other by the run.
# Journey flow — Codesplash Chart Lab (recipe "sequence-sankey")
# 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("sequence-sankey-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
SRC = "from"
DST = "to"
N = "journeys"
d = df[[SRC, DST, N]].dropna()
d = d[d[N] > 0]
nodes = list(dict.fromkeys(list(d[SRC].astype(str)) + list(d[DST].astype(str))))
index = {n: i for i, n in enumerate(nodes)}
step = lambda n: int(str(n).split(":")[0].split()[-1]) if str(n).split(":")[0].split()[-1].isdigit() else 0 # labels are "step: event"
events = sorted({str(n).split(":", 1)[-1].strip() for n in nodes})
colour = {e: PALETTE[i % len(PALETTE)] for i, e in enumerate(events)}
steps = sorted({step(n) for n in nodes})
size = {n: max(d.loc[d[SRC].astype(str) == n, N].sum(), d.loc[d[DST].astype(str) == n, N].sum()) for n in nodes}
total = max(sum(size[n] for n in nodes if step(n) == s) for s in steps)
gap = 0.03 * total
top, out_at, in_at = {}, {}, {}
for s in steps:
y = 0.0
for n in sorted((n for n in nodes if step(n) == s), key=lambda n: -size[n]):
top[n] = out_at[n] = in_at[n] = y
y += size[n] + gap
fig, ax = plt.subplots(figsize=(9, 5))
for _, r in d.sort_values(N, ascending=False).iterrows(): # ribbons: width = journeys
a, b, w = str(r[SRC]), str(r[DST]), float(r[N])
x = np.linspace(step(a) + 0.03, step(b) - 0.03, 40)
t = (x - x[0]) / (x[-1] - x[0])
ease = 3 * t**2 - 2 * t**3
y0, y1 = out_at[a], in_at[b]
ax.fill_between(x, y0 + (y1 - y0) * ease, y0 + w + (y1 - y0) * ease, color=colour[b.split(":", 1)[-1].strip()], alpha=0.3, linewidth=0)
out_at[a] += w
in_at[b] += w
for n in nodes:
ax.fill_between([step(n) - 0.03, step(n) + 0.03], top[n], top[n] + size[n], color=colour[n.split(":", 1)[-1].strip()])
ax.text(step(n) + 0.05, top[n] + size[n] / 2, f"{n.split(':', 1)[-1].strip()} {size[n]:.0f}", fontsize=7, va="center")
ax.invert_yaxis()
ax.set_xticks(steps, [f"step {s}" for s in steps])
ax.set_yticks([])
plt.show()Needs pandas, numpy, matplotlib · reads sequence-sankey-demo.csv · app theme from the optional codesplash helper
# Journey flow — Codesplash Chart Lab (recipe "sequence-sankey")
# 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("sequence-sankey-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
SRC = "from"
DST = "to"
N = "journeys"
d = df[[SRC, DST, N]].dropna()
d = d[d[N] > 0]
nodes = list(dict.fromkeys(list(d[SRC].astype(str)) + list(d[DST].astype(str))))
index = {n: i for i, n in enumerate(nodes)}
step = lambda n: int(str(n).split(":")[0].split()[-1]) if str(n).split(":")[0].split()[-1].isdigit() else 0 # labels are "step: event"
fig = go.Figure(go.Sankey(node=dict(label=nodes, pad=12), link=dict(source=[index[str(v)] for v in d[SRC]], target=[index[str(v)] for v in d[DST]], value=d[N])))
fig.show()Needs pandas, numpy, plotly · reads sequence-sankey-demo.csv · app theme from the optional codesplash helper
# Journey flow — Codesplash Chart Lab (recipe "sequence-sankey")
# 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("sequence-sankey-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["from"]] <- factor(df[["from"]])
df[["to"]] <- factor(df[["to"]])
SRC <- "from"
DST <- "to"
N <- "journeys"
d <- data.frame(s = as.character(df[[SRC]]), t = as.character(df[[DST]]), n = df[[N]])
d <- d[is.finite(d$n) & d$n > 0, ]
step_of <- function(x) as.numeric(gsub("[^0-9]", "", sub(":.*", "", x))) # labels are "step: event"
event_of <- function(x) trimws(sub("^[^:]*:", "", x))
nodes <- unique(c(d$s, d$t))
size <- sapply(nodes, function(k) max(sum(d$n[d$s == k]), sum(d$n[d$t == k])))
node <- data.frame(id = nodes, step = step_of(nodes), event = event_of(nodes), size = size, top = 0, stringsAsFactors = FALSE)
gap <- 0.03 * max(tapply(node$size, node$step, sum))
for (s in unique(node$step)) {
ids <- which(node$step == s); ids <- ids[order(-node$size[ids])]
node$top[ids] <- cumsum(c(0, node$size[ids] + gap))[seq_along(ids)]
}
out_at <- setNames(node$top, node$id); in_at <- out_at
d <- d[order(-d$n), ]
ribbons <- do.call(rbind, lapply(seq_len(nrow(d)), function(i) { # width = journeys
a <- d$s[i]; b <- d$t[i]; w <- d$n[i]
x <- seq(step_of(a) + 0.03, step_of(b) - 0.03, length.out = 40)
u <- (x - x[1]) / (x[40] - x[1]); ease <- 3 * u^2 - 2 * u^3
y <- out_at[[a]] + (in_at[[b]] - out_at[[a]]) * ease
out_at[[a]] <<- out_at[[a]] + w; in_at[[b]] <<- in_at[[b]] + w
data.frame(id = i, x = c(x, rev(x)), y = c(y, rev(y + w)), event = event_of(b))
}))
p <- ggplot() +
geom_polygon(aes(x, y, group = id, fill = event), ribbons, alpha = 0.3) +
geom_rect(aes(xmin = step - 0.03, xmax = step + 0.03, ymin = top, ymax = top + size, fill = event), node) +
geom_text(aes(step + 0.05, top + size / 2, label = paste(event, round(size))), node, hjust = 0, size = 2.4) +
scale_y_reverse() + scale_fill_manual(values = rep_len(cs_cat, length(unique(node$event))), name = NULL) +
labs(x = "step", y = NULL) + theme_cs + theme(axis.text.y = element_blank())
print(p)Needs ggplot2 · reads sequence-sankey-demo.csv · app theme from the optional codesplashr helper