svgwaffle
Waffle chart
What share of the whole does each category hold — in countable units?
How to read it
- Count squares: each one is 1% of the rows.
- Compare blocks of colour.
- Read the legend for exact percentages.
- Callout 1: Each square: 1% of rows.
- Callout 2: The legend gives each share.
Watch out
- It rounds to whole percents, so very small categories may lose or gain a square.
Defaults
- Categories
- 6
- How many categories to show; the rest are grouped.
- Range 2 to 8, step 1
- Percent in legend
- On
- Print each category's share in the legend.
Pinned in the code
- Each of the 100 squares is 1 % of non-missing rows; squares are allocated by the largest-remainder (Hamilton) method so they always total 100.
- Levels sorted by frequency; beyond the top k they pool into “Other” (neutral grey). Squares fill row by row from the top left.
- Shares under 0.5 % may get no square — the legend percentages are exact.
# Waffle chart — Codesplash Chart Lab (recipe "waffle")
# controls: top=6, percents=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5) # stripes let the chart surface show through
df = pd.read_csv("waffle-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def levels(s):
"""Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(c) for c in s.cat.categories]
counts = s.dropna().astype(str).value_counts()
return sorted(counts.index, key=lambda k: (-counts[k], k))
def hamilton(values, cells=100):
"""Largest-remainder (Hamilton) allocation: cells always total `cells`; ties go to the earlier level."""
exact = np.asarray(values, dtype=float) / np.sum(values) * cells
out = np.floor(exact).astype(int)
rest = sorted(range(len(exact)), key=lambda i: (-(exact[i] - np.floor(exact[i])), i))
for i in rest[: cells - out.sum()]:
out[i] += 1
return out
keep = levels(df["heating"])[:6]
s = df["heating"].dropna().astype(str)
counts = s.where(s.isin(keep), "Other").value_counts().reindex(keep + (["Other"] if (~s.isin(keep)).any() else []), fill_value=0)
cells = hamilton(counts.to_numpy()) # each of the 100 squares is 1 % of non-missing rows
colors = ["#9aa0a6" if l == "Other" else PALETTE[i % len(PALETTE)] for i, l in enumerate(counts.index)]
owner = np.repeat(np.arange(len(cells)), cells) # squares fill row by row from the top left
hatches = [SERIES_HATCHES[7 if l == "Other" else i % 8] for i, l in enumerate(counts.index)] # texture per level, as in the app
labels = [f"{l} {v / counts.sum():.1%}" for l, v in counts.items()]
from matplotlib.patches import Patch, Rectangle
fig, ax = plt.subplots(figsize=(7, 4.5))
for k, who in enumerate(owner):
row, col = divmod(k, 10)
ax.add_patch(Rectangle((col, 9 - row), 0.9, 0.9, facecolor=colors[who], hatch=hatches[who], hatchcolor=HATCH_INK, linewidth=0))
ax.set_xlim(-0.1, 10)
ax.set_ylim(-0.1, 10)
ax.set_aspect("equal")
ax.axis("off")
ax.legend(handles=[Patch(facecolor=col, hatch=h, hatchcolor=HATCH_INK, linewidth=0, label=lab) for col, h, lab in zip(colors, hatches, labels)], loc="center left", bbox_to_anchor=(1.02, 0.5))
plt.show()Needs pandas, numpy, matplotlib · reads waffle-demo.csv · app theme from the optional codesplash helper
# Waffle chart — Codesplash Chart Lab (recipe "waffle")
# controls: top=6, percents=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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,0.5)" # stripes let the chart surface show through
df = pd.read_csv("waffle-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def levels(s):
"""Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(c) for c in s.cat.categories]
counts = s.dropna().astype(str).value_counts()
return sorted(counts.index, key=lambda k: (-counts[k], k))
def hamilton(values, cells=100):
"""Largest-remainder (Hamilton) allocation: cells always total `cells`; ties go to the earlier level."""
exact = np.asarray(values, dtype=float) / np.sum(values) * cells
out = np.floor(exact).astype(int)
rest = sorted(range(len(exact)), key=lambda i: (-(exact[i] - np.floor(exact[i])), i))
for i in rest[: cells - out.sum()]:
out[i] += 1
return out
keep = levels(df["heating"])[:6]
s = df["heating"].dropna().astype(str)
counts = s.where(s.isin(keep), "Other").value_counts().reindex(keep + (["Other"] if (~s.isin(keep)).any() else []), fill_value=0)
cells = hamilton(counts.to_numpy()) # each of the 100 squares is 1 % of non-missing rows
colors = ["#9aa0a6" if l == "Other" else PALETTE[i % len(PALETTE)] for i, l in enumerate(counts.index)]
owner = np.repeat(np.arange(len(cells)), cells) # squares fill row by row from the top left
hatches = [SERIES_HATCHES[7 if l == "Other" else i % 8] for i, l in enumerate(counts.index)] # texture per level, as in the app
labels = [f"{l} {v / counts.sum():.1%}" for l, v in counts.items()]
fig = go.Figure()
for i, lab in enumerate(labels):
ks = np.flatnonzero(owner == i)
# one 0.9 × 0.9 bar per square, so the squares can carry the level's texture (as in the app)
fig.add_bar(x=ks % 10, y=np.full(ks.size, 0.9), base=9 - ks // 10 - 0.45, width=0.9, name=lab,
marker=dict(color=colors[i], line_width=0, pattern=dict(shape=hatches[i], fgcolor=HATCH_INK, fillmode="overlay")))
fig.update_layout(barmode="overlay", xaxis=dict(visible=False, range=[-0.6, 9.6]), yaxis=dict(visible=False, range=[-0.6, 9.6], scaleanchor="x"))
fig.show()Needs pandas, numpy, plotly · reads waffle-demo.csv · app theme from the optional codesplash helper
# Waffle chart — Codesplash Chart Lab (recipe "waffle")
# controls: top=6, percents=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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("waffle-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["heating"]] <- factor(df[["heating"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
freq_levels <- function(v) {
# the app's order when the data dictionary declares none: by descending frequency, ties alphabetical
t <- table(as.character(v[!is.na(v)]))
names(t)[order(-as.numeric(t), names(t))]
}
hamilton <- function(values, cells = 100) {
# largest-remainder (Hamilton) allocation: cells always total `cells`; ties go to the earlier level
exact <- values / sum(values) * cells
out <- floor(exact)
rest <- order(-(exact - floor(exact)), seq_along(exact))
add <- head(rest, cells - sum(out))
out[add] <- out[add] + 1
out
}
keep <- head(freq_levels(df[["heating"]]), 6)
v <- as.character(df[["heating"]])
v <- v[!is.na(v)]
v <- ifelse(v %in% keep, v, "Other")
lv <- c(keep, if (any(v == "Other")) "Other")
counts <- as.numeric(table(factor(v, levels = lv)))
cells <- hamilton(counts) # each of the 100 squares is 1 % of non-missing rows
labels <- sprintf("%s %.1f%%", lv, 100 * counts / sum(counts))
grid <- data.frame(k = 0:99, who = factor(rep(labels, cells), levels = labels))
grid$row <- grid$k %/% 10 # squares fill row by row from the top left
grid$col <- grid$k %% 10
fill <- setNames(rep(cs_cat, length.out = length(lv)), labels)
fill[lv == "Other"] <- "#9aa0a6"
fill <- setNames(cs_textures(unname(fill), idx = ifelse(lv == "Other", 8, seq_along(lv))), labels) # texture per level, as in the app
p <- ggplot(grid, aes(col, row, fill = who)) +
geom_tile(width = 0.9, height = 0.9) +
scale_y_reverse() +
scale_fill_manual(values = fill, name = NULL) +
coord_equal() +
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)Needs ggplot2 · reads waffle-demo.csv · app theme from the optional codesplashr helper
-- Waffle chart — Codesplash Chart Lab (recipe "waffle")
-- controls: top=6, percents=true
-- per-level counts (top 6 + 'Other') and their 100 waffle squares by the largest-remainder method
WITH
lv AS (
SELECT "heating"::VARCHAR AS level, row_number() OVER (ORDER BY count(*) DESC, "heating"::VARCHAR) AS rk
FROM read_csv('waffle-demo.csv') WHERE "heating" IS NOT NULL GROUP BY 1
),
counts AS (
SELECT CASE WHEN lv.rk <= 6 THEN lv.level ELSE 'Other' END AS level, count(*) AS n, min(lv.rk) AS rk
FROM read_csv('waffle-demo.csv') s JOIN lv ON lv.level = s."heating"::VARCHAR
GROUP BY 1
),
exact AS (SELECT *, n * 100.0 / sum(n) OVER () AS exact FROM counts),
alloc AS (
SELECT *, floor(exact)::INTEGER AS base,
row_number() OVER (ORDER BY exact - floor(exact) DESC, rk) AS rem_rank,
100 - sum(floor(exact)::INTEGER) OVER () AS leftover
FROM exact
)
SELECT level, n, n / sum(n) OVER () AS share,
base + CASE WHEN rem_rank <= leftover THEN 1 ELSE 0 END AS squares
FROM alloc
ORDER BY rk;Needs duckdb · reads waffle-demo.csv