Skip to content
ChartslibraryUI
Get Pro

React confusion matrix

Actual vs predicted classes for a classifier, with recall per row, precision per column and accuracy.

FreeMIT · install in one command<ConfusionMatrix />

A confusion matrix shows how a classifier's predictions line up with the truth. True classes run down the side, predicted classes across the top, and the diagonal holds the correct predictions; every other cell is a specific mistake, such as bugs filed as feature requests.

By default each row is shown as a share of its true class, so a rare class with poor results isn't hidden behind a common one; counts appear under the shares and in the tooltip. Recall is printed at the end of each row and precision under each column, with overall accuracy below. You can pass one row per prediction or pre-counted pairs, and fix the class order with `classes`.

To choose the score cut-off that produced these predictions, use a ROC or precision-recall curve.

When to use

  • Evaluating a classification or AI model
  • Ticket, document or intent routing quality
  • Fraud or spam detection results

When not to use

Good practice

  • Show shares of each actual class, so rare classes aren't hidden.
  • Name the costly mistake in the title.
  • Keep the class order the same across charts.

Installation

Confusion matrix is free under the MIT license.

pnpm dlx shadcn@latest add https://chartslibraryui.com/r/confusion-matrix.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

Building with an AI tool? Download the confusion matrix for your AI tool and attach it to Claude, ChatGPT, Lovable or Cursor. No terminal needed. How it works

Usage

import { ConfusionMatrix } from "@/components/charts/confusion-matrix";
import { ticketClassifier } from "./sample-data";

export function Example() {
  return (
    <ConfusionMatrix
      title="The classifier mixes up bugs and feature requests most often"
      subtitle="Support tickets by actual and predicted category, share of each actual category, November"
      data={ticketClassifier}
      actual="actual"
      predicted="predicted"
      count="count"
    />
  );
}

Data

Rows with an actual and a predicted class, either one per prediction or one per pair with a count.

[{ actual: "Bug", predicted: "Feature request", count: 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 ConfusionMatrixProps extends FrameProps {
  /** Rows, either one per prediction or one per (actual, predicted) pair with a count. */
  data: Row[];
  /** Key of the true class. */
  actual: string;
  /** Key of the predicted class. */
  predicted: string;
  /** Optional key of a count. Without it, every row counts once. */
  count?: string;
  /** Class order. Default: order of first appearance. */
  classes?: string[];
  /** "row" colours and labels each cell by its share of the actual class (default); "none" uses raw counts. */
  normalize?: "row" | "none";
}

Source

Installs confusion-matrix.tsx and the shared core/ (12 files).

View confusion-matrix.tsx
"use client";

import { useMemo } from "react";
import { AXIS_FONT } from "./core/axis";
import { color as tokens } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatShare } from "./core/format";
import { ChartFrame, ChartTooltip, useActiveIndex, type FrameProps } from "./core/frame";
import { sequentialStep } from "./core/scale";
import { textWidth, truncate } from "./core/text";

export interface ConfusionMatrixProps extends FrameProps {
  /** Rows, either one per prediction or one per (actual, predicted) pair with a count. */
  data: Row[];
  /** Key of the true class. */
  actual: string;
  /** Key of the predicted class. */
  predicted: string;
  /** Optional key of a count. Without it, every row counts once. */
  count?: string;
  /** Class order. Default: order of first appearance. */
  classes?: string[];
  /** "row" colours and labels each cell by its share of the actual class (default); "none" uses raw counts. */
  normalize?: "row" | "none";
}

interface Matrix {
  classes: string[];
  m: number[][];
  rowSum: number[];
  colSum: number[];
  total: number;
  correct: number;
}

/**
 * How a classifier's predictions line up with the truth: true classes down the side, predicted classes across the
 * top, the diagonal is correct. Each row is shown as a share of its true class, with recall per row, precision per
 * column and overall accuracy, so the confusions that matter stand out.
 */
export function ConfusionMatrix({ data, actual, predicted, count, classes: order, normalize = "row", height: hProp, ...frame }: ConfusionMatrixProps) {
  const orderSig = (order ?? []).join("|");
  const prep = useMemo(() => {
    const issues: Issue[] = [];
    const empty: Matrix = { classes: [], m: [], rowSum: [], colSum: [], total: 0, correct: 0 };
    if (!Array.isArray(data) || !data.length) return { mx: empty, issues: [{ level: "error", message: "No data to display." }] as Issue[] };
    const seen: string[] = [];
    const add = (c: string) => {
      if (!seen.includes(c)) seen.push(c);
    };
    const pairs: [string, string, number][] = [];
    let invalid = 0;
    let negative = 0;
    let blank = 0;
    for (const r of data) {
      const a = r?.[actual];
      const p = r?.[predicted];
      if (a === null || a === undefined || String(a).trim() === "" || p === null || p === undefined || String(p).trim() === "") {
        blank++;
        continue;
      }
      let n = 1;
      if (count) {
        const v = readNum(r?.[count]);
        if (v.state === "invalid") {
          invalid++;
          continue;
        }
        if (v.value === null) {
          blank++;
          continue;
        }
        if (v.value < 0) {
          negative++;
          continue;
        }
        n = v.value;
      }
      add(String(a));
      add(String(p));
      pairs.push([String(a), String(p), n]);
    }
    if (invalid) issues.push({ level: "error", message: `"${count}" has ${invalid} non-numeric value(s).` });
    if (negative) issues.push({ level: "error", message: `${negative} negative count(s); counts must be zero or more.` });
    if (blank) issues.push({ level: "note", message: `${blank} row(s) without an actual or predicted class are left out.` });
    const classes = order?.length ? [...order, ...seen.filter((c) => !order.includes(c))] : seen;
    if (order?.length && classes.length > order.length) issues.push({ level: "note", message: `Classes not in \`classes\` were added at the end: ${classes.slice(order.length).join(", ")}.` });
    const k = classes.length;
    const m = classes.map(() => new Array<number>(k).fill(0));
    for (const [a, p, n] of pairs) m[classes.indexOf(a)][classes.indexOf(p)] += n;
    const rowSum = m.map((r) => r.reduce((s, v) => s + v, 0));
    const colSum = classes.map((_, j) => m.reduce((s, r) => s + r[j], 0));
    const total = rowSum.reduce((s, v) => s + v, 0);
    const correct = classes.reduce((s, _, i) => s + m[i][i], 0);
    if (!invalid && total <= 0) issues.push({ level: "error", message: "No predictions to display." });
    const never = classes.filter((_, i) => rowSum[i] === 0);
    if (never.length && total > 0) issues.push({ level: "note", message: `${never.join(", ")} never appear${never.length === 1 ? "s" : ""} as the actual class, so there is no recall to show.` });
    if (k > 12) issues.push({ level: "warning", message: `${k} classes make a dense grid; consider grouping the rare ones.` });
    return { mx: { classes, m, rowSum, colSum, total, correct }, issues };
  }, [data, actual, predicted, count, orderSig]); // eslint-disable-line react-hooks/exhaustive-deps

  const { mx } = prep;
  const { classes, m, rowSum, colSum, total, correct } = mx;
  const k = classes.length;
  const height = hProp ?? Math.max(200, Math.min(560, k * 48 + 96));
  const recall = (i: number) => (rowSum[i] > 0 ? m[i][i] / rowSum[i] : null);
  const precision = (j: number) => (colSum[j] > 0 ? m[j][j] / colSum[j] : null);
  let worst: { a: number; p: number; n: number } | null = null;
  for (let i = 0; i < k; i++) for (let j = 0; j < k; j++) if (i !== j && m[i][j] > 0 && (!worst || m[i][j] > worst.n)) worst = { a: i, p: j, n: m[i][j] };
  const table = {
    columns: [
      { key: "a", label: "Actual" },
      { key: "p", label: "Predicted" },
      { key: "n", label: "Count", align: "right" as const },
      { key: "s", label: "Share of actual", align: "right" as const, format: (v: unknown) => (v === null ? "–" : formatShare(v as number, 1)) },
    ],
    rows: classes.flatMap((a, i) => classes.map((p, j) => ({ a, p, n: m[i][j], s: rowSum[i] > 0 ? m[i][j] / rowSum[i] : null }))),
  };
  const summary = `Confusion matrix of ${total} predictions across ${k} classes. Accuracy ${total > 0 ? formatShare(correct / total, 1) : "–"}. ${classes
    .map((c, i) => `${c}: recall ${recall(i) === null ? "–" : formatShare(recall(i)!, 0)}, precision ${precision(i) === null ? "–" : formatShare(precision(i)!, 0)}`)
    .join("; ")}.${worst ? ` Most common mistake: ${classes[worst.a]} predicted as ${classes[worst.p]} (${worst.n}).` : ""}`;
  return (
    <ChartFrame {...frame} height={height} issues={prep.issues} table={table} summary={summary}>
      {({ width }) => <Grid {...{ width, height, mx, normalize, recall, precision }} />}
    </ChartFrame>
  );
}

function Grid(p: { width: number; height: number; mx: Matrix; normalize: "row" | "none"; recall: (i: number) => number | null; precision: (j: number) => number | null }) {
  const { width, height, mx, normalize, recall, precision } = p;
  const { classes, m, rowSum, total, correct } = mx;
  const k = classes.length;
  const { active, setActive, keyProps } = useActiveIndex(k * k, { columns: k, describe: (i) => ({ label: `Actual ${classes[Math.floor(i / k)]}, predicted ${classes[i % k]}` }) });
  const labelW = Math.min(Math.max(...classes.map((c) => textWidth(c, AXIS_FONT)), textWidth("Precision", AXIS_FONT), 24) + 16, width * 0.28);
  const metaW = 58;
  const headH = 36;
  const footH = 26;
  const capH = 20;
  const cell = Math.max(18, Math.min(84, (width - labelW - metaW - 8) / Math.max(1, k), (height - headH - footH - capH) / Math.max(1, k)));
  const left = labelW;
  const top = headH;
  const maxCount = Math.max(0, ...m.flat());
  const share = (i: number, j: number) => (rowSum[i] > 0 ? m[i][j] / rowSum[i] : 0);
  const stepOf = (i: number, j: number) => {
    const v = normalize === "row" ? share(i, j) : m[i][j];
    const hi = normalize === "row" ? 1 : maxCount;
    return v <= 0 ? 0 : sequentialStep(v, 0, hi, 7);
  };
  const a = active !== null ? { i: Math.floor(active / k), j: active % k } : null;
  const two = cell >= 46;
  const one = cell >= 30;
  const pct = (v: number | null) => (v === null ? "–" : formatShare(v, 0));
  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Confusion matrix. Use arrow keys to move between cells." {...keyProps}>
        <text x={left} y={10} className="clui-annot">
          Predicted
        </text>
        <text x={labelW - 10} y={top - 6} textAnchor="end" className="clui-annot">
          Actual
        </text>
        <text x={left + k * cell + metaW - 6} y={top - 6} textAnchor="end" className="clui-annot">
          Recall
        </text>
        {classes.map((c, j) => (
          <text key={c} x={left + j * cell + cell / 2} y={top - 6} textAnchor="middle" className="clui-tick">
            {truncate(c, Math.max(cell - 4, 28), AXIS_FONT)}
          </text>
        ))}
        {classes.map((c, i) => (
          <g key={c}>
            <text x={labelW - 10} y={top + i * cell + cell / 2} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
              {truncate(c, labelW - 14, AXIS_FONT)}
            </text>
            {classes.map((_, j) => {
              const step = stepOf(i, j);
              const x = left + j * cell;
              const y = top + i * cell;
              const fill = step === 0 ? "var(--clui-surface)" : tokens.seq(step);
              const ink = step === 0 ? "var(--clui-ink-3)" : tokens.seqInk(step);
              const main = normalize === "row" ? (rowSum[i] > 0 ? formatShare(share(i, j), 0) : "–") : String(m[i][j]);
              return (
                <g key={j} onPointerEnter={() => setActive(i * k + j)} onPointerLeave={() => setActive(null)}>
                  <rect x={x + 1} y={y + 1} width={cell - 2} height={cell - 2} rx={2} style={{ fill, stroke: step === 0 ? "var(--clui-grid)" : "none" }} />
                  {i === j && <rect x={x + 3} y={y + 3} width={cell - 6} height={cell - 6} rx={2} fill="none" style={{ stroke: ink, opacity: 0.45 }} strokeDasharray="3 2" aria-hidden />}
                  {one && (
                    <text x={x + cell / 2} y={y + cell / 2 - (two && normalize === "row" ? 6 : 0)} dy="0.32em" textAnchor="middle" style={{ fontSize: 11, fontWeight: i === j ? 600 : 400, fill: ink, fontVariantNumeric: "tabular-nums" }} aria-hidden>
                      {main}
                    </text>
                  )}
                  {two && normalize === "row" && (
                    <text x={x + cell / 2} y={y + cell / 2 + 9} dy="0.32em" textAnchor="middle" style={{ fontSize: 9.5, fill: ink, opacity: 0.85, fontVariantNumeric: "tabular-nums" }} aria-hidden>
                      {m[i][j]}
                    </text>
                  )}
                </g>
              );
            })}
            <text x={left + k * cell + metaW - 6} y={top + i * cell + cell / 2} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)", fontVariantNumeric: "tabular-nums" }}>
              {pct(recall(i))}
            </text>
          </g>
        ))}
        <text x={labelW - 10} y={top + k * cell + 14} dy="0.32em" textAnchor="end" className="clui-annot">
          Precision
        </text>
        {classes.map((c, j) => (
          <text key={c} x={left + j * cell + cell / 2} y={top + k * cell + 14} dy="0.32em" textAnchor="middle" className="clui-tick" style={{ fill: "var(--clui-ink)", fontVariantNumeric: "tabular-nums" }}>
            {pct(precision(j))}
          </text>
        ))}
        <text x={left} y={top + k * cell + footH + 10} dy="0.32em" className="clui-label">
          <tspan className="clui-label-strong">Accuracy {total > 0 ? formatShare(correct / total, 1) : "–"}</tspan> · {correct} of {total} correct
        </text>
        {a && <rect x={left + a.j * cell} y={top + a.i * cell} width={cell} height={cell} fill="none" style={{ stroke: "var(--clui-ink)" }} strokeWidth={2} rx={2} pointerEvents="none" />}
      </svg>
      {a && (
        <ChartTooltip
          x={left + a.j * cell + cell / 2}
          y={top + a.i * cell + cell / 2}
          width={width}
          height={height}
          data={{
            title: a.i === a.j ? `${classes[a.i]}: correct` : `Actual ${classes[a.i]}, predicted ${classes[a.j]}`,
            rows: [
              { label: "Count", value: String(m[a.i][a.j]), strong: true },
              { label: `Share of actual ${classes[a.i]}`, value: rowSum[a.i] > 0 ? formatShare(share(a.i, a.j), 1) : "–" },
              { label: "Share of all predictions", value: total > 0 ? formatShare(m[a.i][a.j] / total, 1) : "–" },
            ],
          }}
        />
      )}
    </>
  );
}
Pro

ROC curve

How well a model separates positives from negatives at every cut-off, with AUC, or precision-recall.

Pro

Heatmap

A grid coloured by value, sequential or diverging, with missing cells hatched.

Table chart

A sortable table with inline bars, coloured deltas and sparklines.

Sign in to ChartslibraryUI

New here? The same step creates your account.

Continue with Google
or

No password needed. Bought Pro? Use the email you paid with and your license is there. By signing in you agree to the Terms and Privacy policy.