Skip to content
svgwaffle

Waffle chart

What share of the whole does each category hold — in countable units?

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

How to read it

  1. Count squares: each one is 1% of the rows.
  2. Compare blocks of colour.
  3. Read the legend for exact percentages.
  1. Callout 1: Each square: 1% of rows.
  2. 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