Skip to content
svgbrushableslope

Slope chart

Which categories rose or fell between two points in time — and did the ranking change?

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

How to read it

  1. Follow each line from left to right: up means it rose.
  2. Check where lines cross: the ranking changed there.
  3. Read the labels at both ends for the values.
  1. Callout 1: A steep rising line: a big gain.
  2. Callout 2: Coloured lines: the biggest movers.
  3. 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