Skip to content
ChartslibraryUI Get Pro

Waffle chart

A countable part-to-whole: one square is one percent.

FreeMIT · install in one command<WaffleChart />

When to use

  • A single rate ("64 in 100 accounts are active")
  • Two to four parts of a whole for general audiences

When not to use

Good practice

  • Pass total to show a single rate against the remainder.
  • Keep to four parts or fewer.

Installation

Waffle chart is free under the MIT license.

$ npx shadcn@latest add https://chartslibraryui.com/r/waffle-chart.json

Installs the chart, its dependencies and the shared core into your components folder.

Then import the theme once: import "@/components/charts/core/charts.css" Installation guide

Usage

import { WaffleChart } from "@/components/charts/waffle-chart";
import { waffleShares } from "./sample-data";

export function Example() {
  return (
    <WaffleChart
      title="Two in three accounts are active every week"
      subtitle="Accounts by activity, last 30 days"
      data={waffleShares}
      label="label"
      value="value"
      format={{ kind: "percent" }}
    />
  );
}

Data

Rows with a label key and a non-negative value key; optional total.

[{ label: "Active weekly", value: 0.64 }, ...]

Missing values are null. Invalid values make the chart say what’s wrong instead of drawing a misleading picture. How charts handle bad data

Props

Every chart also accepts the shared frame props: title, subtitle, source, height, mode, toolbar. Common API

export interface WaffleChartProps extends FrameProps {
  data: Row[];
  label: string;
  value: string;
  /** The whole. Default: the sum of values. With a larger total, the remainder is drawn as empty squares. */
  total?: number;
  format?: FormatInput;
  /** Grid size per side. Default 10 (one square = 1%). */
  grid?: number;
  /** Name for the unfilled remainder when `total` exceeds the sum. */
  remainderLabel?: string;
}

Source

Installs waffle-chart.tsx and the shared core/ (11 files).

View waffle-chart.tsx
"use client";

import { useMemo } from "react";
import { color as tokens } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatShare, formatValue, type FormatInput } from "./core/format";
import { ChartFrame, useActiveIndex, type FrameProps } from "./core/frame";

export interface WaffleChartProps extends FrameProps {
  data: Row[];
  label: string;
  value: string;
  /** The whole. Default: the sum of values. With a larger total, the remainder is drawn as empty squares. */
  total?: number;
  format?: FormatInput;
  /** Grid size per side. Default 10 (one square = 1%). */
  grid?: number;
  /** Name for the unfilled remainder when `total` exceeds the sum. */
  remainderLabel?: string;
}

/**
 * A countable part-to-whole: one square is one percent. Easier to read than a pie for a single rate ("64 in 100")
 * or two to four parts. Squares are allocated by largest remainder so they always add up to the grid.
 */
export function WaffleChart({
  data,
  label,
  value,
  total: totalProp,
  format,
  grid = 10,
  remainderLabel = "Remainder",
  height,
  ...frame
}: WaffleChartProps) {
  const cells = grid * grid;
  const { parts, issues } = useMemo(() => {
    const issues: Issue[] = [];
    if (!Array.isArray(data) || !data.length)
      return { parts: [] as { name: string; value: number; share: number; squares: number; color: string }[], issues: [{ level: "error", message: "No data to display." }] as Issue[] };
    const items: { name: string; value: number }[] = [];
    for (const row of data) {
      const r = readNum(row?.[value]);
      const name = String(row?.[label] ?? "");
      if (r.state === "invalid" || (r.value !== null && r.value < 0)) {
        issues.push({ level: "error", message: `"${name}" must be a number of zero or more.` });
      } else if (r.value === null) issues.push({ level: "warning", message: `"${name}" has no value and is left out.` });
      else items.push({ name, value: r.value });
    }
    const sum = items.reduce((a, b) => a + b.value, 0);
    const total = totalProp ?? sum;
    if (totalProp !== undefined && sum > totalProp + 1e-9)
      issues.push({ level: "error", message: `Parts add up to ${formatValue(sum, format)}, more than the total of ${formatValue(totalProp, format)}.` });
    if (total <= 0 && !issues.some((i) => i.level === "error")) issues.push({ level: "error", message: "The total is zero." });
    const withRest = [...items];
    if (total > sum) withRest.push({ name: remainderLabel, value: total - sum });
    // largest remainder allocation
    const raw = withRest.map((d) => (total ? (d.value / total) * cells : 0));
    const squares = raw.map(Math.floor);
    let left = cells - squares.reduce((a, b) => a + b, 0);
    raw
      .map((v, i) => ({ i, rem: v - Math.floor(v) }))
      .sort((a, b) => b.rem - a.rem)
      .forEach(({ i }) => {
        if (left > 0) {
          squares[i]++;
          left--;
        }
      });
    let slot = 0;
    const parts = withRest.map((d, i) => ({
      ...d,
      share: total ? d.value / total : 0,
      squares: squares[i],
      color: total > sum && i === withRest.length - 1 ? tokens.contextSoft : tokens.series(slot++),
    }));
    const tinyHidden = parts.filter((p) => p.value > 0 && p.squares === 0);
    if (tinyHidden.length)
      issues.push({ level: "note", message: `${tinyHidden.map((p) => p.name).join(", ")} round to less than one square; see the table.` });
    return { parts, issues };
  }, [data, label, value, totalProp, cells, remainderLabel, format]);

  const legend = parts.map((p) => ({ key: p.name, label: `${p.name} ${formatShare(p.share)}`, color: p.color }));
  const table = {
    columns: [
      { key: "name", label },
      { key: "value", label: value, align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
      { key: "share", label: "Share", align: "right" as const, format: (v: unknown) => formatShare(v as number, 1) },
    ],
    rows: parts.map((p) => ({ name: p.name, value: p.value, share: p.share })),
  };
  const summary = `Waffle chart, ${cells} squares. ${parts.map((p) => `${p.name}: ${formatShare(p.share)}`).join(", ")}.`;
  const h = height ?? 220;

  return (
    <ChartFrame {...frame} height={h} issues={issues} table={table} summary={summary} legend={legend}>
      {({ width }) => <WafflePlot width={width} height={h} parts={parts} grid={grid} />}
    </ChartFrame>
  );
}

function WafflePlot({
  width,
  height,
  parts,
  grid,
}: {
  width: number;
  height: number;
  parts: { name: string; squares: number; color: string; share: number }[];
  grid: number;
}) {
  const { active, setActive, keyProps } = useActiveIndex(parts.length);
  const size = Math.min(height, width);
  const gap = 2;
  const cell = (size - gap * (grid - 1)) / grid;
  const owner: number[] = [];
  parts.forEach((p, i) => {
    for (let k = 0; k < p.squares; k++) owner.push(i);
  });
  return (
    <svg width={width} height={size} role="group" aria-roledescription="chart" aria-label="Waffle chart. Use arrow keys to read parts." {...keyProps}>
      {owner.map((o, k) => {
        // fill column by column from the bottom-left so parts read as blocks
        const col = Math.floor(k / grid);
        const row = grid - 1 - (k % grid);
        return (
          <rect
            key={k}
            x={col * (cell + gap)}
            y={row * (cell + gap)}
            width={cell}
            height={cell}
            rx={Math.min(3, cell / 4)}
            style={{ fill: parts[o].color }}
            className={`clui-mark${active !== null && active !== o ? " clui-dim" : ""}`}
            onPointerEnter={() => setActive(o)}
            onPointerLeave={() => setActive(null)}
          >
            <title>{`${parts[o].name}: ${formatShare(parts[o].share, 1)}`}</title>
          </rect>
        );
      })}
      {active !== null && parts[active] && (
        <g aria-hidden>
          <text x={size + 20} y={size / 2 - 8} className="clui-label-strong" style={{ fontSize: 22 }}>
            {formatShare(parts[active].share)}
          </text>
          <text x={size + 20} y={size / 2 + 14} className="clui-annot">
            {parts[active].name}
          </text>
        </g>
      )}
    </svg>
  );
}

Donut chart

One whole in up to six parts, with the total in the middle and a value legend.

Pie chart

Two to five parts of one whole, with a value-and-share legend.