Skip to content
ChartslibraryUI Get Pro

Dot plot

Many items on one scale, optionally against a comparison, with no zero required.

FreeMIT · install in one command<DotPlot />

When to use

  • Rates in a narrow band (conversion by segment)
  • Current vs prior per item
  • Long lists where bars would be heavy

When not to use

Good practice

  • Dots encode position, so the axis doesn't need zero; say so if it matters.
  • Sort by value.

Installation

Dot plot is free under the MIT license.

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

export function Example() {
  return (
    <DotPlot
      title="Margins improved in four of six regions"
      subtitle="Contribution margin, this year vs last year"
      data={margins}
      x="region"
      y="margin"
      label="This year"
      compare="prior"
      compareLabel="Last year"
      format={{ kind: "percent", decimals: 0 }}
    />
  );
}

Data

Rows with a label key, a value key and optionally a comparison key.

[{ region: "Nordics", margin: 0.31, prior: 0.29 }, ...]

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 DotPlotProps extends FrameProps {
  data: Row[];
  /** Key of the item label. */
  x: string;
  /** Key of the value. */
  y: string;
  /** Optional comparison key (prior period, plan). Drawn as a hollow dot joined to the current value. */
  compare?: string;
  label?: string;
  compareLabel?: string;
  format?: FormatInput;
  sort?: "none" | "asc" | "desc";
  /** Colour the connector by whether the change is favorable. */
  favorable?: Favorable;
  /** Include zero in the axis. Default false: dots encode position, not length. */
  zero?: boolean;
  /** Show the value next to each dot. Default true when up to 15 rows. */
  labels?: boolean;
}

Source

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

View dot-plot.tsx
"use client";

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

export interface DotPlotProps extends FrameProps {
  data: Row[];
  /** Key of the item label. */
  x: string;
  /** Key of the value. */
  y: string;
  /** Optional comparison key (prior period, plan). Drawn as a hollow dot joined to the current value. */
  compare?: string;
  label?: string;
  compareLabel?: string;
  format?: FormatInput;
  sort?: "none" | "asc" | "desc";
  /** Colour the connector by whether the change is favorable. */
  favorable?: Favorable;
  /** Include zero in the axis. Default false: dots encode position, not length. */
  zero?: boolean;
  /** Show the value next to each dot. Default true when up to 15 rows. */
  labels?: boolean;
}

/**
 * Many items on one shared scale, optionally against a comparison. Uses less ink than bars and doesn't need a zero
 * baseline, which makes it the honest choice for rates that sit in a narrow band.
 */
export function DotPlot({
  data,
  x,
  y,
  compare,
  label,
  compareLabel = "Comparison",
  format,
  sort = "desc",
  favorable = "up",
  zero = false,
  labels,
  height: hProp,
  ...frame
}: DotPlotProps) {
  const { rows, issues, cur, cmp } = useMemo(() => {
    const issues: Issue[] = [];
    if (!Array.isArray(data) || !data.length) return { rows: [] as Row[], issues: [{ level: "error", message: "No data to display." }] as Issue[], cur: [] as (number | null)[], cmp: [] as (number | null)[] };
    const rows = [...data];
    if (sort !== "none") rows.sort((a, b) => ((sort === "asc" ? 1 : -1) * (((a?.[y] as number) ?? -Infinity) - ((b?.[y] as number) ?? -Infinity))));
    const c1 = column(rows, y);
    const c2 = compare ? column(rows, compare) : null;
    if (c1.invalid || c2?.invalid) issues.push({ level: "error", message: "Some values are not numbers." });
    if (c1.missing) issues.push({ level: "note", message: `${c1.missing} item(s) have no value.` });
    return { rows, issues, cur: c1.values, cmp: c2?.values ?? [] };
  }, [data, y, compare, sort]);
  const n = rows.length;
  const height = hProp ?? Math.max(120, n * 30 + 34);
  const legend: LegendItem[] = compare
    ? [
        { key: "cur", label: label ?? y, color: tokens.series(0), shape: "dot" },
        { key: "cmp", label: compareLabel, color: "var(--clui-ink-3)", shape: "ring" },
      ]
    : [];
  const table = {
    columns: [
      { key: "x", label: x },
      { key: "v", label: label ?? y, align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
      ...(compare
        ? [
            { key: "c", label: compareLabel, align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
            { key: "d", label: "Change", align: "right" as const, format: (v: unknown) => formatDelta(v as number, format, "table") },
          ]
        : []),
    ],
    rows: rows.map((r, i) => ({ x: r?.[x], v: cur[i], c: cmp[i], d: cur[i] !== null && cmp[i] != null ? cur[i]! - cmp[i]! : null })),
  };
  const summary = `Dot plot of ${label ?? y} for ${n} items${compare ? ` compared with ${compareLabel}` : ""}.`;

  return (
    <ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary} legend={legend}>
      {({ width }) => (
        <DotInner {...{ width, height, rows, x, cur, cmp, format, favorable, zero, compare: !!compare, labels: labels ?? n <= 15, label: label ?? y, compareLabel }} />
      )}
    </ChartFrame>
  );
}

function DotInner(p: {
  width: number;
  height: number;
  rows: Row[];
  x: string;
  cur: (number | null)[];
  cmp: (number | null)[];
  format?: FormatInput;
  favorable: Favorable;
  zero: boolean;
  compare: boolean;
  labels: boolean;
  label: string;
  compareLabel: string;
}) {
  const { width, height, rows, cur, cmp } = p;
  const n = rows.length;
  const { active, setActive, keyProps } = useActiveIndex(n);
  const names = rows.map((r) => String(r?.[p.x] ?? ""));
  const left = Math.min(Math.max(...names.map((s) => textWidth(s, AXIS_FONT)), 20) + 14, width * 0.36);
  const right = width - (p.labels ? 52 : 14);
  const top = 4;
  const bottom = height - 22;
  const vals = [...cur, ...cmp].filter((v): v is number => v !== null && v !== undefined);
  const { domain, ticks } = valueDomain(vals, { includeZero: p.zero, ticks: Math.max(3, Math.floor((right - left) / 90)) });
  const fx = tickFormatter(p.format, ticks);
  const sx = linearScale(domain, [left, right]);
  const band = bandScale(n, [top, bottom], { paddingInner: 0, paddingOuter: 0 });
  const cy = (i: number) => band(i) + band.bandwidth / 2;
  const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).y + top));

  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Dot plot. Use arrow keys to read items." {...keyProps}>
        <XGrid ticks={ticks} x={sx} y0={top} y1={bottom} format={fx} labelY={bottom + 16} />
        {rows.map((_, i) => {
          const v = cur[i];
          const c = p.compare ? cmp[i] : null;
          const tone = c != null && v != null ? toneOf(v - c, p.favorable) : "neutral";
          return (
            <g key={i} className={`clui-mark${active !== null && active !== i ? " clui-dim" : ""}`}>
              <text x={left - 10} y={cy(i)} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
                {truncate(names[i], left - 14, AXIS_FONT)}
                <title>{names[i]}</title>
              </text>
              <line x1={left} x2={right} y1={cy(i)} y2={cy(i)} style={{ stroke: "var(--clui-grid)" }} strokeDasharray="1 3" />
              {c != null && v != null && <line x1={sx(c)} x2={sx(v)} y1={cy(i)} y2={cy(i)} style={{ stroke: toneColor(tone) }} strokeWidth={2} />}
              {c != null && <circle cx={sx(c)} cy={cy(i)} r={4.5} style={{ fill: "var(--clui-surface)", stroke: "var(--clui-ink-3)" }} strokeWidth={2} />}
              {v != null && <circle cx={sx(v)} cy={cy(i)} r={5} style={{ fill: tokens.series(0), stroke: "var(--clui-surface)" }} strokeWidth={2} />}
              {p.labels && v != null && (
                <text
                  x={c != null && c > v ? sx(v) - 9 : sx(v) + 9}
                  y={cy(i)}
                  dy="0.32em"
                  textAnchor={c != null && c > v ? "end" : "start"}
                  className="clui-label clui-halo"
                >
                  {formatValue(v, p.format)}
                </text>
              )}
            </g>
          );
        })}
        <rect x={0} y={top} width={width} height={Math.max(0, bottom - top)} fill="transparent" onPointerMove={onMove} onPointerLeave={() => setActive(null)} />
      </svg>
      {active !== null && (
        <ChartTooltip
          x={sx(cur[active] ?? domain[0])}
          y={cy(active)}
          width={width}
          height={height}
          data={{
            title: names[active],
            rows: [
              { label: p.label, value: formatValue(cur[active], p.format, { context: "tooltip" }), color: tokens.series(0), shape: "dot" },
              ...(p.compare
                ? [
                    { label: p.compareLabel, value: formatValue(cmp[active], p.format, { context: "tooltip" }), color: "var(--clui-ink-3)", shape: "ring" as const },
                    { label: "Change", value: cur[active] != null && cmp[active] != null ? formatDelta(cur[active]! - cmp[active]!, p.format, "tooltip") : "–", strong: true },
                  ]
                : []),
            ],
          }}
        />
      )}
    </>
  );
}
Pro

Dumbbell chart

Before and after per item with the change printed and coloured by direction.

Slope chart

Two points in time per item, where both change and rank matter.