Skip to content
ChartslibraryUI
Get Pro

React correlation matrix

How strongly each pair of metrics moves together, from -1 to +1, computed from your raw rows.

FreeMIT · install in one command<CorrelationMatrix />

A correlation matrix shows how strongly each pair of numeric columns moves together. Every cell holds a coefficient from -1 (one goes up as the other goes down) to +1 (they rise together), coloured on a diverging scale with white at zero, so the strong pairs stand out at a glance.

You pass raw rows and the columns to compare; the chart does the maths. Pearson measures straight-line relationships; Spearman ranks the values first, so it is robust to outliers and curved relationships. Each pair uses the rows where both values exist, and the tooltip says how many. Columns with no variation, pairs with too few rows and small samples are flagged instead of showing a misleading number. By default only the lower triangle is drawn, because the matrix is symmetric and the diagonal is always 1.

Correlation is a starting point: look at the strongest pairs on a scatter chart before drawing conclusions.

When to use

  • Which account metrics move together
  • Checking drivers before a forecast or model
  • Survey items that measure the same thing

When not to use

Good practice

  • Correlation is not cause: say so when the title suggests one.
  • Use Spearman when there are outliers or curved relationships.
  • Check the strongest pairs on a scatter chart.

Installation

Correlation matrix is free under the MIT license.

pnpm dlx shadcn@latest add https://chartslibraryui.com/r/correlation-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 correlation matrix for your AI tool and attach it to Claude, ChatGPT, Lovable or Cursor. No terminal needed. How it works

Usage

import { CorrelationMatrix } from "@/components/charts/correlation-matrix";
import { accountHealth, accountHealthLabels } from "./sample-data";

export function Example() {
  return (
    <CorrelationMatrix
      title="Accounts that log in more use more features; more tickets go with lower NPS"
      subtitle="Pearson correlation between account metrics, 180 customers"
      data={accountHealth}
      columns={columns}
      labels={accountHealthLabels}
    />
  );
}

Data

One row per observation with a numeric key per metric. Pass the keys to compare in `columns`.

[{ seats: 24, logins: 7.5, tickets: 3, nps: 8 }, ...]

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 CorrelationMatrixProps extends FrameProps {
  /** Raw rows, one per observation (customer, day, deal). */
  data: Row[];
  /** Keys of the numeric columns to correlate, in display order. */
  columns: string[];
  /** Display names for the columns, e.g. { mrr: "MRR" }. */
  labels?: Record<string, string>;
  /** "pearson" (straight-line relationships, default) or "spearman" (rank order, robust to outliers). */
  method?: "pearson" | "spearman";
  /** "lower" shows each pair once (default); "full" shows the whole square. */
  triangle?: "lower" | "full";
  /** Decimals for the coefficients. Default 2. */
  decimals?: number;
}

Source

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

View correlation-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 { ChartFrame, ChartTooltip, useActiveIndex, type FrameProps } from "./core/frame";
import { divergingStep } from "./core/scale";
import { textWidth, truncate } from "./core/text";

export interface CorrelationMatrixProps extends FrameProps {
  /** Raw rows, one per observation (customer, day, deal). */
  data: Row[];
  /** Keys of the numeric columns to correlate, in display order. */
  columns: string[];
  /** Display names for the columns, e.g. { mrr: "MRR" }. */
  labels?: Record<string, string>;
  /** "pearson" (straight-line relationships, default) or "spearman" (rank order, robust to outliers). */
  method?: "pearson" | "spearman";
  /** "lower" shows each pair once (default); "full" shows the whole square. */
  triangle?: "lower" | "full";
  /** Decimals for the coefficients. Default 2. */
  decimals?: number;
}

interface Cell {
  a: number;
  b: number;
  r: number | null;
  n: number;
}

const MIN_PAIRS = 3;

function ranks(v: number[]): number[] {
  const idx = v.map((x, i) => [x, i] as [number, number]).sort((p, q) => p[0] - q[0]);
  const out = new Array<number>(v.length);
  for (let i = 0; i < idx.length; ) {
    let j = i;
    while (j + 1 < idx.length && idx[j + 1][0] === idx[i][0]) j++;
    const avg = (i + j) / 2 + 1;
    for (let k = i; k <= j; k++) out[idx[k][1]] = avg;
    i = j + 1;
  }
  return out;
}

function pearson(x: number[], y: number[]): number | null {
  const n = x.length;
  if (n < MIN_PAIRS) return null;
  const mx = x.reduce((a, b) => a + b, 0) / n;
  const my = y.reduce((a, b) => a + b, 0) / n;
  let sxy = 0;
  let sxx = 0;
  let syy = 0;
  for (let i = 0; i < n; i++) {
    sxy += (x[i] - mx) * (y[i] - my);
    sxx += (x[i] - mx) ** 2;
    syy += (y[i] - my) ** 2;
  }
  if (sxx === 0 || syy === 0) return null;
  return Math.max(-1, Math.min(1, sxy / Math.sqrt(sxx * syy)));
}

const strength = (r: number) => {
  const a = Math.abs(r);
  const s = a >= 0.7 ? "strong" : a >= 0.4 ? "moderate" : a >= 0.2 ? "weak" : "little or no";
  return a < 0.2 ? `${s} relationship` : `${s} ${r > 0 ? "positive" : "negative"}`;
};

/**
 * How strongly each pair of numeric columns moves together, from -1 to +1, as a colour grid with the coefficient in
 * each cell. Computed for you from raw rows (Pearson or Spearman), each pair from the rows where both values exist.
 */
export function CorrelationMatrix({ data, columns, labels = {}, method = "pearson", triangle = "lower", decimals = 2, height: hProp, ...frame }: CorrelationMatrixProps) {
  const colSig = (columns ?? []).join("|");
  const prep = useMemo(() => {
    const issues: Issue[] = [];
    const cols = (columns ?? []).filter((c, i, a) => a.indexOf(c) === i);
    if (!Array.isArray(data) || !data.length) return { cells: [] as Cell[], cols, issues: [{ level: "error", message: "No data to display." }] as Issue[] };
    if (cols.length < 2) return { cells: [] as Cell[], cols, issues: [{ level: "error", message: "Pass at least two keys in `columns`." }] as Issue[] };
    const vals: (number | null)[][] = cols.map(() => []);
    let invalid = 0;
    let missing = 0;
    for (const r of data)
      cols.forEach((c, j) => {
        const n = readNum(r?.[c]);
        if (n.state === "invalid") {
          invalid++;
          vals[j].push(null);
        } else {
          if (n.value === null) missing++;
          vals[j].push(n.value);
        }
      });
    if (invalid) issues.push({ level: "error", message: `${invalid} value(s) are not numbers. Convert them before charting.` });
    if (missing) issues.push({ level: "note", message: `${missing} missing value(s); each pair uses the rows where both values exist.` });
    const flat = cols.map((c, j) => {
      const present = vals[j].filter((v): v is number => v !== null);
      return present.length > 1 && present.every((v) => v === present[0]) ? c : null;
    }).filter(Boolean);
    if (flat.length) issues.push({ level: "note", message: `${flat.map((c) => labels[c!] ?? c).join(", ")} ha${flat.length === 1 ? "s" : "ve"} no variation, so ${flat.length === 1 ? "its" : "their"} correlations are blank.` });
    const cells: Cell[] = [];
    let thin = 0;
    for (let a = 0; a < cols.length; a++)
      for (let b = 0; b < a; b++) {
        const x: number[] = [];
        const y: number[] = [];
        for (let i = 0; i < data.length; i++) {
          const va = vals[a][i];
          const vb = vals[b][i];
          if (va !== null && vb !== null && va !== undefined && vb !== undefined) {
            x.push(va);
            y.push(vb);
          }
        }
        if (x.length < MIN_PAIRS) thin++;
        const r = method === "spearman" ? pearson(ranks(x), ranks(y)) : pearson(x, y);
        cells.push({ a, b, r, n: x.length });
      }
    if (thin) issues.push({ level: "note", message: `${thin} pair(s) have fewer than ${MIN_PAIRS} rows with both values and are blank.` });
    const minN = Math.min(...cells.map((c) => c.n));
    if (cells.length && minN >= MIN_PAIRS && minN < 10) issues.push({ level: "warning", message: `Some correlations come from fewer than 10 rows (as few as ${minN}); treat them as rough.` });
    return { cells, cols, issues };
  }, [data, colSig, method]); // eslint-disable-line react-hooks/exhaustive-deps

  const { cells, cols } = prep;
  const name = (c: string) => labels[c] ?? c;
  const fmt = (r: number | null) => (r === null ? "–" : r.toFixed(decimals).replace(/^-/, "−"));
  const height = hProp ?? Math.max(200, Math.min(600, cols.length * 52 + 110));
  const ranked = cells.filter((c) => c.r !== null).sort((p, q) => q.r! - p.r!);
  const top = ranked[0];
  const bottom = ranked[ranked.length - 1];
  const table = {
    columns: [
      { key: "a", label: "Column A" },
      { key: "b", label: "Column B" },
      { key: "r", label: method === "spearman" ? "Spearman ρ" : "Pearson r", align: "right" as const, format: (v: unknown) => fmt(v as number | null) },
      { key: "n", label: "Rows", align: "right" as const },
    ],
    rows: cells.map((c) => ({ a: name(cols[c.a]), b: name(cols[c.b]), r: c.r, n: c.n })),
  };
  const summary = `Correlation matrix (${method}) of ${cols.length} columns, ${cells.length} pairs.${
    top ? ` Strongest positive: ${name(cols[top.a])} and ${name(cols[top.b])}, ${fmt(top.r)}.` : ""
  }${bottom && bottom !== top && bottom.r! < 0 ? ` Strongest negative: ${name(cols[bottom.a])} and ${name(cols[bottom.b])}, ${fmt(bottom.r)}.` : ""}`;
  return (
    <ChartFrame {...frame} height={height} issues={prep.issues} table={table} summary={summary}>
      {({ width }) => <Grid {...{ width, height, cells, cols, name, fmt, triangle, method }} />}
    </ChartFrame>
  );
}

function Grid(p: { width: number; height: number; cells: Cell[]; cols: string[]; name: (c: string) => string; fmt: (r: number | null) => string; triangle: "lower" | "full"; method: string }) {
  const { width, height, cells, cols, name, fmt, triangle } = p;
  const k = cols.length;
  const lower = triangle === "lower";
  // lower triangle: rows 2..k, columns 1..k-1 (the diagonal is always 1, so it is left out)
  const rowIdx = lower ? cols.map((_, i) => i).slice(1) : cols.map((_, i) => i);
  const colIdx = lower ? cols.map((_, i) => i).slice(0, -1) : cols.map((_, i) => i);
  const get = (a: number, b: number): Cell | null => {
    if (a === b) return { a, b, r: 1, n: 0 };
    const c = cells.find((x) => (x.a === a && x.b === b) || (x.a === b && x.b === a));
    return c ?? null;
  };
  const shown = rowIdx.flatMap((a) => colIdx.map((b) => ({ a, b, show: lower ? b < a : true })));
  const { active, setActive, keyProps } = useActiveIndex(shown.length, { columns: colIdx.length, describe: (i) => ({ label: `${name(cols[shown[i].a])} × ${name(cols[shown[i].b])}` }) });
  const labelW = Math.min(Math.max(...rowIdx.map((i) => textWidth(name(cols[i]), AXIS_FONT)), 24) + 16, width * 0.32);
  const legendH = 28;
  const sizeFor = (labelH: number) =>
    Math.max(16, Math.min(64, (width - labelW - 4) / Math.max(1, colIdx.length), (height - legendH - labelH - 4) / Math.max(1, rowIdx.length)));
  // column names: horizontal when they fit the cell, otherwise slanted so they never overlap
  const colNameW = Math.max(...colIdx.map((j) => textWidth(name(cols[j]), AXIS_FONT)), 0);
  const slant = colNameW > sizeFor(20) - 8;
  const SIN = Math.sin((40 * Math.PI) / 180);
  const slantMax = 110;
  const colLabelH = slant ? Math.min(slantMax, colNameW * SIN + 14) : 20;
  const cell = sizeFor(colLabelH);
  const left = labelW;
  const topY = colLabelH;
  const a = active !== null && shown[active]?.show ? shown[active] : null;
  const ac = a ? get(a.a, a.b) : null;
  const showText = cell >= 30;
  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Correlation matrix. Use arrow keys to move between pairs." {...keyProps}>
        {colIdx.map((j, cj) => (
          <text
            key={j}
            x={left + cj * cell + cell / 2}
            y={topY - 6}
            textAnchor={slant ? "start" : "middle"}
            transform={slant ? `rotate(-40 ${left + cj * cell + cell / 2} ${topY - 6})` : undefined}
            className="clui-tick"
          >
            {slant ? truncate(name(cols[j]), (slantMax - 14) / SIN, AXIS_FONT) : name(cols[j])}
          </text>
        ))}
        {rowIdx.map((i, ri) => (
          <text key={i} x={labelW - 10} y={topY + ri * cell + cell / 2} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
            {truncate(name(cols[i]), labelW - 14, AXIS_FONT)}
          </text>
        ))}
        {shown.map((s, idx) => {
          if (!s.show) return null;
          const ri = rowIdx.indexOf(s.a);
          const cj = colIdx.indexOf(s.b);
          const c = get(s.a, s.b);
          const r = c?.r ?? null;
          const diag = s.a === s.b;
          const step = r === null || diag ? 0 : divergingStep(r, 1);
          const fill = diag ? "var(--clui-grid)" : r === null ? "transparent" : tokens.div(step);
          const ink = diag || r === null ? "var(--clui-ink-2)" : tokens.divInk(step);
          return (
            <g key={idx} onPointerEnter={() => setActive(idx)} onPointerLeave={() => setActive(null)}>
              <rect x={left + cj * cell + 1} y={topY + ri * cell + 1} width={cell - 2} height={cell - 2} rx={2} style={{ fill, stroke: r === null && !diag ? "var(--clui-grid)" : "none" }} />
              {showText && (
                <text x={left + cj * cell + cell / 2} y={topY + ri * cell + cell / 2} dy="0.32em" textAnchor="middle" style={{ fontSize: 10.5, fill: ink, fontVariantNumeric: "tabular-nums" }} aria-hidden>
                  {diag ? "1" : fmt(r)}
                </text>
              )}
            </g>
          );
        })}
        {a && (
          <rect
            x={left + colIdx.indexOf(a.b) * cell}
            y={topY + rowIdx.indexOf(a.a) * cell}
            width={cell}
            height={cell}
            fill="none"
            style={{ stroke: "var(--clui-ink)" }}
            strokeWidth={2}
            rx={2}
            pointerEvents="none"
          />
        )}
      </svg>
      <div style={{ position: "absolute", left, bottom: 0, display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: "var(--clui-ink-2)" }} aria-hidden>
        <span style={{ fontVariantNumeric: "tabular-nums" }}>−1</span>
        <span style={{ display: "flex", gap: 1 }}>
          {[-3, -2, -1, 0, 1, 2, 3].map((s) => (
            <span key={s} style={{ width: 16, height: 10, borderRadius: 2, background: tokens.div(s) }} />
          ))}
        </span>
        <span style={{ fontVariantNumeric: "tabular-nums" }}>+1</span>
      </div>
      {a && ac && a.a !== a.b && (
        <ChartTooltip
          x={left + colIdx.indexOf(a.b) * cell + cell / 2}
          y={topY + rowIdx.indexOf(a.a) * cell + cell / 2}
          width={width}
          height={height}
          data={{
            title: `${name(cols[a.a])} × ${name(cols[a.b])}`,
            rows: [
              { label: p.method === "spearman" ? "Spearman ρ" : "Pearson r", value: fmt(ac.r), strong: true },
              ...(ac.r !== null ? [{ label: "Reads as", value: strength(ac.r) }] : []),
              { label: "Rows used", value: String(ac.n) },
            ],
          }}
        />
      )}
    </>
  );
}

Scatter chart

The relationship between two measures, with groups, bubbles, quadrants and a trend line.

Pro

Heatmap

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

Small multiples

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

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.