Skip to content
ChartslibraryUI Get Pro

Small multiples

One small chart per group on a shared scale, instead of a ten-colour spaghetti chart.

FreeMIT · install in one command<SmallMultiples />

When to use

  • The same metric across many regions or products
  • Comparing shapes across five or more series

When not to use

  • Two or three series that need precise comparison – use Line chart

Good practice

  • Keep the shared scale; independent scales hide differences in level and are flagged in a note.
  • Order panels meaningfully (order="last-desc").

Installation

Small multiples is free under the MIT license.

$ npx shadcn@latest add https://chartslibraryui.com/r/small-multiples.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 { SmallMultiples } from "@/components/charts/small-multiples";
import { signupsByRegion } from "./sample-data";

export function Example() {
  return (
    <SmallMultiples
      title="Signups are rising everywhere except the Nordics and MEA"
      subtitle="New signups per month, shared scale"
      data={signupsByRegion}
      facet="region"
      x="month"
      y="signups"
      format="integer"
      kind="area"
      order="last-desc"
    />
  );
}

Data

Long-format rows: facet key, x key, value key.

[{ region: "Nordics", month: "Jan", signups: 212 }, ...]

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 SmallMultiplesProps extends FrameProps {
  /** Long-format rows: one row per (panel, x) pair. */
  data: Row[];
  /** Key that splits rows into panels. */
  facet: string;
  x: string;
  y: string;
  kind?: "line" | "area" | "bar";
  format?: FormatInput;
  /** Same y scale in every panel (default true). Turn off only when shapes matter more than levels, and say so. */
  sharedScale?: boolean;
  /** Minimum panel width. Columns are derived from the container width. */
  minPanelWidth?: number;
  /** Height of each panel's plot. */
  panelHeight?: number;
  /** Panel names to emphasise. */
  highlight?: string[];
  /** Panel order: data order (default) or by the last value. */
  order?: "data" | "last-desc" | "last-asc";
}

Source

Installs small-multiples.tsx and the shared core/ (11 files).

View small-multiples.tsx
"use client";

import { useMemo, useState } from "react";
import { color as tokens } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatValue, tickFormatter, type FormatInput } from "./core/format";
import { ChartFrame, localPoint, type FrameProps } from "./core/frame";
import { areaPath, barPath, linePath, type MaybePoint } from "./core/path";
import { bandScale, linearScale, pointScale, valueDomain } from "./core/scale";
import { truncate } from "./core/text";

export interface SmallMultiplesProps extends FrameProps {
  /** Long-format rows: one row per (panel, x) pair. */
  data: Row[];
  /** Key that splits rows into panels. */
  facet: string;
  x: string;
  y: string;
  kind?: "line" | "area" | "bar";
  format?: FormatInput;
  /** Same y scale in every panel (default true). Turn off only when shapes matter more than levels, and say so. */
  sharedScale?: boolean;
  /** Minimum panel width. Columns are derived from the container width. */
  minPanelWidth?: number;
  /** Height of each panel's plot. */
  panelHeight?: number;
  /** Panel names to emphasise. */
  highlight?: string[];
  /** Panel order: data order (default) or by the last value. */
  order?: "data" | "last-desc" | "last-asc";
}

interface Panel {
  name: string;
  xs: string[];
  ys: (number | null)[];
}

/**
 * One small chart per group on a shared scale, instead of a spaghetti chart with ten colours. Readers compare
 * shapes across panels at a glance. Hover any panel to read the same period in every panel.
 */
export function SmallMultiples({
  data,
  facet,
  x,
  y,
  kind = "line",
  format,
  sharedScale = true,
  minPanelWidth = 180,
  panelHeight = 90,
  highlight,
  order = "data",
  ...frame
}: SmallMultiplesProps) {
  const { panels, issues, xsAll } = useMemo(() => {
    const issues: Issue[] = [];
    if (!Array.isArray(data) || !data.length) return { panels: [] as Panel[], issues: [{ level: "error", message: "No data to display." }] as Issue[], xsAll: [] as string[] };
    const map = new Map<string, Map<string, number | null>>();
    const xsAll: string[] = [];
    let invalid = 0;
    let missing = 0;
    for (const row of data) {
      const f = String(row?.[facet] ?? "");
      const xv = String(row?.[x] ?? "");
      const r = readNum(row?.[y]);
      if (r.state === "invalid") invalid++;
      if (r.state === "missing") missing++;
      if (!map.has(f)) map.set(f, new Map());
      map.get(f)!.set(xv, r.value);
      if (!xsAll.includes(xv)) xsAll.push(xv);
    }
    if (invalid) issues.push({ level: "error", message: `${invalid} value(s) in "${y}" are not numbers.` });
    if (missing) issues.push({ level: "note", message: `${missing} missing value(s) shown as gaps.` });
    let panels: Panel[] = [...map.entries()].map(([name, m]) => ({ name, xs: xsAll, ys: xsAll.map((xv) => (m.has(xv) ? m.get(xv)! : null)) }));
    if (order !== "data") {
      const last = (p: Panel) => [...p.ys].reverse().find((v) => v !== null) ?? -Infinity;
      panels = panels.sort((a, b) => (order === "last-desc" ? last(b) - last(a) : last(a) - last(b)));
    }
    if (!sharedScale) issues.push({ level: "note", message: "Each panel has its own y scale; compare shapes, not levels." });
    return { panels, issues, xsAll };
  }, [data, facet, x, y, order, sharedScale]);

  const table = {
    columns: [{ key: "__x", label: x }, ...panels.map((p) => ({ key: p.name, label: p.name, align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) }))],
    rows: xsAll.map((xv, i) => ({ __x: xv, ...Object.fromEntries(panels.map((p) => [p.name, p.ys[i]])) })),
  };
  const summary = `Small multiples: ${panels.length} panels of ${y} by ${x}${sharedScale ? " on a shared scale" : ""}.`;

  return (
    <ChartFrame {...frame} height={0} issues={issues} table={table} summary={summary}>
      {({ width }) => <Grid {...{ width, panels, kind, format, sharedScale, minPanelWidth, panelHeight, highlight }} />}
    </ChartFrame>
  );
}

function Grid(p: {
  width: number;
  panels: Panel[];
  kind: "line" | "area" | "bar";
  format?: FormatInput;
  sharedScale: boolean;
  minPanelWidth: number;
  panelHeight: number;
  highlight?: string[];
}) {
  const [hover, setHover] = useState<number | null>(null);
  const gap = 20;
  const cols = Math.max(1, Math.min(p.panels.length, Math.floor((p.width + gap) / (p.minPanelWidth + gap))));
  const pw = (p.width - gap * (cols - 1)) / cols;
  const all = p.panels.flatMap((pn) => pn.ys.filter((v): v is number => v !== null));
  const shared = valueDomain(all, { includeZero: p.kind !== "line" || Math.min(...all) >= 0, ticks: 2 });
  const hl = p.highlight ? new Set(p.highlight) : null;
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gap: `18px ${gap}px` }}>
      {p.panels.map((pn) => {
        const vals = pn.ys.filter((v): v is number => v !== null);
        const dom = p.sharedScale ? shared : valueDomain(vals, { includeZero: p.kind !== "line", ticks: 2 });
        const fmt = tickFormatter(p.format, dom.ticks);
        const top = 4;
        const bottom = p.panelHeight - 16;
        const left = 0;
        const right = pw;
        const sy = linearScale(dom.domain, [bottom, top]);
        const n = pn.xs.length;
        const ps = pointScale(n, [left + 2, right - 2]);
        const band = bandScale(n, [left, right], { paddingInner: 0.25, paddingOuter: 0.05 });
        const cx = (i: number) => (p.kind === "bar" ? band(i) + band.bandwidth / 2 : ps(i));
        const c = hl && !hl.has(pn.name) ? tokens.context : tokens.series(0);
        const pts: MaybePoint[] = pn.ys.map((v, i) => (v === null ? null : [cx(i), sy(v)]));
        const last = [...pn.ys].reverse().find((v) => v !== null);
        const top2 = dom.ticks[dom.ticks.length - 1];
        return (
          <div key={pn.name} style={{ position: "relative", minWidth: 0 }}>
            <div style={{ display: "flex", justifyContent: "space-between", gap: 8, fontSize: 12, marginBottom: 4 }}>
              <span style={{ fontWeight: 600, color: "var(--clui-ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={pn.name}>
                {truncate(pn.name, pw - 70, 12)}
              </span>
              <span style={{ color: "var(--clui-ink-2)", fontVariantNumeric: "tabular-nums" }}>{formatValue(hover !== null ? pn.ys[hover] : last, p.format)}</span>
            </div>
            <svg width={pw} height={p.panelHeight} aria-hidden onPointerMove={(e) => setHover(p.kind === "bar" ? band.indexAt(localPoint(e).x) : ps.indexAt(localPoint(e).x))} onPointerLeave={() => setHover(null)}>
              <line x1={left} x2={right} y1={sy(top2) + 0.5} y2={sy(top2) + 0.5} style={{ stroke: "var(--clui-grid)" }} />
              <text x={right} y={sy(top2) - 3} textAnchor="end" className="clui-tick" style={{ fontSize: 10 }}>
                {fmt(top2)}
              </text>
              <line x1={left} x2={right} y1={sy(Math.max(dom.domain[0], Math.min(0, dom.domain[1]))) + 0.5} y2={sy(Math.max(dom.domain[0], Math.min(0, dom.domain[1]))) + 0.5} style={{ stroke: "var(--clui-axis)" }} />
              {p.kind === "bar"
                ? pn.ys.map((v, i) =>
                    v === null ? null : (
                      <path key={i} d={barPath(band(i), sy(Math.max(0, v)), band.bandwidth, Math.abs(sy(v) - sy(0)), 2, v >= 0 ? "up" : "down")} style={{ fill: c, opacity: hover !== null && hover !== i ? 0.45 : 1 }} />
                    ),
                  )
                : (
                  <>
                    {p.kind === "area" && <path d={areaPath(pts, sy(Math.max(dom.domain[0], 0)))} style={{ fill: c, opacity: 0.12 }} />}
                    <path d={linePath(pts)} fill="none" style={{ stroke: c }} strokeWidth={1.75} strokeLinejoin="round" />
                  </>
                )}
              {hover !== null && pn.ys[hover] !== null && p.kind !== "bar" && <circle cx={cx(hover)} cy={sy(pn.ys[hover]!)} r={3.5} style={{ fill: c, stroke: "var(--clui-surface)" }} strokeWidth={1.5} />}
              {hover !== null && <line x1={cx(hover)} x2={cx(hover)} y1={top} y2={bottom} style={{ stroke: "var(--clui-axis)" }} />}
              {hover !== null ? (
                <text x={Math.max(16, Math.min(right - 16, cx(hover)))} y={p.panelHeight - 2} textAnchor="middle" className="clui-tick" style={{ fontSize: 10, fill: "var(--clui-ink)" }}>
                  {pn.xs[hover]}
                </text>
              ) : (
                <>
                  <text x={0} y={p.panelHeight - 2} className="clui-tick" style={{ fontSize: 10 }}>
                    {pn.xs[0]}
                  </text>
                  <text x={right} y={p.panelHeight - 2} textAnchor="end" className="clui-tick" style={{ fontSize: 10 }}>
                    {pn.xs[n - 1]}
                  </text>
                </>
              )}
            </svg>
          </div>
        );
      })}
    </div>
  );
}

Line chart

Trends over time for one to four series, with gaps for missing data and marked forecasts.

Index chart

Measures in different units rebased to 100, so growth compares on one honest axis.