Skip to content
ChartslibraryUI Get Pro

Strip plot

Every observation visible by group, with the median marked.

FreeMIT · install in one command<StripPlot />

When to use

  • Small and medium samples by group
  • Showing how few points a summary rests on

When not to use

  • Thousands of points per group – use Box plot

Good practice

  • Jitter is deterministic, so the chart doesn't change between renders.
  • Use the table view for summary statistics.

Installation

Strip plot is free under the MIT license.

$ npx shadcn@latest add https://chartslibraryui.com/r/strip-plot.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 { StripPlot } from "@/components/charts/strip-plot";
import { responseTimes } from "./sample-data";

export function Example() {
  return (
    <StripPlot
      title="Priority tickets are answered within hours"
      subtitle="First response time by support tier, hours"
      data={responseTimes}
      group="tier"
      value="hours"
      format={{ kind: "number", decimals: 1, unit: "h" }}
    />
  );
}

Data

Long-format rows with a group key and a numeric value key.

[{ tier: "Priority", hours: 1.4 }, ...]

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 StripPlotProps extends FrameProps {
  data: Row[];
  /** Key of the group (one row of dots per group). */
  group: string;
  /** Key of the numeric value. */
  value: string;
  format?: FormatInput;
  /** Draw the median as a tick. Default true. */
  median?: boolean;
  /** Include zero on the axis. Default false. */
  zero?: boolean;
}

Source

Installs strip-plot.tsx and the shared core/ (11 files).

View strip-plot.tsx
"use client";

import { useMemo, type PointerEvent } from "react";
import { AXIS_FONT, XGrid } from "./core/axis";
import { color as tokens } from "./core/color";
import { quantile, readNum, type Issue, type Row } from "./core/data";
import { formatValue, tickFormatter, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, localPoint, useActiveIndex, type FrameProps } from "./core/frame";
import { linearScale, valueDomain } from "./core/scale";
import { textWidth, truncate } from "./core/text";

export interface StripPlotProps extends FrameProps {
  data: Row[];
  /** Key of the group (one row of dots per group). */
  group: string;
  /** Key of the numeric value. */
  value: string;
  format?: FormatInput;
  /** Draw the median as a tick. Default true. */
  median?: boolean;
  /** Include zero on the axis. Default false. */
  zero?: boolean;
}

/**
 * Every observation visible, grouped. Honest for small and medium samples, where a box plot or average would hide
 * how few points there are. Points are jittered vertically (deterministically) to reduce overlap.
 */
export function StripPlot({ data, group, value, format, median = true, zero = false, height: hProp, ...frame }: StripPlotProps) {
  const { groups, issues } = useMemo(() => {
    const issues: Issue[] = [];
    if (!Array.isArray(data) || !data.length) return { groups: [] as { name: string; values: number[] }[], issues: [{ level: "error", message: "No data to display." }] as Issue[] };
    const map = new Map<string, number[]>();
    let missing = 0;
    let invalid = 0;
    for (const row of data) {
      const r = readNum(row?.[value]);
      if (r.state === "missing") missing++;
      else if (r.state === "invalid") invalid++;
      else {
        const g = String(row?.[group] ?? "");
        if (!map.has(g)) map.set(g, []);
        map.get(g)!.push(r.value!);
      }
    }
    if (invalid) issues.push({ level: "error", message: `${invalid} value(s) are not numbers.` });
    if (missing) issues.push({ level: "note", message: `${missing} missing value(s) are not drawn.` });
    return { groups: [...map.entries()].map(([name, values]) => ({ name, values })), issues };
  }, [data, group, value]);

  const rowH = 44;
  const height = hProp ?? Math.max(120, groups.length * rowH + 34);
  const all = groups.flatMap((g) => g.values.map((v) => ({ g: g.name, v })));
  const table = {
    columns: [
      { key: "group", label: group },
      { key: "n", label: "Count", align: "right" as const },
      { key: "median", label: "Median", align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
      { key: "min", label: "Min", align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
      { key: "max", label: "Max", align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
    ],
    rows: groups.map((g) => {
      const s = [...g.values].sort((a, b) => a - b);
      return { group: g.name, n: s.length, median: quantile(s, 0.5), min: s[0], max: s[s.length - 1] };
    }),
  };
  const summary = `Strip plot of ${all.length} values in ${groups.length} groups. ${table.rows
    .map((r) => `${r.group}: median ${formatValue(r.median, format)}`)
    .join("; ")}.`;

  return (
    <ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary}>
      {({ width }) => <StripInner width={width} height={height} groups={groups} format={format} median={median} zero={zero} />}
    </ChartFrame>
  );
}

function StripInner({ width, height, groups, format, median, zero }: { width: number; height: number; groups: { name: string; values: number[] }[]; format?: FormatInput; median: boolean; zero: boolean }) {
  const pts = useMemo(
    () =>
      groups.flatMap((g, gi) =>
        g.values.map((v, k) => ({ gi, v, k, j: (((k * 2654435761) >>> 0) % 1000) / 1000 - 0.5 })),
      ),
    [groups],
  );
  const order = useMemo(() => pts.map((p, i) => i).sort((a, b) => pts[a].gi - pts[b].gi || pts[a].v - pts[b].v), [pts]);
  const { active, setActive, keyProps } = useActiveIndex(pts.length);
  const labelW = Math.min(Math.max(...groups.map((g) => textWidth(g.name, AXIS_FONT)), 30) + 18, width * 0.3);
  const left = labelW;
  const right = width - 12;
  const top = 6;
  const bottom = height - 22;
  const { domain, ticks } = valueDomain(pts.map((p) => p.v), { includeZero: zero, ticks: Math.max(3, Math.floor((right - left) / 90)) });
  const fx = tickFormatter(format, ticks);
  const sx = linearScale(domain, [left, right]);
  const rowH = (bottom - top) / Math.max(1, groups.length);
  const cy = (gi: number) => top + rowH * gi + rowH / 2;
  const r = pts.length > 600 ? 2.5 : 3.5;
  const ap = active !== null ? pts[order[active]] : null;
  const onMove = (e: PointerEvent<SVGRectElement>) => {
    const { x, y } = localPoint(e);
    let best = -1;
    let bd = Infinity;
    pts.forEach((p, i) => {
      const dx = sx(p.v) - (x + left);
      const dy = cy(p.gi) + p.j * rowH * 0.6 - (y + top);
      const d = dx * dx + dy * dy;
      if (d < bd) {
        bd = d;
        best = i;
      }
    });
    setActive(bd < 400 ? order.indexOf(best) : null);
  };
  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Strip plot. Use arrow keys to step through values." {...keyProps}>
        <XGrid ticks={ticks} x={sx} y0={top} y1={bottom} format={fx} labelY={bottom + 16} />
        {groups.map((g, gi) => (
          <text key={g.name} x={left - 10} y={cy(gi)} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
            {truncate(g.name, left - 14, AXIS_FONT)}
          </text>
        ))}
        {pts.map((p, i) => (
          <circle key={i} cx={sx(p.v)} cy={cy(p.gi) + p.j * rowH * 0.6} r={r} style={{ fill: tokens.series(0), fillOpacity: 0.55, stroke: "var(--clui-surface)" }} strokeWidth={0.75} />
        ))}
        {median &&
          groups.map((g, gi) => {
            const m = quantile([...g.values].sort((a, b) => a - b), 0.5);
            if (!Number.isFinite(m)) return null;
            return <line key={g.name} x1={sx(m)} x2={sx(m)} y1={cy(gi) - rowH * 0.38} y2={cy(gi) + rowH * 0.38} style={{ stroke: "var(--clui-ink)" }} strokeWidth={2.5} strokeLinecap="round" />;
          })}
        {ap && <circle cx={sx(ap.v)} cy={cy(ap.gi) + ap.j * rowH * 0.6} r={r + 3} fill="none" style={{ stroke: "var(--clui-ink)" }} strokeWidth={1.5} />}
        <rect x={left} y={top} width={Math.max(0, right - left)} height={Math.max(0, bottom - top)} fill="transparent" onPointerMove={onMove} onPointerLeave={() => setActive(null)} />
      </svg>
      {ap && (
        <ChartTooltip
          x={sx(ap.v)}
          y={cy(ap.gi)}
          width={width}
          height={height}
          data={{ title: groups[ap.gi].name, rows: [{ label: "Value", value: formatValue(ap.v, format, { context: "tooltip" }) }], footer: median ? "Vertical tick = median" : undefined }}
        />
      )}
    </>
  );
}
Pro

Box plot

Median, quartiles, whiskers and every outlier per group, with n printed.

Histogram

The shape of one distribution, with automatic binning and a median marker.