svgbrushableslope
Slope chart
Which categories rose or fell between two points in time — and did the ranking change?
How to read it
- Follow each line from left to right: up means it rose.
- Check where lines cross: the ranking changed there.
- Read the labels at both ends for the values.
- Callout 1: A steep rising line: a big gain.
- Callout 2: Coloured lines: the biggest movers.
- Callout 3: End labels: the second period's value.
Watch out
- Two time points cannot show a trend, and many crossing lines become unreadable.
Defaults
- Aggregate
- Sum
- How rows combine into one number per group or period, such as a sum or a mean.
- Also: Mean · Median · Count
- Colour
- Emphasise biggest movers
- How bars or lines are coloured.
- Also: Up / down
- Movers emphasised
- 3
- How many of the biggest movers get colour.
- Range 1 to 8, step 1
- Categories
- 8
- How many categories to show; the rest are grouped.
- Range 3 to 15, step 1
Pinned in the code
- Values are per-category aggregates (sum by default) of the first two period levels; categories missing a period are dropped.
- The top N categories by the second period's value are drawn; the N largest absolute changes are emphasised (increase in blue, decrease in orange-red), the rest are grey.
- End labels are nudged apart (≥ 12.5 px) so they never overlap; lines keep their true end positions.
# Slope chart — Codesplash Chart Lab (recipe "slope")
# controls: stat=sum, color=emphasis, emphasis=3, top=8
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("slope-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["year"] = pd.Categorical(df["year"].astype("string"), categories=["2024", "2026"])
def levels(s):
"""Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(c) for c in s.cat.categories]
counts = s.dropna().astype(str).value_counts()
return sorted(counts.index, key=lambda k: (-counts[k], k))
periods = levels(df["year"])[:2] # from → to: the first two period levels
d = df[["brand", "units_k", "year"]].dropna()
d = d.assign(_cat=d["brand"].astype(str), _per=d["year"].astype(str))
d = d[d["_per"].isin(periods)]
w = d.groupby(["_cat", "_per"])["units_k"].agg("sum").unstack().reindex(columns=periods).dropna() # both periods needed
w.columns = ["start", "end"] # from → to
w["gap"] = w["end"] - w["start"]
w = w.rename_axis("level").reset_index()
w = w.sort_values("end", ascending=False, kind="stable").head(8) # top N by the second period
movers = set(w.loc[w["gap"].abs().sort_values(ascending=False, kind="stable").index[:3], "level"]) # largest |change|
w["color"] = [(PALETTE[0] if g >= 0 else "#ce5342") if lvl in movers else "#9aa0a6" for lvl, g in zip(w["level"], w["gap"])]
def nudge(ys, gap):
"""Spread label positions so neighbours are at least `gap` apart (lines keep their true ends)."""
ys = np.asarray(ys, dtype=float)
order = np.argsort(ys)
out = ys.copy()
for k in range(1, len(order)):
out[order[k]] = max(out[order[k]], out[order[k - 1]] + gap)
return out
fig, ax = plt.subplots(figsize=(6, 5))
for row in w.itertuples():
ax.plot([0, 1], [row.start, row.end], color=row.color, linewidth=2.2 if row.color != "#9aa0a6" else 1.2, marker="o")
gap = 0.035 * (np.nanmax(w[["start", "end"]].to_numpy()) - np.nanmin(w[["start", "end"]].to_numpy()) or 1)
for side, col, ha in ((0, "start", "right"), (1, "end", "left")):
for yl, row in zip(nudge(w[col], gap), w.itertuples()):
value = row.start if side == 0 else row.end
text = f"{row.level} {value:,.4g}" if side == 0 else f"{value:,.4g} {row.level}"
ax.text(side + (-0.04 if side == 0 else 0.04), yl, text, ha=ha, va="center", fontsize=8, color=row.color)
ax.set_xticks([0, 1], periods)
ax.set_xlim(-0.6, 1.6)
ax.set_ylabel("Sum of units_k")
ax.grid(axis="x", visible=False)
plt.show()Needs pandas, numpy, matplotlib · reads slope-demo.csv · app theme from the optional codesplash helper
# Slope chart — Codesplash Chart Lab (recipe "slope")
# controls: stat=sum, color=emphasis, emphasis=3, top=8
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("slope-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["year"] = pd.Categorical(df["year"].astype("string"), categories=["2024", "2026"])
def levels(s):
"""Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(c) for c in s.cat.categories]
counts = s.dropna().astype(str).value_counts()
return sorted(counts.index, key=lambda k: (-counts[k], k))
periods = levels(df["year"])[:2] # from → to: the first two period levels
d = df[["brand", "units_k", "year"]].dropna()
d = d.assign(_cat=d["brand"].astype(str), _per=d["year"].astype(str))
d = d[d["_per"].isin(periods)]
w = d.groupby(["_cat", "_per"])["units_k"].agg("sum").unstack().reindex(columns=periods).dropna() # both periods needed
w.columns = ["start", "end"] # from → to
w["gap"] = w["end"] - w["start"]
w = w.rename_axis("level").reset_index()
w = w.sort_values("end", ascending=False, kind="stable").head(8) # top N by the second period
movers = set(w.loc[w["gap"].abs().sort_values(ascending=False, kind="stable").index[:3], "level"]) # largest |change|
w["color"] = [(PALETTE[0] if g >= 0 else "#ce5342") if lvl in movers else "#9aa0a6" for lvl, g in zip(w["level"], w["gap"])]
fig = go.Figure()
for row in w.itertuples():
fig.add_scatter(x=periods, y=[row.start, row.end], mode="lines+markers+text", line=dict(color=row.color, width=3 if row.color != "#9aa0a6" else 1.5),
text=[f"{row.level} {row.start:,.4g}", f"{row.end:,.4g} {row.level}"], textposition=["middle left", "middle right"], showlegend=False)
fig.update_layout(yaxis_title="Sum of units_k", xaxis=dict(type="category", range=[-0.8, 1.8]))
fig.show()Needs pandas, numpy, plotly · reads slope-demo.csv · app theme from the optional codesplash helper
# Slope chart — Codesplash Chart Lab (recipe "slope")
# controls: stat=sum, color=emphasis, emphasis=3, top=8
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("slope-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["brand"]] <- factor(df[["brand"]])
df[["year"]] <- factor(df[["year"]], levels = c("2024", "2026"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
periods <- head(levels(df[["year"]]), 2) # from → to: the first two period levels
cat <- as.character(df[["brand"]])
per <- as.character(df[["year"]])
val <- df[["units_k"]]
ok <- !is.na(cat) & !is.na(val) & per %in% periods
a <- tapply(val[ok & per == periods[1]], cat[ok & per == periods[1]], sum)
b <- tapply(val[ok & per == periods[2]], cat[ok & per == periods[2]], sum)
both <- intersect(names(a), names(b)) # categories missing either period are dropped
w <- data.frame(level = both, from = as.numeric(a[both]), to = as.numeric(b[both]))
w$gap <- w$to - w$from
w <- head(w[order(-w$to), ], 8) # top N by the second period
movers <- w$level[order(-abs(w$gap))][seq_len(min(3, nrow(w)))] # largest |change|
w$color <- ifelse(w$level %in% movers, ifelse(w$gap >= 0, cs_cat[1], "#ce5342"), "#9aa0a6")
nudge <- function(ys, gap) {
# spread label positions so neighbours are at least `gap` apart (lines keep their true ends)
o <- order(ys)
out <- ys
for (k in seq_along(o)[-1]) out[o[k]] <- max(out[o[k]], out[o[k - 1]] + gap)
out
}
gap <- 0.035 * diff(range(c(w$from, w$to)))
w$from_label <- nudge(w$from, gap)
w$to_label <- nudge(w$to, gap)
p <- ggplot(w) +
geom_segment(aes(x = 1, xend = 2, y = from, yend = to, colour = color), linewidth = 1) +
geom_point(aes(x = 1, y = from, colour = color), size = 2) +
geom_point(aes(x = 2, y = to, colour = color), size = 2) +
geom_text(aes(x = 0.95, y = from_label, label = paste(level, prettyNum(signif(from, 4), big.mark = ",")), colour = color), hjust = 1, size = 2.8) +
geom_text(aes(x = 2.05, y = to_label, label = paste(prettyNum(signif(to, 4), big.mark = ","), level), colour = color), hjust = 0, size = 2.8) +
scale_colour_identity() +
scale_x_continuous(breaks = 1:2, labels = periods, limits = c(0.3, 2.7)) +
labs(x = NULL, y = "Sum of units_k") +
theme_cs
print(p)Needs ggplot2 · reads slope-demo.csv · app theme from the optional codesplashr helper
-- Slope chart — Codesplash Chart Lab (recipe "slope")
-- controls: stat=sum, color=emphasis, emphasis=3, top=8
-- Sum of units_k per category for the first two period levels (from → to)
WITH
p(level, rk) AS (VALUES ('2024', 1), ('2026', 2)),
cells AS (
SELECT s."brand"::VARCHAR AS level, p.rk, sum(s."units_k") AS value
FROM read_csv('slope-demo.csv') s JOIN p ON p.level = s."year"::VARCHAR
WHERE p.rk <= 2 AND s."brand" IS NOT NULL AND s."units_k" IS NOT NULL
GROUP BY 1, 2
)
SELECT level,
max(value) FILTER (WHERE rk = 1) AS "from",
max(value) FILTER (WHERE rk = 2) AS "to",
"to" - "from" AS gap
FROM cells
GROUP BY level
HAVING count(*) = 2
ORDER BY gap DESC, level;Needs duckdb · reads slope-demo.csv