svgbrushableparallel-coords
Parallel coordinates
How do rows compare across many numeric variables at once?
How to read it
- Each line is one row, crossing every axis at its value.
- Lines running parallel between two axes: those variables move together; lines crossing in an X: they move oppositely.
- Drag on an axis to select a range and see those rows light up.
- Callout 1: Each axis is scaled to its own minimum and maximum.
- Callout 2: Lines crossing in an X: the two variables move oppositely.
- Callout 3: Colour marks the group.
Watch out
- Axis order changes which patterns you can see, and many rows turn into a solid mass.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Each axis is min–max scaled to its own observed range (labels show min and max); a missing value breaks that row's line.
- Line opacity ≈ 6/√n (clamped to [0.08, 0.5]) so dense regions read as density.
- Brushing an axis selects rows whose value lies in the brushed range; brushes on several axes combine with AND.
# Parallel coordinates — Codesplash Chart Lab (recipe "parallel-coords")
# controls: defaults
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("parallel-coords-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["origin"] = pd.Categorical(df["origin"].astype("string"), categories=["USA", "Europe", "Japan"])
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def stride(frame, k):
if len(frame) <= k:
return frame
return frame.iloc[np.floor(np.arange(k) * len(frame) / k).astype(int)]
VARS = ["mpg", "cylinders", "displacement", "horsepower", "weight", "acceleration"]
d = stride(df, 1500) # at most 1,500 lines (deterministic stride)
lo, hi = df[VARS].min(), df[VARS].max()
scaled = (d[VARS] - lo) / (hi - lo).replace(0, 1) # each axis min–max scaled to its own range
alpha = float(np.clip(6 / np.sqrt(len(d)), 0.08, 0.5))
fig, ax = plt.subplots(figsize=(8, 4.5))
xs = np.arange(len(VARS))
colours = {lv: PALETTE[i % len(PALETTE)] for i, lv in enumerate(freq_levels(df["origin"]))}
for row, g in zip(scaled.to_numpy(), d["origin"].astype(str)):
ax.plot(xs, row, color=colours.get(g, PALETTE[7]), alpha=alpha, linewidth=0.8) # a missing value breaks the line
for lv, col in colours.items():
ax.plot([], [], color=col, label=lv)
ax.legend(title="origin", fontsize=8, loc="upper right")
for i, v in enumerate(VARS):
ax.axvline(i, color="#6c727b", linewidth=0.8)
ax.text(i, -0.04, f"{lo[v]:.4g}", ha="center", va="top", fontsize=7)
ax.text(i, 1.04, f"{hi[v]:.4g}", ha="center", va="bottom", fontsize=7)
ax.set_xticks(xs, VARS)
ax.set_yticks([])
ax.set_ylim(-0.12, 1.12)
ax.grid(False)
plt.show()Needs pandas, numpy, matplotlib · reads parallel-coords-demo.csv · app theme from the optional codesplash helper
# Parallel coordinates — Codesplash Chart Lab (recipe "parallel-coords")
# controls: defaults
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("parallel-coords-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["origin"] = pd.Categorical(df["origin"].astype("string"), categories=["USA", "Europe", "Japan"])
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def stride(frame, k):
if len(frame) <= k:
return frame
return frame.iloc[np.floor(np.arange(k) * len(frame) / k).astype(int)]
VARS = ["mpg", "cylinders", "displacement", "horsepower", "weight", "acceleration"]
d = stride(df, 1500)
levels = freq_levels(df["origin"])
code = d["origin"].astype(str).map({lv: i for i, lv in enumerate(levels)}).fillna(len(levels))
fig = go.Figure(go.Parcoords(
dimensions=[dict(label=v, values=d[v], range=[df[v].min(), df[v].max()]) for v in VARS],
line=dict(color=code, colorscale=[[i / max(1, len(levels)), PALETTE[i % 8]] for i in range(len(levels) + 1)], cmin=0, cmax=max(1, len(levels))),
))
# plotly's Parcoords leaves rows with a missing value out (the app breaks the line instead)
fig.show()Needs pandas, numpy, plotly · reads parallel-coords-demo.csv · app theme from the optional codesplash helper
# Parallel coordinates — Codesplash Chart Lab (recipe "parallel-coords")
# controls: defaults
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("parallel-coords-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["origin"]] <- factor(df[["origin"]], levels = c("USA", "Europe", "Japan"))
stride <- function(frame, k) {
if (nrow(frame) <= k) return(frame)
frame[floor((seq_len(k) - 1) * nrow(frame) / k) + 1, , drop = FALSE]
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["origin"]], "cs_declared") <- TRUE # stored level order
vars <- c("mpg", "cylinders", "displacement", "horsepower", "weight", "acceleration")
d <- stride(df, 1500) # at most 1,500 lines (deterministic stride)
d$row <- seq_len(nrow(d))
rng <- lapply(df[vars], range, na.rm = TRUE)
long <- do.call(rbind, lapply(vars, function(v) {
r <- rng[[v]]
data.frame(row = d$row, axis = v, value = (d[[v]] - r[1]) / ifelse(diff(r) == 0, 1, diff(r)), g = d[["origin"]])
}))
long$axis <- factor(long$axis, levels = vars)
alpha <- min(0.5, max(0.08, 6 / sqrt(nrow(d))))
labs_df <- data.frame(axis = factor(vars, levels = vars), lo = sapply(rng, `[`, 1), hi = sapply(rng, `[`, 2))
p <- ggplot(long, aes(axis, value, group = row, colour = g)) +
geom_vline(xintercept = seq_along(vars), colour = "#6c727b", linewidth = 0.3) +
geom_path(alpha = alpha, linewidth = 0.4, na.rm = TRUE) + # a missing value breaks the line
scale_colour_manual(values = cs_cat, name = "origin") +
geom_text(data = labs_df, aes(axis, -0.05, label = signif(lo, 4)), inherit.aes = FALSE, size = 2.5, vjust = 1) +
geom_text(data = labs_df, aes(axis, 1.05, label = signif(hi, 4)), inherit.aes = FALSE, size = 2.5, vjust = 0) +
labs(x = NULL, y = NULL) +
theme_cs + theme(axis.text.y = element_blank(), panel.grid = element_blank())
print(p)Needs ggplot2 · reads parallel-coords-demo.csv · app theme from the optional codesplashr helper
-- Parallel coordinates — Codesplash Chart Lab (recipe "parallel-coords")
-- controls: defaults
-- every variable min–max scaled to [0, 1] on its own range (one polyline per row)
SELECT row_number() OVER () AS row, "origin",
("mpg" - min("mpg") OVER ()) / NULLIF(max("mpg") OVER () - min("mpg") OVER (), 0) AS "mpg",
("cylinders" - min("cylinders") OVER ()) / NULLIF(max("cylinders") OVER () - min("cylinders") OVER (), 0) AS "cylinders",
("displacement" - min("displacement") OVER ()) / NULLIF(max("displacement") OVER () - min("displacement") OVER (), 0) AS "displacement",
("horsepower" - min("horsepower") OVER ()) / NULLIF(max("horsepower") OVER () - min("horsepower") OVER (), 0) AS "horsepower",
("weight" - min("weight") OVER ()) / NULLIF(max("weight") OVER () - min("weight") OVER (), 0) AS "weight",
("acceleration" - min("acceleration") OVER ()) / NULLIF(max("acceleration") OVER () - min("acceleration") OVER (), 0) AS "acceleration"
FROM read_csv('parallel-coords-demo.csv');Needs duckdb · reads parallel-coords-demo.csv