Menu

Components

Radar Chart

One axis for each measure, all from the same center, and a shape that joins the values: compare profiles at a glance.

Introduction

Radar Chart, also called a spider chart, has one axis for each measure, all from the same center, and a shape that joins the value of a series on each axis. Use it to compare a few things across the same set of measures, such as the strengths of two products or the skills of a team, where the shape shows the profile at a glance.

  • It is drawn as SVG from your data, with no charting library to install, and scales to the width it is given, up to size.
  • Rings at round numbers, polygon or round, with their values along the first axis. All the axes share one scale, set from the data or with minValue and maxValue.
  • Pointing anywhere finds the nearest axis, marks it, and shows the values of every series on it, with a dot on each shape. It works from anywhere around the chart, not only on the axis line.
  • The legend hides and shows series, and pointing at a name lights its shape up and dims the others.
  • Colors come from the theme in light and dark, and the shapes open out from the center as they appear, and not for people who prefer reduced motion.
  • The SVG is hidden from screen readers, and the same data is there as a table, under the name you give with aria-label.

A radar chart needs at least three axes, and works best with five to eight and two or three series. The order of the axes changes the shape, so put related measures next to each other. It is a Client Component, so functions such as valueFormatter must be defined in a client file. Each row is an object with the name of the axis under the key you give as index, and a number for each series.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add tailwind-variants tailwind-merge clsx

# pnpm
pnpm add tailwind-variants tailwind-merge clsx

# npm
npm install tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports. It uses the chart colors and ticks of Area Chart, the geometry of Pie Chart, and the radar-chart animation from globals.css.

1. Add the shared chart parts

The chart colors --chart-1 to --chart-5 in your theme, and these files.

src/types/area-chart-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for AreaChart. The chart itself is an SVG, drawn from the numbers in
// area-chart.tsx; these are the parts around it and inside it that are plain
// HTML or take their color from the theme.
export const areaChartStyles = tv({
  slots: {
    root: "flex w-full flex-col gap-3",
    plot: "relative w-full touch-pan-y",
    svg: "block overflow-visible select-none",
    axisText: "fill-muted-fg text-xs tabular-nums",
    gridLine: "stroke-border",
    cursor: "stroke-muted-fg",
    legend: "flex flex-wrap items-center gap-x-2 gap-y-1 text-sm",
    legendItem:
      "inline-flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-fg outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring aria-[pressed=false]:text-muted-fg aria-[pressed=false]:line-through",
    swatch: "size-2.5 shrink-0 rounded-[3px] transition-opacity",
    tooltip:
      "pointer-events-none absolute z-10 min-w-36 rounded-lg border bg-card px-3 py-2 text-xs text-card-fg shadow-lg",
    tooltipTitle: "mb-1.5 font-medium",
    tooltipRow: "flex items-center gap-2",
    tooltipLabel: "text-muted-fg",
    tooltipValue: "ml-auto pl-4 font-medium tabular-nums",
    live: "pointer-events-none absolute top-0 right-3 inline-flex items-center gap-1.5 rounded-full border bg-card px-2 py-0.5 text-xs font-medium text-muted-fg",
    liveDot: "size-1.5 rounded-full bg-success motion-safe:animate-pulse",
    empty: "flex items-center justify-center text-sm text-muted-fg",
  },
  variants: {
    legendPosition: {
      top: { root: "flex-col-reverse" },
      bottom: { root: "flex-col" },
    },
  },
  defaultVariants: { legendPosition: "bottom" },
});

/** The colors a series has when it is given none, in order, then again. */
export const areaChartColors = [
  "var(--chart-1)",
  "var(--chart-2)",
  "var(--chart-3)",
  "var(--chart-4)",
  "var(--chart-5)",
] as const;
src/types/area-chart-utils.tsShow code
// The math behind AreaChart: nice axis ticks, and the paths of a line through
// points as a straight line, a smooth curve that does not overshoot, or steps.
// It knows nothing about React.

export type AreaCurve = "linear" | "monotone" | "step";

export interface Point {
  x: number;
  y: number;
}

/** One piece of a path, with where it starts so it can be walked backwards. */
type Segment =
  | { type: "L"; from: Point; to: Point }
  | { type: "C"; from: Point; c1: Point; c2: Point; to: Point };

const round = (n: number) => Math.round(n * 100) / 100;
const pt = (p: Point) => `${round(p.x)} ${round(p.y)}`;

function niceNumber(range: number, isRound: boolean) {
  const exponent = Math.floor(Math.log10(range));
  const fraction = range / 10 ** exponent;
  let nice: number;
  if (isRound) {
    nice = fraction < 1.5 ? 1 : fraction < 3 ? 2 : fraction < 7 ? 5 : 10;
  } else {
    nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
  }
  return nice * 10 ** exponent;
}

/**
 * Round numbers to put on an axis, from at or below `min` to at or above
 * `max`, about `count` of them.
 */
export function niceTicks(min: number, max: number, count = 5): number[] {
  if (min === max) max = min + 1;
  const step = niceNumber((max - min) / Math.max(count - 1, 1), true);
  const start = Math.floor(min / step) * step;
  const end = Math.ceil(max / step) * step;
  const ticks: number[] = [];
  // Rounding each step keeps 0.1 + 0.2 from becoming 0.30000000000000004.
  for (let value = start; value <= end + step / 2; value += step) {
    ticks.push(Number(value.toPrecision(12)));
  }
  return ticks;
}

function monotoneTangents(points: Point[]) {
  const n = points.length;
  const slopes: number[] = [];
  for (let i = 0; i < n - 1; i++) {
    const dx = points[i + 1].x - points[i].x;
    slopes.push(dx === 0 ? 0 : (points[i + 1].y - points[i].y) / dx);
  }
  const tangents: number[] = new Array(n);
  tangents[0] = slopes[0];
  tangents[n - 1] = slopes[n - 2];
  for (let i = 1; i < n - 1; i++) {
    tangents[i] =
      slopes[i - 1] * slopes[i] <= 0 ? 0 : (slopes[i - 1] + slopes[i]) / 2;
  }
  // Keep each tangent small enough that the curve does not go past its points.
  for (let i = 0; i < n - 1; i++) {
    if (slopes[i] === 0) {
      tangents[i] = 0;
      tangents[i + 1] = 0;
      continue;
    }
    const a = tangents[i] / slopes[i];
    const b = tangents[i + 1] / slopes[i];
    const h = a * a + b * b;
    if (h > 9) {
      const t = 3 / Math.sqrt(h);
      tangents[i] = t * a * slopes[i];
      tangents[i + 1] = t * b * slopes[i];
    }
  }
  return tangents;
}

function segments(points: Point[], curve: AreaCurve): Segment[] {
  const out: Segment[] = [];
  if (curve === "monotone" && points.length > 2) {
    const tangents = monotoneTangents(points);
    for (let i = 0; i < points.length - 1; i++) {
      const from = points[i];
      const to = points[i + 1];
      const third = (to.x - from.x) / 3;
      out.push({
        type: "C",
        from,
        c1: { x: from.x + third, y: from.y + tangents[i] * third },
        c2: { x: to.x - third, y: to.y - tangents[i + 1] * third },
        to,
      });
    }
    return out;
  }
  for (let i = 0; i < points.length - 1; i++) {
    const from = points[i];
    const to = points[i + 1];
    if (curve === "step") {
      const middle = (from.x + to.x) / 2;
      const a = { x: middle, y: from.y };
      const b = { x: middle, y: to.y };
      out.push(
        { type: "L", from, to: a },
        { type: "L", from: a, to: b },
        { type: "L", from: b, to },
      );
    } else {
      out.push({ type: "L", from, to });
    }
  }
  return out;
}

const forward = (list: Segment[]) =>
  list
    .map((s) =>
      s.type === "L" ? `L${pt(s.to)}` : `C${pt(s.c1)} ${pt(s.c2)} ${pt(s.to)}`,
    )
    .join("");

// The same pieces walked from the end to the start.
const backward = (list: Segment[]) =>
  [...list]
    .reverse()
    .map((s) =>
      s.type === "L"
        ? `L${pt(s.from)}`
        : `C${pt(s.c2)} ${pt(s.c1)} ${pt(s.from)}`,
    )
    .join("");

/** The path of a line through `points`. */
export function linePath(points: Point[], curve: AreaCurve): string {
  if (points.length === 0) return "";
  if (points.length === 1) return `M${pt(points[0])}`;
  return `M${pt(points[0])}${forward(segments(points, curve))}`;
}

/**
 * The path of the shape between a line through `top` and one through `bottom`:
 * along the top, down at the end, back along the bottom, and closed. Both lines
 * are drawn with the same curve, so a stacked area sits exactly on the one
 * under it.
 */
export function areaPath(
  top: Point[],
  bottom: Point[],
  curve: AreaCurve,
): string {
  if (top.length === 0) return "";
  const last = bottom[bottom.length - 1];
  if (top.length === 1) {
    return `M${pt(top[0])}L${pt(last)}Z`;
  }
  return `M${pt(top[0])}${forward(segments(top, curve))}L${pt(last)}${backward(
    segments(bottom, curve),
  )}Z`;
}
src/types/pie-chart-utils.tsShow code
// The geometry of PieChart: where a point is at an angle on a circle, and the
// path of a slice. Angles are in degrees, 0 at the top and growing clockwise.
// It knows nothing about React.

const RAD = Math.PI / 180;
const round = (n: number) => Math.round(n * 100) / 100;

/** The point at `angle` degrees on the circle of `radius` around (`cx`, `cy`). */
export function polar(cx: number, cy: number, radius: number, angle: number) {
  const a = (angle - 90) * RAD;
  return { x: cx + radius * Math.cos(a), y: cy + radius * Math.sin(a) };
}

/**
 * The path of a slice from `start` to `end` degrees, between the circles of
 * `inner` and `outer` radius. With an inner radius of 0 it is a wedge that
 * comes to the center. A slice of the whole circle is drawn as two halves,
 * because one arc cannot start and end at the same point.
 */
export function slicePath(
  cx: number,
  cy: number,
  inner: number,
  outer: number,
  start: number,
  end: number,
): string {
  if (end - start >= 359.99) {
    const half = start + 180;
    const ring = `${arc(cx, cy, outer, start, half)}${arc(cx, cy, outer, half, start + 360, false)}`;
    if (inner <= 0) return `${ring}Z`;
    return `${ring}Z${arc(cx, cy, inner, start, half, true, true)}${arc(cx, cy, inner, half, start + 360, false, true)}Z`;
  }
  const large = end - start > 180 ? 1 : 0;
  const o0 = polar(cx, cy, outer, start);
  const o1 = polar(cx, cy, outer, end);
  const outerArc = `M${round(o0.x)} ${round(o0.y)}A${round(outer)} ${round(outer)} 0 ${large} 1 ${round(o1.x)} ${round(o1.y)}`;
  if (inner <= 0) return `${outerArc}L${round(cx)} ${round(cy)}Z`;
  const i1 = polar(cx, cy, inner, end);
  const i0 = polar(cx, cy, inner, start);
  return `${outerArc}L${round(i1.x)} ${round(i1.y)}A${round(inner)} ${round(inner)} 0 ${large} 0 ${round(i0.x)} ${round(i0.y)}Z`;
}

function arc(
  cx: number,
  cy: number,
  radius: number,
  from: number,
  to: number,
  move = true,
  reverse = false,
) {
  const a = polar(cx, cy, radius, reverse ? to : from);
  const b = polar(cx, cy, radius, reverse ? from : to);
  return `${move ? `M${round(a.x)} ${round(a.y)}` : ""}A${round(radius)} ${round(radius)} 0 0 ${reverse ? 0 : 1} ${round(b.x)} ${round(b.y)}`;
}

export const toDegrees = (radians: number) => radians / RAD;

/**
 * The path of an arc of the circle of `radius` from `start` to `end` degrees,
 * for drawing with a stroke rather than a fill. An arc of the whole circle is
 * drawn as two halves, because one arc cannot start and end at the same point.
 */
export function arcPath(
  cx: number,
  cy: number,
  radius: number,
  start: number,
  end: number,
): string {
  const f = (n: number) => Math.round(n * 100) / 100;
  if (end - start >= 359.99) {
    const a = polar(cx, cy, radius, start);
    const b = polar(cx, cy, radius, start + 180);
    return `M${f(a.x)} ${f(a.y)}A${f(radius)} ${f(radius)} 0 0 1 ${f(b.x)} ${f(b.y)}A${f(radius)} ${f(radius)} 0 0 1 ${f(a.x)} ${f(a.y)}`;
  }
  const from = polar(cx, cy, radius, start);
  const to = polar(cx, cy, radius, end);
  const large = end - start > 180 ? 1 : 0;
  return `M${f(from.x)} ${f(from.y)}A${f(radius)} ${f(radius)} 0 ${large} 1 ${f(to.x)} ${f(to.y)}`;
}

2. Add the styles

src/types/radar-chart-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for RadarChart. The chart is SVG in a fixed coordinate space that
// scales to the width it is given; these are the parts around it and the text
// inside it that take their color from the theme. They match the other charts.
export const radarChartStyles = tv({
  slots: {
    root: "flex w-full flex-col items-center gap-3",
    plot: "relative w-full",
    svg: "block h-auto w-full overflow-visible select-none",
    gridLine: "fill-none stroke-border",
    axisLine: "stroke-border",
    activeAxis: "stroke-muted-fg",
    axisText: "fill-fg text-xs",
    tickText: "fill-muted-fg text-[10px] tabular-nums",
    area: "transition-opacity duration-200 motion-reduce:transition-none",
    legend: "flex flex-wrap justify-center gap-x-2 gap-y-1 text-sm",
    legendItem:
      "inline-flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-fg outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring aria-[pressed=false]:text-muted-fg aria-[pressed=false]:line-through",
    swatch: "size-2.5 shrink-0 rounded-[3px] transition-opacity",
    tooltip:
      "pointer-events-none absolute z-10 min-w-36 rounded-lg border bg-card px-3 py-2 text-xs text-card-fg shadow-lg",
    tooltipTitle: "mb-1.5 font-medium",
    tooltipRow: "flex items-center gap-2",
    tooltipLabel: "text-muted-fg",
    tooltipValue: "ml-auto pl-4 font-medium tabular-nums",
    empty: "flex items-center justify-center text-center text-sm text-muted-fg",
  },
  variants: {
    legendPosition: {
      top: { root: "flex-col-reverse" },
      bottom: { root: "flex-col" },
    },
  },
  defaultVariants: { legendPosition: "bottom" },
});

3. Add the Radar Chart file

src/components/ui/radar-chart/radar-chart.tsxShow code
"use client";

import { type PointerEvent, useMemo, useRef, useState } from "react";
import { cn } from "@/lib/cn";
import { areaChartColors } from "@/types/area-chart-styles";
import { niceTicks } from "@/types/area-chart-utils";
import { polar } from "@/types/pie-chart-utils";
import { radarChartStyles } from "@/types/radar-chart-styles";

export interface RadarChartSeries {
  /** The key in each row of `data` that holds this series' numbers. */
  key: string;
  /** What it is called in the legend and the tooltip. Defaults to `key`. */
  label?: string;
  /** Any CSS color, such as `var(--chart-2)` or `#3b82f6`. Defaults to the next of the theme's chart colors. */
  color?: string;
}

export interface RadarChartProps<T extends Record<string, unknown>> {
  /** One row per axis, the spokes of the chart: `{ skill: "Speed", alice: 82, bob: 64 }`. Three or more. */
  data: T[];
  /** The key of the value that names each axis, such as `skill`. */
  index: keyof T & string;
  /** The shapes to draw, one per key of the rows that holds numbers. */
  series: RadarChartSeries[];
  /** The rings behind the shapes: `polygon` follows the axes, `circle` is round, `none` leaves them out. Defaults to `polygon`. */
  grid?: "polygon" | "circle" | "none";
  /** The lines from the center to each axis. Defaults to `true`. */
  showAxisLines?: boolean;
  /** The numbers of the rings, along the first axis. Defaults to `true`. */
  showValueAxis?: boolean;
  /**
   * The fill of each shape: `solid` is a light tint, `none` leaves only the
   * outline. Defaults to `solid`.
   */
  fill?: "solid" | "none";
  /** A dot at each corner of the shapes. Defaults to `false`. */
  showDots?: boolean;
  /** The thickness of the outlines in pixels. Defaults to 2. */
  strokeWidth?: number;
  /** The card that follows the pointer and shows the values of the axis nearest to it. Defaults to `true`. */
  showTooltip?: boolean;
  /** The list of series, which also hides and shows them. Defaults to `true` when there is more than one. */
  showLegend?: boolean;
  legendPosition?: "top" | "bottom";
  /** Where the first axis points, in degrees clockwise from the top. Defaults to 0. */
  startAngle?: number;
  /** How many numbers the scale has, the center and the rings, about. Defaults to 5. */
  tickCount?: number;
  /** The number at the center. Defaults to 0, or lower if the data is. */
  minValue?: number;
  /** The number at the outer ring. Defaults to a round number above the data. */
  maxValue?: number;
  /** Where a number is shown, on the rings and in the tooltip: `(v) => v + "%"`. */
  valueFormatter?: (value: number) => string;
  /** Where the name of an axis is shown. */
  indexFormatter?: (value: string) => string;
  /** How wide the chart is at most, in pixels. It gets narrower when its parent is. Defaults to 420. */
  size?: number;
  /** Names the chart for screen readers. A table of the data is there too. */
  "aria-label": string;
  className?: string;
}

type Row = Record<string, unknown>;

// The drawing is in a space of W by H units, whatever size it is shown at.
// There is room around the rings for the names of the axes.
const W = 400;
const H = 340;
const CX = W / 2;
const CY = H / 2;
const RADIUS = 115;

const toNumber = (value: unknown) => {
  const n = Number(value);
  return Number.isFinite(n) ? n : 0;
};

const defaultValueFormatter = (value: number) =>
  new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(value);

const shorten = (text: string, chars: number) =>
  text.length > chars ? `${text.slice(0, Math.max(chars - 1, 1))}…` : text;

const points = (list: { x: number; y: number }[]) =>
  list.map(
    (p) => `${Math.round(p.x * 100) / 100} ${Math.round(p.y * 100) / 100}`,
  );

const polygon = (list: { x: number; y: number }[]) =>
  `M${points(list).join("L")}Z`;

/**
 * A radar chart, also called a spider chart: one axis for each category, all
 * from the same center, and a shape joining the value of a series on each
 * axis. Use it to compare a few things across the same set of measures, such
 * as the strengths of two products or the skills of a team, where the shape
 * shows the profile at a glance.
 *
 * It is drawn as SVG from your data, with no charting library, and scales to
 * the width it is given. Pointing anywhere shows the values of the nearest
 * axis, the legend hides and shows series, colors follow the theme in light and
 * dark, and screen readers get the data as a table.
 *
 * It needs at least three axes. All the axes share one scale, so it suits
 * measures that can be compared, such as scores out of 100.
 *
 * @example
 * <RadarChart
 *   aria-label="Skills of two engineers"
 *   data={[{ skill: "Speed", alice: 82, bob: 64 }, ...]}
 *   index="skill"
 *   series={[{ key: "alice", label: "Alice" }, { key: "bob", label: "Bob" }]}
 * />
 */
export function RadarChart<T extends Row>({
  data,
  index,
  series,
  grid = "polygon",
  showAxisLines = true,
  showValueAxis = true,
  fill = "solid",
  showDots = false,
  strokeWidth = 2,
  showTooltip = true,
  showLegend,
  legendPosition,
  startAngle = 0,
  tickCount = 5,
  minValue,
  maxValue,
  valueFormatter = defaultValueFormatter,
  indexFormatter = (name) => name,
  size = 420,
  "aria-label": ariaLabel,
  className,
}: RadarChartProps<T>) {
  const styles = radarChartStyles({ legendPosition });
  const svg = useRef<SVGSVGElement>(null);
  const [hidden, setHidden] = useState<string[]>([]);
  const [focused, setFocused] = useState<string | null>(null);
  const [pointer, setPointer] = useState<{
    x: number;
    y: number;
    axis: number;
  } | null>(null);
  const count = data.length;
  const step = count > 0 ? 360 / count : 0;

  const all = useMemo(
    () =>
      series.map((s, i) => ({
        key: s.key,
        label: s.label ?? s.key,
        color: s.color ?? areaChartColors[i % areaChartColors.length],
      })),
    [series],
  );
  const visible = all.filter((s) => !hidden.includes(s.key));
  const hasLegend = showLegend ?? all.length > 1;

  const layers = useMemo(
    () =>
      visible.map((s) => ({
        ...s,
        values: data.map((row) => toNumber(row[s.key])),
      })),
    [visible, data],
  );

  // The rings: round numbers from the center out.
  const ticks = useMemo(() => {
    let low = 0;
    let high = 0;
    for (const layer of layers) {
      for (const v of layer.values) {
        low = Math.min(low, v);
        high = Math.max(high, v);
      }
    }
    const lowest = minValue ?? low;
    const highest = maxValue ?? high;
    return niceTicks(
      lowest,
      highest === lowest ? lowest + 1 : highest,
      tickCount,
    );
  }, [layers, minValue, maxValue, tickCount]);
  const vMin = minValue ?? ticks[0];
  const vMax = maxValue ?? ticks[ticks.length - 1];

  const radiusOf = (v: number) =>
    Math.min(Math.max((v - vMin) / (vMax - vMin || 1), 0), 1) * RADIUS;
  const angleOf = (i: number) => startAngle + i * step;
  const at = (i: number, r: number) => polar(CX, CY, r, angleOf(i));

  function moveTo(event: PointerEvent<SVGSVGElement>) {
    if (!showTooltip || count === 0 || !svg.current) return;
    const box = svg.current.getBoundingClientRect();
    const center = {
      x: box.left + (box.width * CX) / W,
      y: box.top + (box.height * CY) / H,
    };
    const angle =
      (Math.atan2(event.clientX - center.x, center.y - event.clientY) * 180) /
      Math.PI;
    const turn = (((angle - startAngle) % 360) + 360) % 360;
    const axis = Math.round(turn / step) % count;
    const wrap = event.currentTarget.parentElement?.getBoundingClientRect();
    if (!wrap) return;
    setPointer({
      x: event.clientX - wrap.left,
      y: event.clientY - wrap.top,
      axis,
    });
  }

  function toggle(key: string) {
    setHidden((current) =>
      current.includes(key)
        ? current.filter((k) => k !== key)
        : visible.length > 1
          ? [...current, key]
          : current,
    );
  }

  const names = data.map((row) => indexFormatter(String(row[index] ?? "")));
  const flip =
    pointer !== null && pointer.x > (svg.current?.clientWidth ?? 0) / 2;
  const valid = count >= 3;

  return (
    <figure
      aria-label={ariaLabel}
      className={cn(styles.root(), "m-0", className)}
    >
      {valid ? (
        <div className={styles.plot()} style={{ maxWidth: size }}>
          <svg
            ref={svg}
            viewBox={`0 0 ${W} ${H}`}
            aria-hidden="true"
            className={styles.svg()}
            onPointerMove={moveTo}
            onPointerDown={moveTo}
            onPointerLeave={() => setPointer(null)}
          >
            {grid === "none"
              ? null
              : ticks.slice(1).map((t) => {
                  const r = radiusOf(t);
                  return grid === "circle" ? (
                    <circle
                      key={t}
                      className={styles.gridLine()}
                      cx={CX}
                      cy={CY}
                      r={r}
                    />
                  ) : (
                    <path
                      key={t}
                      className={styles.gridLine()}
                      d={polygon(data.map((_, i) => at(i, r)))}
                    />
                  );
                })}

            {showAxisLines
              ? data.map((_, i) => {
                  const end = at(i, RADIUS);
                  return (
                    <line
                      // biome-ignore lint/suspicious/noArrayIndexKey: the axes are the positions
                      key={i}
                      className={
                        pointer?.axis === i
                          ? styles.activeAxis()
                          : styles.axisLine()
                      }
                      x1={CX}
                      y1={CY}
                      x2={end.x}
                      y2={end.y}
                    />
                  );
                })
              : null}

            <g
              className="radar-chart-in"
              style={{ transformOrigin: `${CX}px ${CY}px` }}
            >
              {layers.map((layer) => {
                const corners = layer.values.map((v, i) => at(i, radiusOf(v)));
                const dim = focused !== null && focused !== layer.key;
                return (
                  <g
                    key={layer.key}
                    className={styles.area()}
                    style={{ opacity: dim ? 0.25 : 1 }}
                  >
                    <path
                      d={polygon(corners)}
                      fill={fill === "solid" ? layer.color : "none"}
                      fillOpacity={fill === "solid" ? 0.22 : undefined}
                      stroke={layer.color}
                      strokeWidth={strokeWidth}
                      strokeLinejoin="round"
                    />
                    {showDots
                      ? corners.map((p, i) => (
                          <circle
                            // biome-ignore lint/suspicious/noArrayIndexKey: the axes are the positions
                            key={i}
                            cx={p.x}
                            cy={p.y}
                            r={3}
                            fill={layer.color}
                          />
                        ))
                      : null}
                  </g>
                );
              })}
            </g>

            {showValueAxis
              ? ticks.slice(1).map((t) => (
                  <text
                    key={t}
                    className={styles.tickText()}
                    x={CX + 4}
                    y={CY - radiusOf(t) - 3}
                  >
                    {valueFormatter(t)}
                  </text>
                ))
              : null}

            {data.map((_, i) => {
              const p = at(i, RADIUS + 14);
              const dx = p.x - CX;
              const anchor =
                Math.abs(dx) < 4 ? "middle" : dx > 0 ? "start" : "end";
              const dy = p.y - CY;
              return (
                <text
                  // biome-ignore lint/suspicious/noArrayIndexKey: the axes are the positions
                  key={i}
                  className={styles.axisText()}
                  x={p.x}
                  y={p.y}
                  textAnchor={anchor}
                  dominantBaseline={
                    Math.abs(dy) < 4 ? "central" : dy > 0 ? "hanging" : "auto"
                  }
                  fontWeight={pointer?.axis === i ? 600 : 400}
                >
                  {shorten(names[i], 14)}
                </text>
              );
            })}

            {pointer !== null
              ? layers.map((layer) => {
                  const p = at(
                    pointer.axis,
                    radiusOf(layer.values[pointer.axis]),
                  );
                  return (
                    <circle
                      key={layer.key}
                      cx={p.x}
                      cy={p.y}
                      r={4.5}
                      fill="var(--card)"
                      stroke={layer.color}
                      strokeWidth={2}
                    />
                  );
                })
              : null}
          </svg>

          {showTooltip && pointer !== null ? (
            <div
              className={styles.tooltip()}
              style={{
                top: pointer.y,
                left: pointer.x,
                transform: `translate(${flip ? "calc(-100% - 14px)" : "14px"}, -50%)`,
              }}
            >
              <p className={cn(styles.tooltipTitle(), "m-0")}>
                {names[pointer.axis]}
              </p>
              <div className="flex flex-col gap-1">
                {layers.map((layer) => (
                  <div key={layer.key} className={styles.tooltipRow()}>
                    <span
                      aria-hidden="true"
                      className={styles.swatch()}
                      style={{ background: layer.color }}
                    />
                    <span className={styles.tooltipLabel()}>{layer.label}</span>
                    <span className={styles.tooltipValue()}>
                      {valueFormatter(layer.values[pointer.axis])}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          ) : null}
        </div>
      ) : (
        <div className={styles.empty()} style={{ height: 140 }}>
          {count === 0 ? "No data" : "A radar chart needs at least three axes"}
        </div>
      )}

      {hasLegend ? (
        <div className={styles.legend()}>
          {all.map((s) => {
            const shown = !hidden.includes(s.key);
            return (
              <button
                key={s.key}
                type="button"
                aria-pressed={shown}
                onClick={() => toggle(s.key)}
                onPointerEnter={() => shown && setFocused(s.key)}
                onPointerLeave={() => setFocused(null)}
                onFocus={() => shown && setFocused(s.key)}
                onBlur={() => setFocused(null)}
                className={styles.legendItem()}
              >
                <span
                  aria-hidden="true"
                  className={cn(styles.swatch(), !shown && "opacity-40")}
                  style={{ background: s.color }}
                />
                {s.label}
              </button>
            );
          })}
        </div>
      ) : null}

      <table className="sr-only">
        <caption>{ariaLabel}</caption>
        <thead>
          <tr>
            <th scope="col">{index}</th>
            {all.map((s) => (
              <th key={s.key} scope="col">
                {s.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.map((row, i) => (
            // biome-ignore lint/suspicious/noArrayIndexKey: rows have no id of their own
            <tr key={i}>
              <th scope="row">{names[i]}</th>
              {all.map((s) => (
                <td key={s.key}>{valueFormatter(toNumber(row[s.key]))}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </figure>
  );
}

4. Use it

import { RadarChart } from "@/components/ui/radar-chart/radar-chart";

Anatomy

An SVG with a tooltip over it, and a legend under it.

<RadarChart
  aria-label="Skills of two engineers"
  data={[{ skill: "Speed", alice: 82, bob: 64 }, ...]}
  index="skill"
  series={[
    { key: "alice", label: "Alice" },
    { key: "bob", label: "Bob" },
  ]}
/>
PartRendered asNotes
Axessvg line, textOne from the center for each row, with its name at the end. Three or more.
Ringssvg pathThe grid behind the shapes, at round numbers, with their values along the first axis.
Shapesvg pathOne per series: a polygon through its value on each axis, filled with a light tint.
TooltipdivA card that follows the pointer with the values of the axis nearest to it, and a dot on each shape.
LegendbuttonOne button per series. Pressing it hides or shows the shape, and pointing at it lights the shape up.
Data tabletable, sr-onlyThe same data as a table for screen readers. The SVG is hidden from them.

Examples

Usage

Move the pointer around the chart to see the values of the nearest axis.

Skills of Alice
skillAlice
Speed82
Design58
Testing76
Docs63
Teamwork90
Security48

Multiple series

Add a series for each key. With more than one, the legend shows: point at a name to light its shape up, or press it to hide it.

Skills of three engineers
skillAliceBobCarol
Speed826471
Design588874
Testing765290
Docs637055
Teamwork906680
Security486068

Grid

The rings behind the shapes follow the axes (polygon), are round (circle), or are left out.

polygon

Skills of two engineers, polygon grid
skillAliceBob
Speed8264
Design5888
Testing7652
Docs6370
Teamwork9066
Security4860

circle

Skills of two engineers, circle grid
skillAliceBob
Speed8264
Design5888
Testing7652
Docs6370
Teamwork9066
Security4860

none

Skills of two engineers, none grid
skillAliceBob
Speed8264
Design5888
Testing7652
Docs6370
Teamwork9066
Security4860

Outline, dots and thickness

fill="none" leaves only the outline, which keeps several overlapping shapes readable. showDots marks each corner, and strokeWidth sets the thickness of the outline.

Outline only, with dots

Skills, outline with dots
skillAliceBob
Speed8264
Design5888
Testing7652
Docs6370
Teamwork9066
Security4860

Thick outline

Skills, thick outline
skillAliceBob
Speed8264
Design5888
Testing7652
Docs6370
Teamwork9066
Security4860

Range and rings

Fix the center and the outer ring with minValue and maxValue, for scores out of 100 for example, and choose how many rings there are with tickCount.

Product comparison out of 100
metricProLite
Performance9270
Reliability8882
Price5590
Support8560
Ease of use7288

Start angle

startAngle turns the chart: where the first axis points, in degrees clockwise from the top.

Product comparison, turned
metricPro
Performance92
Reliability88
Price55
Support85
Ease of use72

Formatting values

valueFormatter writes the numbers on the rings and in the tooltip, and indexFormatter the names of the axes.

Product scores as percentages
metricProLite
PERFORMANCE92%70%
RELIABILITY88%82%
PRICE55%90%
SUPPORT85%60%
EASE OF USE72%88%

Too few axes

With fewer than three rows there is no shape to draw, and it says so.

A radar chart needs at least three axes
Only two axes
metricPro
Performance92
Reliability88

No data

With no rows it says so instead of drawing empty rings.

No data
No scores yet
metricPro

Component API

RadarChart takes the props below, and each item of series takes the second table.

PropTypeDefault
dataRecord<string, unknown>[]-
indexstring-
seriesRadarChartSeries[]-
aria-labelstring-
grid"polygon" | "circle" | "none""polygon"
showAxisLinesbooleantrue
showValueAxisbooleantrue
fill"solid" | "none""solid"
showDotsbooleanfalse
strokeWidthnumber (px)2
showTooltipbooleantrue
showLegendbooleantrue if more than one series
legendPosition"top" | "bottom""bottom"
startAnglenumber (degrees)0
tickCountnumber5
minValuenumber0, or lower if the data is
maxValuenumbera round number above the data
valueFormatter(value: number) => stringnumber with grouping
indexFormatter(value: string) => stringthe value
sizenumber (px)420
classNamestring-

RadarChartSeries

PropTypeDefault
keystring-
labelstringkey
colorstringthe next --chart-N