svgpaired-lines
Paired lines (spaghetti plot)
How did each subject change across conditions or time points?
How to read it
- Follow one thin line: that subject's change across conditions.
- Read the bold line as the mean.
- Compare: do most subjects move in the mean's direction?
- Callout 1: The bold line: the mean at each condition.
- Callout 2: A thin line: one subject.
- 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
# Paired lines (spaghetti plot) — Codesplash Chart Lab (recipe "paired-lines")
# controls: means=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("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 = go.Figure()
for name, s in d.groupby(SUBJ, observed=True):
fig.add_scatter(x=s[COND].astype(str), y=s[V], mode="lines+markers", name=str(name), line=dict(color=GREY, width=1), marker=dict(size=4), showlegend=False)
if MEANS:
mu = d.groupby("_x")[V].mean()
fig.add_scatter(x=[conds[i] for i in mu.index], y=mu.values, mode="lines+markers", name="mean", line=dict(color=PALETTE[0], width=3), marker=dict(size=9))
fig.update_xaxes(categoryorder="array", categoryarray=conds, title=COND)
fig.update_yaxes(title=V)
fig.show()Needs pandas, numpy, plotly · reads paired-lines-demo.csv · app theme from the optional codesplash helper
# Paired lines (spaghetti plot) — Codesplash Chart Lab (recipe "paired-lines")
# controls: means=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("paired-lines-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["patient"]] <- factor(df[["patient"]])
df[["visit"]] <- factor(df[["visit"]], levels = c("baseline", "week 4", "week 12"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
subj_col <- "patient"
cond_col <- "visit"
v_col <- "score"
show_means <- TRUE
d <- df[!is.na(df[[subj_col]]) & !is.na(df[[cond_col]]) & !is.na(df[[v_col]]), ]
d <- data.frame(s = as.character(d[[subj_col]]), x = factor(as.character(d[[cond_col]]), levels = levels_of(d[[cond_col]])), v = d[[v_col]])
mu <- aggregate(v ~ x, data = d, FUN = mean)
p <- ggplot(d, aes(x, v, group = s)) + geom_line(colour = grey_col, linewidth = 0.4) + geom_point(colour = grey_col, size = 0.9) +
{ if (show_means) list(geom_line(data = mu, aes(group = 1), colour = cs_cat[1], linewidth = 1.3), geom_point(data = mu, aes(group = 1), colour = cs_cat[1], size = 3)) } +
labs(x = cond_col, y = v_col) + theme_cs
print(p)Needs ggplot2 · reads paired-lines-demo.csv · app theme from the optional codesplashr helper