svgbrushabledumbbell
Dumbbell chart
How did each category change between two periods or conditions?
How to read it
- Read the two dots as before and after.
- Read the bar's length as the size of the change and the label as its value.
- Rows are sorted by change, so the biggest movers are together.
- Callout 1: The later value.
- Callout 2: The earlier value; the bar between them is the change.
- Callout 3: The change, with its sign.
Watch out
- It shows only two moments. A large change may be noise or part of a longer swing.
Defaults
- Aggregate
- Mean
- How rows combine into one number per group or period, such as a sum or a mean.
- Also: Sum · Median · Count
- Sort
- By change
- How rows are sorted.
- Also: By latest value · Alphabetical
- Top N
- 12
- How many categories to show.
- Range 3 to 30, step 1
- Change labels
- On
- Print the change beside each row.
Pinned in the code
- From/to are the first two levels of the period role (dictionary order, else frequency); categories missing either period are dropped.
- Each dot is the aggregate (mean by default; sum, type-7 median, count) of the category's rows in that period; the label is to − from.
- Sorted by the change (descending) so the biggest movers sit on top.
# Dumbbell chart — Codesplash Chart Lab (recipe "dumbbell")
# controls: stat=mean, sort=gap, top=12, 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("dumbbell-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=["2025", "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[["department", "engagement", "year"]].dropna()
d = d.assign(_cat=d["department"].astype(str), _per=d["year"].astype(str))
d = d[d["_per"].isin(periods)]
w = d.groupby(["_cat", "_per"])["engagement"].agg("mean").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(["gap", "level"], ascending=[False, True]).head(12) # biggest movers on top
fig, ax = plt.subplots(figsize=(7, 5))
y = np.arange(len(w))[::-1] # first row on top
ax.hlines(y, w["start"], w["end"], color="#ced1d6", linewidth=5, zorder=1)
ax.scatter(w["start"], y, s=60, color="#9aa0a6", label=periods[0], zorder=2)
ax.scatter(w["end"], y, s=60, color=PALETTE[0], label=periods[1], zorder=3)
for yi, row in zip(y, w.itertuples()):
ax.annotate(f"{row.gap:+.3g}", (max(row.start, row.end), yi), xytext=(8, 0), textcoords="offset points", va="center", fontsize=8)
ax.set_yticks(y, w["level"])
ax.set_xlabel("Mean engagement")
ax.set_ylabel("department")
ax.legend()
plt.show()Needs pandas, numpy, matplotlib · reads dumbbell-demo.csv · app theme from the optional codesplash helper
# Dumbbell chart — Codesplash Chart Lab (recipe "dumbbell")
# controls: stat=mean, sort=gap, top=12, 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("dumbbell-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=["2025", "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[["department", "engagement", "year"]].dropna()
d = d.assign(_cat=d["department"].astype(str), _per=d["year"].astype(str))
d = d[d["_per"].isin(periods)]
w = d.groupby(["_cat", "_per"])["engagement"].agg("mean").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(["gap", "level"], ascending=[False, True]).head(12) # biggest movers on top
fig = go.Figure()
for row in w.itertuples():
fig.add_shape(type="line", x0=row.start, x1=row.end, y0=row.level, y1=row.level, line=dict(color="#ced1d6", width=6), layer="below")
fig.add_scatter(x=w["start"], y=w["level"], mode="markers", name=periods[0], marker=dict(color="#9aa0a6", size=12))
fig.add_scatter(x=w["end"], y=w["level"], mode="markers+text", name=periods[1], marker=dict(color=PALETTE[0], size=12),
text=[f"{g:+.3g}" for g in w["gap"]], textposition="middle right")
fig.update_layout(xaxis_title="Mean engagement", yaxis_title="department", yaxis_autorange="reversed")
fig.show()Needs pandas, numpy, plotly · reads dumbbell-demo.csv · app theme from the optional codesplash helper
# Dumbbell chart — Codesplash Chart Lab (recipe "dumbbell")
# controls: stat=mean, sort=gap, top=12, 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("dumbbell-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["department"]] <- factor(df[["department"]])
df[["year"]] <- factor(df[["year"]], levels = c("2025", "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[["department"]])
per <- as.character(df[["year"]])
val <- df[["engagement"]]
ok <- !is.na(cat) & !is.na(val) & per %in% periods
a <- tapply(val[ok & per == periods[1]], cat[ok & per == periods[1]], mean)
b <- tapply(val[ok & per == periods[2]], cat[ok & per == periods[2]], mean)
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$gap, w$level), ], 12) # biggest movers on top
w$level <- factor(w$level, levels = rev(w$level))
pts <- rbind(data.frame(level = w$level, value = w$from, period = periods[1]),
data.frame(level = w$level, value = w$to, period = periods[2]))
pts$period <- factor(pts$period, levels = periods)
p <- ggplot(w) +
geom_segment(aes(x = from, xend = to, y = level, yend = level), colour = "#ced1d6", linewidth = 2.2) +
geom_point(data = pts, aes(value, level, colour = period), size = 3) +
geom_text(aes(x = pmax(from, to), y = level, label = sprintf("%+.3g", gap)), hjust = -0.3, size = 2.8) +
scale_colour_manual(values = setNames(c("#9aa0a6", cs_cat[1]), periods), name = NULL) +
scale_x_continuous(expand = expansion(mult = c(0.05, 0.12))) +
labs(x = "Mean engagement", y = "department") +
theme_cs
print(p)Needs ggplot2 · reads dumbbell-demo.csv · app theme from the optional codesplashr helper
-- Dumbbell chart — Codesplash Chart Lab (recipe "dumbbell")
-- controls: stat=mean, sort=gap, top=12, labels=true
-- Mean engagement per category for the first two period levels (from → to)
WITH
p(level, rk) AS (VALUES ('2025', 1), ('2026', 2)),
cells AS (
SELECT s."department"::VARCHAR AS level, p.rk, avg(s."engagement") AS value
FROM read_csv('dumbbell-demo.csv') s JOIN p ON p.level = s."year"::VARCHAR
WHERE p.rk <= 2 AND s."department" IS NOT NULL AND s."engagement" 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 dumbbell-demo.csv