svgbrushableconnected-scatter
Connected scatter
How did two variables move together over time?
How to read it
- Start at the labelled first point and follow the path through time.
- Use the arrows and the colour ramp for direction.
- Read a loop as a cycle; a long straight run as a sustained move.
- Callout 1: The start of the path.
- Callout 2: A sharp excursion: find the dates.
- Callout 3: Labelled points anchor the timeline.
Watch out
- Time isn't an axis here. Readers can misjudge direction unless arrows or labels are on.
Defaults
- Colour by time
- On
- Fade the path from early to late so you can follow its direction.
- Direction arrows
- On
- Add arrows along the path.
- Label every k points
- 5
- Label every k-th point along the path.
- Range 0 to 20, step 1
Pinned in the code
- Rows are sorted by the order variable (ties keep row order); rows missing x, y or order are dropped.
- Segments are coloured along a sequential ramp from the first to the last point; arrows sit at segment midpoints.
- Labels are placed on the outside of the bend (away from the neighbouring points).
# Connected scatter — Codesplash Chart Lab (recipe "connected-scatter")
# controls: gradient=true, arrows=true, labelEvery=5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import LinearSegmentedColormap
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("connected-scatter-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
d = df.dropna(subset=["unemployment_pct", "inflation_pct", "year"]).sort_values("year", kind="stable") # ties keep row order
xv, yv = d["unemployment_pct"].to_numpy(dtype=float), d["inflation_pct"].to_numpy(dtype=float)
ramp = LinearSegmentedColormap.from_list("time", [SEQ[0], SEQ[-1]])
t = np.linspace(0.3, 1, len(d) - 1) # early → late (skip the palest end of the ramp)
fig, ax = plt.subplots(figsize=(7, 4.5))
segments = np.stack([np.c_[xv[:-1], yv[:-1]], np.c_[xv[1:], yv[1:]]], axis=1)
ax.add_collection(LineCollection(segments, colors=ramp(t), linewidths=2))
ax.scatter(xv, yv, s=18, color=ramp(np.linspace(0.3, 1, len(d))), zorder=3)
for (x0, y0), (x1, y1) in zip(segments[:, 0], segments[:, 1]): # arrows at segment midpoints
mx, my = (x0 + x1) / 2, (y0 + y1) / 2
ax.annotate("", xy=(mx + (x1 - x0) * 0.01, my + (y1 - y0) * 0.01), xytext=(mx, my), arrowprops=dict(arrowstyle="-|>", color=REF, lw=1))
labels = d["year"].astype(str).to_numpy()
keep = set([0, len(d) - 1] + (list(range(0, len(d), 5)) if 5 > 0 else []))
for i in sorted(keep):
ax.annotate(labels[i], (xv[i], yv[i]), textcoords="offset points", xytext=(4, 4), fontsize=8)
ax.autoscale()
ax.set_xlabel("unemployment_pct")
ax.set_ylabel("inflation_pct")
plt.show()Needs pandas, numpy, matplotlib · reads connected-scatter-demo.csv · app theme from the optional codesplash helper
# Connected scatter — Codesplash Chart Lab (recipe "connected-scatter")
# controls: gradient=true, arrows=true, labelEvery=5
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("connected-scatter-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
d = df.dropna(subset=["unemployment_pct", "inflation_pct", "year"]).sort_values("year", kind="stable")
xv, yv = d["unemployment_pct"].to_numpy(dtype=float), d["inflation_pct"].to_numpy(dtype=float)
labels = d["year"].astype(str).to_numpy()
show = [i == 0 or i == len(d) - 1 or (5 > 0 and i % 5 == 0) for i in range(len(d))]
fig = go.Figure(go.Scatter(
x=xv, y=yv, mode="lines+markers+text", text=[l if s else "" for l, s in zip(labels, show)], textposition="top right",
line=dict(color=REF, width=1.5), marker=dict(color=np.arange(len(d)), colorscale=[[0, SEQ[0]], [1, SEQ[-1]]], cmin=-0.4 * len(d), size=8),
name="year",
))
for i in range(len(d) - 1): # arrows at segment midpoints
mx, my = (xv[i] + xv[i + 1]) / 2, (yv[i] + yv[i + 1]) / 2
fig.add_annotation(x=mx, y=my, ax=xv[i], ay=yv[i], xref="x", yref="y", axref="x", ayref="y", showarrow=True, arrowhead=2, arrowcolor=REF, text="")
fig.update_layout(xaxis_title="unemployment_pct", yaxis_title="inflation_pct")
fig.show()Needs pandas, numpy, plotly · reads connected-scatter-demo.csv · app theme from the optional codesplash helper
# Connected scatter — Codesplash Chart Lab (recipe "connected-scatter")
# controls: gradient=true, arrows=true, labelEvery=5
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("connected-scatter-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
d <- df[stats::complete.cases(df[c("unemployment_pct", "inflation_pct", "year")]), , drop = FALSE]
d <- d[order(d[["year"]]), , drop = FALSE] # order() is stable: ties keep row order
d$step <- seq_len(nrow(d))
seg <- data.frame(x = utils::head(d[["unemployment_pct"]], -1), y = utils::head(d[["inflation_pct"]], -1),
xend = d[["unemployment_pct"]][-1], yend = d[["inflation_pct"]][-1], step = utils::head(d$step, -1))
seg$mx <- (seg$x + seg$xend) / 2; seg$my <- (seg$y + seg$yend) / 2
lab <- d[d$step %in% unique(c(1, nrow(d), if (5 > 0) seq(1, nrow(d), by = 5))), , drop = FALSE]
p <- ggplot() +
geom_segment(data = seg, aes(x, y, xend = xend, yend = yend, colour = step), linewidth = 0.9) +
geom_segment(data = seg, aes(x, y, xend = mx, yend = my), colour = ref_col, linewidth = 0.4, arrow = grid::arrow(length = grid::unit(2, "mm"), type = "closed")) +
geom_point(data = d, aes(.data[["unemployment_pct"]], .data[["inflation_pct"]], colour = step), size = 1.8) +
geom_text(data = lab, aes(.data[["unemployment_pct"]], .data[["inflation_pct"]], label = .data[["year"]]), hjust = -0.2, vjust = -0.4, size = 3) +
scale_colour_gradient(low = grDevices::colorRampPalette(seq_ramp)(10)[3], high = seq_ramp[2], guide = "none") +
labs(x = "unemployment_pct", y = "inflation_pct") +
theme_cs
print(p)Needs ggplot2 · reads connected-scatter-demo.csv · app theme from the optional codesplashr helper
-- Connected scatter — Codesplash Chart Lab (recipe "connected-scatter")
-- controls: gradient=true, arrows=true, labelEvery=5
-- the path in time order: each row with the next point and the segment midpoint (arrow position)
SELECT "year", "unemployment_pct", "inflation_pct",
lead("unemployment_pct") OVER w AS x_next, lead("inflation_pct") OVER w AS y_next,
("unemployment_pct" + lead("unemployment_pct") OVER w) / 2 AS arrow_x, ("inflation_pct" + lead("inflation_pct") OVER w) / 2 AS arrow_y
FROM read_csv('connected-scatter-demo.csv')
WHERE "unemployment_pct" IS NOT NULL AND "inflation_pct" IS NOT NULL AND "year" IS NOT NULL
WINDOW w AS (ORDER BY "year")
ORDER BY "year";Needs duckdb · reads connected-scatter-demo.csv