svgcolumn-sparkline
Column sparklines
What does each column look like at a glance?
How to read it
- Scan the tiles for a first look at each column: kind, missing share and distinct count.
- Read the mini chart for shape: a histogram for numbers, top values for categories.
- Look for surprises: a spike, a red missing bar, one value dominating.
- Callout 1: Column name and its inferred kind.
- Callout 2: A mini histogram: spikes and long tails stand out.
- Callout 3: A red bar: a large missing share.
Watch out
- An inferred kind is a guess. An id stored as a number still gets a histogram.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Numeric and temporal columns: 18 equal-width [a, b) bins over [min, max] (fewer when there are fewer distinct values).
- Categorical and boolean columns: the 4 most frequent levels (ties alphabetical) plus “Other”.
- Kinds: id-like = every non-missing value distinct (n ≥ 20, integers or short strings); text = strings averaging > 30 characters or > 3 words with > 50 % distinct.
- Missing bar: grey below 5 %, amber 5–40 %, red above 40 %.
# Column sparklines — Codesplash Chart Lab (recipe "column-sparkline")
# 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("column-sparkline-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["signup_date"] = pd.to_datetime(df["signup_date"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])
KIND_ORDER = ["numeric", "temporal", "categorical", "boolean", "text", "id-like"]
KIND_COLOUR = {"numeric": 0, "temporal": 2, "categorical": 1, "boolean": 4, "text": 5, "id-like": 7}
def infer_kind(s, kind):
"""id-like = every non-missing value distinct (n ≥ 20; integers or short strings);
text = strings averaging > 30 characters, or > 3 words with > 50 % distinct."""
if kind in ("boolean", "temporal"):
return kind
present = s.dropna()
distinct = present.astype(str).nunique()
unique = len(present) >= 20 and distinct == len(present)
if kind == "numeric":
ints = bool(np.all(np.mod(present.to_numpy(dtype=float), 1) == 0))
return "id-like" if unique and ints else "numeric"
strs = present.astype(str)
avg_len = strs.str.len().mean() if len(strs) else 0
avg_words = strs.str.strip().str.split().str.len().mean() if len(strs) else 0
if avg_len > 30 or (avg_words > 3 and distinct > 0.5 * len(strs)):
return "text"
return "id-like" if unique else "categorical"
def tile(s, kind, bins=18, top_k=4):
"""Numeric/temporal: equal-width [a, b) bins over [min, max] (fewer when fewer distinct values);
categorical/boolean: the top 4 levels (ties A→Z) plus Other."""
present = s.dropna()
if kind in ("numeric", "temporal") and len(present):
v = present.astype("int64").to_numpy() if kind == "temporal" else present.to_numpy(dtype=float)
k = max(1, min(bins, present.nunique()))
counts, edges = np.histogram(v, bins=k, range=(v.min(), v.max() if v.max() > v.min() else v.min() + 1))
return "bins", counts, edges
if kind in ("categorical", "boolean"):
vc = present.astype(str).value_counts()
levels = sorted(vc.index, key=lambda l: (-vc[l], l))
top = [(l, int(vc[l])) for l in levels[:top_k]]
other = int(len(present) - sum(n for _, n in top))
return "levels", top + ([("Other", other)] if other else []), None
return "none", None, None
KINDS = {"signup_date": "temporal", "age": "numeric", "income": "numeric", "region": "categorical", "plan": "categorical", "churned": "boolean", "satisfaction": "numeric", "comments": "categorical"} # physical kinds from the app
COLS = list(KINDS)
cols = 4
rows = int(np.ceil(len(COLS) / cols))
fig, axes = plt.subplots(rows, cols, figsize=(3 * cols, 1.9 * rows), squeeze=False)
for ax, name in zip(axes.flat, COLS):
s = df[name]
kind = infer_kind(s, KINDS[name])
share = s.isna().mean()
miss_colour = "#6e7278" if share < 0.05 else PALETTE[1] if share <= 0.4 else PALETTE[3] # grey < 5 %, amber ≤ 40 %, red above
what, a, b = tile(s, kind)
colour = PALETTE[KIND_COLOUR[kind]]
if what == "bins":
ax.bar(b[:-1], a, width=np.diff(b), align="edge", color=colour, edgecolor="white", linewidth=0.4)
elif what == "levels":
labels = [l for l, _ in a][::-1]
ax.barh(labels, [n for _, n in a][::-1], color=[colour if l != "Other" else "#9aa0a6" for l in labels])
ax.tick_params(axis="y", labelsize=7)
else:
ax.text(0.5, 0.5, f"{s.dropna().astype(str).nunique():,} distinct", ha="center", va="center", transform=ax.transAxes, fontsize=9)
ax.set_title(f"{name} · {kind}", fontsize=9, loc="left")
ax.text(1, 1.02, f"{share:.0%} missing", transform=ax.transAxes, ha="right", va="bottom", fontsize=8, color=miss_colour)
ax.set_xticks([])
if what != "levels":
ax.set_yticks([])
ax.grid(False)
for ax in list(axes.flat)[len(COLS):]:
ax.set_visible(False)
fig.tight_layout()
plt.show()Needs pandas, numpy, matplotlib · reads column-sparkline-demo.csv · app theme from the optional codesplash helper
# Column sparklines — Codesplash Chart Lab (recipe "column-sparkline")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
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("column-sparkline-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["signup_date"] = pd.to_datetime(df["signup_date"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])
KIND_ORDER = ["numeric", "temporal", "categorical", "boolean", "text", "id-like"]
KIND_COLOUR = {"numeric": 0, "temporal": 2, "categorical": 1, "boolean": 4, "text": 5, "id-like": 7}
def infer_kind(s, kind):
"""id-like = every non-missing value distinct (n ≥ 20; integers or short strings);
text = strings averaging > 30 characters, or > 3 words with > 50 % distinct."""
if kind in ("boolean", "temporal"):
return kind
present = s.dropna()
distinct = present.astype(str).nunique()
unique = len(present) >= 20 and distinct == len(present)
if kind == "numeric":
ints = bool(np.all(np.mod(present.to_numpy(dtype=float), 1) == 0))
return "id-like" if unique and ints else "numeric"
strs = present.astype(str)
avg_len = strs.str.len().mean() if len(strs) else 0
avg_words = strs.str.strip().str.split().str.len().mean() if len(strs) else 0
if avg_len > 30 or (avg_words > 3 and distinct > 0.5 * len(strs)):
return "text"
return "id-like" if unique else "categorical"
def tile(s, kind, bins=18, top_k=4):
"""Numeric/temporal: equal-width [a, b) bins over [min, max] (fewer when fewer distinct values);
categorical/boolean: the top 4 levels (ties A→Z) plus Other."""
present = s.dropna()
if kind in ("numeric", "temporal") and len(present):
v = present.astype("int64").to_numpy() if kind == "temporal" else present.to_numpy(dtype=float)
k = max(1, min(bins, present.nunique()))
counts, edges = np.histogram(v, bins=k, range=(v.min(), v.max() if v.max() > v.min() else v.min() + 1))
return "bins", counts, edges
if kind in ("categorical", "boolean"):
vc = present.astype(str).value_counts()
levels = sorted(vc.index, key=lambda l: (-vc[l], l))
top = [(l, int(vc[l])) for l in levels[:top_k]]
other = int(len(present) - sum(n for _, n in top))
return "levels", top + ([("Other", other)] if other else []), None
return "none", None, None
KINDS = {"signup_date": "temporal", "age": "numeric", "income": "numeric", "region": "categorical", "plan": "categorical", "churned": "boolean", "satisfaction": "numeric", "comments": "categorical"} # physical kinds from the app
COLS = list(KINDS)
cols = 4
rows = int(np.ceil(len(COLS) / cols))
kinds = {n: infer_kind(df[n], KINDS[n]) for n in COLS}
titles = [f"{n} · {kinds[n]} · {df[n].isna().mean():.0%} missing" for n in COLS]
fig = make_subplots(rows=rows, cols=cols, subplot_titles=titles, vertical_spacing=0.12)
for i, name in enumerate(COLS):
what, a, b = tile(df[name], kinds[name])
r, cc = i // cols + 1, i % cols + 1
colour = PALETTE[KIND_COLOUR[kinds[name]]]
if what == "bins":
fig.add_bar(x=(b[:-1] + b[1:]) / 2, y=a, width=np.diff(b), marker_color=colour, showlegend=False, row=r, col=cc)
elif what == "levels":
fig.add_bar(y=[l for l, _ in a][::-1], x=[n for _, n in a][::-1], orientation="h", marker_color=colour, showlegend=False, row=r, col=cc)
fig.update_xaxes(showticklabels=False)
fig.update_annotations(font_size=10)
fig.update_layout(height=200 * rows, bargap=0.05)
fig.show()Needs pandas, numpy, plotly · reads column-sparkline-demo.csv · app theme from the optional codesplash helper
# Column sparklines — Codesplash Chart Lab (recipe "column-sparkline")
# 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("column-sparkline-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["signup_date"]] <- as.POSIXct(df[["signup_date"]], tz = "UTC")
df[["churned"]] <- as.logical(df[["churned"]])
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
df[["plan"]] <- factor(df[["plan"]], levels = c("Basic", "Plus", "Pro"))
df[["comments"]] <- factor(df[["comments"]])
kind_order <- c("numeric", "temporal", "categorical", "boolean", "text", "id-like")
kind_colour <- c(numeric = 1, temporal = 3, categorical = 2, boolean = 5, text = 6, "id-like" = 8)
infer_kind <- function(v, kind) {
# id-like = every non-missing value distinct (n >= 20); text = long or multi-word strings, > 50 % distinct
if (kind %in% c("boolean", "temporal")) return(kind)
present <- v[!is.na(v)]
distinct <- length(unique(as.character(present)))
unique_all <- length(present) >= 20 && distinct == length(present)
if (kind == "numeric") return(if (unique_all && all(present %% 1 == 0)) "id-like" else "numeric")
s <- as.character(present)
avg_len <- if (length(s)) mean(nchar(s)) else 0
avg_words <- if (length(s)) mean(lengths(strsplit(trimws(s), "\\s+"))) else 0
if (avg_len > 30 || (avg_words > 3 && distinct > 0.5 * length(s))) return("text")
if (unique_all) "id-like" else "categorical"
}
kinds <- c("signup_date" = "temporal", "age" = "numeric", "income" = "numeric", "region" = "categorical", "plan" = "categorical", "churned" = "boolean", "satisfaction" = "numeric", "comments" = "categorical") # physical kinds from the app
cols <- names(kinds)
tiles <- do.call(rbind, lapply(cols, function(nm) {
v <- df[[nm]]; kind <- infer_kind(v, kinds[[nm]]); share <- mean(is.na(v))
label <- sprintf("%s · %s · %.0f%% missing", nm, kind, 100 * share)
present <- v[!is.na(v)]
if (kind %in% c("numeric", "temporal") && length(present)) {
x <- as.numeric(present); k <- max(1, min(18, length(unique(x))))
e <- seq(min(x), if (max(x) > min(x)) max(x) else min(x) + 1, length.out = k + 1) # equal-width [a, b), last closed
n <- as.vector(table(cut(x, e, right = FALSE, include.lowest = TRUE)))
return(data.frame(panel = label, kind = kind, pos = seq_len(k), n = n, level = ""))
}
if (kind %in% c("categorical", "boolean")) {
tab <- table(as.character(present)); lv <- names(tab)[order(-as.vector(tab), names(tab))]
top <- utils::head(lv, 4); other <- length(present) - sum(tab[top])
lv <- c(top, if (other > 0) "Other"); n <- c(as.vector(tab[top]), if (other > 0) other)
return(data.frame(panel = label, kind = kind, pos = seq_along(lv), n = n, level = lv))
}
data.frame(panel = label, kind = kind, pos = 1, n = 0, level = sprintf("%d distinct", length(unique(present))))
}))
tiles$panel <- factor(tiles$panel, levels = unique(tiles$panel))
tiles$fill <- ifelse(tiles$level == "Other", "#9aa0a6", cs_cat[kind_colour[tiles$kind]])
p <- ggplot(tiles, aes(pos, n)) +
geom_col(aes(fill = fill), width = 0.95) + scale_fill_identity() +
geom_text(aes(y = 0, label = level), angle = 90, hjust = -0.1, size = 2.3) +
facet_wrap(~panel, scales = "free", ncol = 4) +
labs(x = NULL, y = NULL) +
theme_cs + theme(axis.text = element_blank(), panel.grid = element_blank(), strip.text = element_text(size = 7, hjust = 0))
print(p)Needs ggplot2 · reads column-sparkline-demo.csv · app theme from the optional codesplashr helper
-- Column sparklines — Codesplash Chart Lab (recipe "column-sparkline")
-- controls: defaults
-- one summary row per column: missing share, distinct values and range
SELECT 'signup_date' AS "column", 'temporal' AS kind, count(*) AS n, count(*) - count("signup_date") AS missing,
(count(*) - count("signup_date")) / count(*) AS missing_share, count(DISTINCT "signup_date") AS "distinct",
min("signup_date")::VARCHAR AS min, max("signup_date")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'age' AS "column", 'numeric' AS kind, count(*) AS n, count(*) - count("age") AS missing,
(count(*) - count("age")) / count(*) AS missing_share, count(DISTINCT "age") AS "distinct",
min("age")::VARCHAR AS min, max("age")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'income' AS "column", 'numeric' AS kind, count(*) AS n, count(*) - count("income") AS missing,
(count(*) - count("income")) / count(*) AS missing_share, count(DISTINCT "income") AS "distinct",
min("income")::VARCHAR AS min, max("income")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'region' AS "column", 'categorical' AS kind, count(*) AS n, count(*) - count("region") AS missing,
(count(*) - count("region")) / count(*) AS missing_share, count(DISTINCT "region") AS "distinct",
min("region")::VARCHAR AS min, max("region")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'plan' AS "column", 'categorical' AS kind, count(*) AS n, count(*) - count("plan") AS missing,
(count(*) - count("plan")) / count(*) AS missing_share, count(DISTINCT "plan") AS "distinct",
min("plan")::VARCHAR AS min, max("plan")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'churned' AS "column", 'boolean' AS kind, count(*) AS n, count(*) - count("churned") AS missing,
(count(*) - count("churned")) / count(*) AS missing_share, count(DISTINCT "churned") AS "distinct",
min("churned")::VARCHAR AS min, max("churned")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'satisfaction' AS "column", 'numeric' AS kind, count(*) AS n, count(*) - count("satisfaction") AS missing,
(count(*) - count("satisfaction")) / count(*) AS missing_share, count(DISTINCT "satisfaction") AS "distinct",
min("satisfaction")::VARCHAR AS min, max("satisfaction")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'comments' AS "column", 'categorical' AS kind, count(*) AS n, count(*) - count("comments") AS missing,
(count(*) - count("comments")) / count(*) AS missing_share, count(DISTINCT "comments") AS "distinct",
min("comments")::VARCHAR AS min, max("comments")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv');Needs duckdb · reads column-sparkline-demo.csv