Skip to content
svgpaired-lines

Paired lines (spaghetti plot)

How did each subject change across conditions or time points?

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

How to read it

  1. Follow one thin line: that subject's change across conditions.
  2. Read the bold line as the mean.
  3. Compare: do most subjects move in the mean's direction?
  1. Callout 1: The bold line: the mean at each condition.
  2. Callout 2: A thin line: one subject.
  3. Callout 3: A subject moving against the mean.

Watch out

  • A flat mean can hide large individual changes in opposite directions.

Defaults

Condition means
On
Draw the mean at each condition over the individual lines.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Long data: one row per subject × condition; conditions keep the stored level order. A subject's missing condition breaks its line.
  • Means are of the values shown (complete or not); the test's estimates come from the engine.
# Paired lines (spaghetti plot) — Codesplash Chart Lab (recipe "paired-lines")
# controls: means=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("paired-lines-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["visit"] = pd.Categorical(df["visit"].astype("string"), categories=["baseline", "week 4", "week 12"])

_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")
def levels_of(s):
    """Declared level order (categoricals), else order of first appearance."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [v for v in s.cat.categories if (s == v).any()]
    return list(dict.fromkeys(s.dropna().astype(str)))
SUBJ = "patient"
COND = "visit"
V = "score"
MEANS = True
d = df.dropna(subset=[SUBJ, COND, V])
conds = levels_of(d[COND])
d = d.assign(_x=[conds.index(str(v)) for v in d[COND]]).sort_values("_x")
fig, ax = plt.subplots(figsize=(7, 4.5))
for _, s in d.groupby(SUBJ, observed=True):
    ax.plot(s["_x"], s[V], color=GREY, linewidth=0.9, marker="o", ms=2.5, alpha=0.9)
if MEANS:
    mu = d.groupby("_x")[V].mean()
    ax.plot(mu.index, mu.values, color=PALETTE[0], linewidth=2.6, marker="o", ms=7, label="mean")
    ax.legend(fontsize=8)
ax.set_xticks(range(len(conds)), conds)
ax.set_xlabel(COND)
ax.set_ylabel(V)
plt.show()

Needs pandas, numpy, matplotlib · reads paired-lines-demo.csv · app theme from the optional codesplash helper