Menu

Components

Area Chart

A line chart with the area under it filled: how a number changes over time, or how parts add up to a whole.

Introduction

Area Chart draws one or more series of numbers as lines with the area under them filled. Use it for how something changes over time, such as visitors a month, or, stacked, for how parts add up to a whole.

  • It is drawn as SVG from your data, with no charting library to install. It is as wide as its parent and redraws when that changes.
  • Three curves: smooth (monotone, which never goes past its points), straight, and steps. Three fills: a gradient, a flat tint, or none.
  • Stacked areas pile up, with the total in the tooltip. Hovering anywhere shows a card with the values at the nearest point.
  • The legend lists the series and hides or shows each one. The axes use round numbers, and the labels along the bottom thin out so they never overlap.
  • Set isLive for data that keeps coming in: it slides along as rows arrive and pulses on the latest value.
  • Colors come from the theme in light and dark. The chart draws in from the left, 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.

It is a Client Component, so functions such as valueFormatter must be defined in a client file. It does not fetch data: pass the rows in. Each row is an object with the value along the bottom, 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.

1. Add the chart colors to your theme

The series take these in order. Also add --color-chart-1 to --color-chart-5 in @theme inline to use them as Tailwind colors, and the area-chart-reveal animation from globals.css for the draw-in.

/* globals.css, in :root */
--chart-1: light-dark(oklch(0.55 0.2 260), oklch(0.72 0.15 260));
--chart-2: light-dark(oklch(0.62 0.15 185), oklch(0.75 0.13 185));
--chart-3: light-dark(oklch(0.7 0.17 60), oklch(0.8 0.16 75));
--chart-4: light-dark(oklch(0.56 0.22 305), oklch(0.72 0.17 305));
--chart-5: light-dark(oklch(0.6 0.22 10), oklch(0.72 0.17 10));

2. Add the math

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`;
}

3. Add the styles

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;

4. Add the Area Chart file

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

import {
  type PointerEvent,
  type ReactNode,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { cn } from "@/lib/cn";
import { areaChartColors, areaChartStyles } from "@/types/area-chart-styles";
import {
  type AreaCurve,
  areaPath,
  linePath,
  niceTicks,
  type Point,
} from "@/types/area-chart-utils";

export type { AreaCurve };

export interface AreaChartSeries {
  /** 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;
  /** Draw the line dashed, to tell it from the others, such as a forecast or a goal. */
  isDashed?: boolean;
  /** The thickness of this series' line in pixels. Defaults to the `strokeWidth` of the chart. */
  strokeWidth?: number;
}

export interface AreaChartProps<T extends Record<string, unknown>> {
  /** One row per point along the bottom: `{ month: "Jan", desktop: 186, mobile: 80 }`. */
  data: T[];
  /** The key of the value along the bottom, such as `month`. */
  index: keyof T & string;
  /** The areas to draw, one per key of the rows that holds numbers. */
  series: AreaChartSeries[];
  /**
   * The shape of the line between points: `monotone` is smooth and never goes
   * past its points, `linear` is straight, `step` is stairs. Defaults to
   * `monotone`.
   */
  curve?: AreaCurve;
  /** Pile the series on top of each other, so the top line is their total. */
  isStacked?: boolean;
  /**
   * The fill under the line: `gradient` fades out downward, `solid` is a flat
   * light tint, `none` leaves only the line. Defaults to `gradient`.
   */
  fill?: "gradient" | "solid" | "none";
  /** The lines behind the areas. Defaults to `horizontal`. */
  grid?: "horizontal" | "vertical" | "both" | "none";
  /** The labels along the bottom. Defaults to `true`. */
  showXAxis?: boolean;
  /** The numbers along the left. Defaults to `true`. */
  showYAxis?: boolean;
  /** The card that follows the pointer and shows the values at a point. 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";
  /** A dot on every point. Defaults to `false`. */
  showDots?: boolean;
  /** The thickness of the lines in pixels. Defaults to 2. */
  strokeWidth?: number;
  /**
   * What to do with a row that has no number for a series (`null`, `undefined`
   * or empty): leave a gap in the line (`false`, the default) or draw the line
   * across it (`true`). A stacked chart counts the missing number as 0.
   */
  connectNulls?: boolean;
  /**
   * For data that keeps coming in, such as a monitor: pass rows that change
   * (drop the oldest, add the newest) and the chart slides along by one point
   * each time, marks the latest value with a pulsing dot, and shows a "Live"
   * badge. It does not fetch anything: `useLiveData` is one way to feed it.
   */
  isLive?: boolean;
  /** The text of the badge on a live chart. Defaults to "Live". */
  liveLabel?: string;
  /**
   * How long a live chart takes to slide by one point, in milliseconds. Left
   * out, it is the time between the last updates, measured as they come, so
   * the chart moves without a stop between one point and the next.
   */
  liveDuration?: number;
  /** The height of the plot in pixels. The width is that of the parent. Defaults to 280. */
  height?: number;
  /** Where a number is shown, on the left axis and in the tooltip: `(v) => "$" + v`. */
  valueFormatter?: (value: number) => string;
  /** Where a value along the bottom is shown, on the axis and the tooltip's title. */
  indexFormatter?: (value: string) => string;
  /** About how many numbers on the left axis. Defaults to 5. */
  yTickCount?: number;
  /** The lowest number of the left axis. Defaults to 0, or lower if the data is. */
  minValue?: number;
  /** The highest number of the left axis. Defaults to a round number above the data. */
  maxValue?: number;
  /** Names the chart for screen readers. A table of the data is there too. */
  "aria-label": string;
  className?: string;
}

const FONT = 12;
const CHAR = 6.6;

type Row = Record<string, unknown>;

const hasNumber = (value: unknown) =>
  value !== null &&
  value !== undefined &&
  value !== "" &&
  Number.isFinite(Number(value));

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);

/**
 * An area chart: one or more series of numbers along a line, with the area
 * under each line filled. Use it for how something changes over time, such as
 * visitors a month, or how parts add up to a whole when it is stacked.
 *
 * It is drawn as SVG from your data, with no charting library. It is as wide as
 * its parent, shows the values in a tooltip when the pointer is over it, and
 * takes its colors from the theme, so it follows light and dark. The legend hides
 * and shows series, and screen readers get the data as a table.
 *
 * @example
 * <AreaChart
 *   aria-label="Visitors by month"
 *   data={[{ month: "Jan", desktop: 186 }, { month: "Feb", desktop: 305 }]}
 *   index="month"
 *   series={[{ key: "desktop", label: "Desktop" }]}
 * />
 */
export function AreaChart<T extends Row>({
  data,
  index,
  series,
  curve = "monotone",
  isStacked = false,
  fill = "gradient",
  grid = "horizontal",
  showXAxis = true,
  showYAxis = true,
  showTooltip = true,
  showLegend,
  legendPosition,
  showDots = false,
  strokeWidth = 2,
  connectNulls = false,
  isLive = false,
  liveLabel = "Live",
  liveDuration,
  height = 280,
  valueFormatter = defaultValueFormatter,
  indexFormatter = (value) => value,
  yTickCount = 5,
  minValue,
  maxValue,
  "aria-label": ariaLabel,
  className,
}: AreaChartProps<T>) {
  const styles = areaChartStyles({ legendPosition });
  const uid = useId().replace(/[^a-zA-Z0-9_-]/g, "");
  const plot = useRef<HTMLDivElement>(null);
  // The parts that slide along on a live chart, and the data of the last draw.
  const slideLabels = useRef<SVGGElement>(null);
  const slideAreas = useRef<SVGGElement>(null);
  const lastData = useRef(data);
  const lastAt = useRef(0);
  const pace = useRef(1000);
  const [width, setWidth] = useState(0);
  const [active, setActive] = useState<number | null>(null);
  const [hidden, setHidden] = useState<string[]>([]);

  useLayoutEffect(() => {
    const el = plot.current;
    if (!el) return;
    setWidth(el.clientWidth);
    const observer = new ResizeObserver(([entry]) =>
      setWidth(entry.contentRect.width),
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

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

  // A live chart also keeps the row that just left the window, one point to
  // the left of the plot. Without it there would be a gap at the left edge
  // while the chart slides. `tick` counts the points that have come in, so a
  // label along the bottom stays with its point as it slides.
  const [seen, setSeen] = useState(data);
  const [live, setLive] = useState<{ extra: Row | null; tick: number }>({
    extra: null,
    tick: 0,
  });
  if (seen !== data) {
    setSeen(data);
    if (isLive) {
      const shifted = seen.length === data.length && data.length > 0;
      setLive({
        extra: shifted ? seen[0] : null,
        tick: shifted ? live.tick + 1 : live.tick,
      });
    }
  }
  const extra = isLive ? live.extra : null;
  const tick = isLive ? live.tick : 0;
  const rows = extra ? [extra, ...data] : data;
  const off = extra ? 1 : 0;

  // The numbers each visible series has, and where each area starts: at zero,
  // or on top of the series under it when they are stacked.
  const layers = useMemo(() => {
    const totals = new Array<number>(rows.length).fill(0);
    return visible.map((s) => {
      const values = rows.map((row) => toNumber(row[s.key]));
      // A row with no number is a gap in the line, except in a stack, where it is 0.
      const defined = rows.map((row) => isStacked || hasNumber(row[s.key]));
      const base = [...totals];
      const top = values.map((v, i) => (isStacked ? totals[i] + v : v));
      if (isStacked) {
        for (let i = 0; i < rows.length; i++) totals[i] = top[i];
      }
      return { ...s, values, base, top, defined };
    });
  }, [visible, rows, isStacked]);

  // The left axis: round numbers from the lowest to the highest.
  const ticks = useMemo(() => {
    let low = 0;
    let high = 0;
    for (const layer of layers) {
      for (let i = 0; i < rows.length; i++) {
        low = Math.min(low, layer.top[i], layer.base[i]);
        high = Math.max(high, layer.top[i], layer.base[i]);
      }
    }
    const lowest = minValue ?? low;
    const highest = maxValue ?? high;
    return niceTicks(
      lowest,
      highest === lowest ? lowest + 1 : highest,
      yTickCount,
    );
  }, [layers, rows.length, minValue, maxValue, yTickCount]);
  const yMin = minValue ?? ticks[0];
  const yMax = maxValue ?? ticks[ticks.length - 1];

  const yLabels = ticks.map((t) => valueFormatter(t));
  const yAxisWidth = showYAxis
    ? Math.ceil(Math.max(...yLabels.map((l) => l.length)) * CHAR) + 12
    : 0;
  const margin = {
    top: 10,
    right: 12,
    bottom: showXAxis ? 30 : 10,
    left: showYAxis ? yAxisWidth : 12,
  };
  const innerW = Math.max(width - margin.left - margin.right, 0);
  const innerH = Math.max(height - margin.top - margin.bottom, 0);

  const xAt = (i: number) =>
    margin.left + (count <= 1 ? innerW / 2 : (i / (count - 1)) * innerW);
  const yAt = (v: number) =>
    margin.top + innerH - ((v - yMin) / (yMax - yMin || 1)) * innerH;
  const floor = Math.min(Math.max(0, yMin), yMax);

  // Which labels along the bottom to write, so they do not run into each other.
  const labels = rows.map((row) => indexFormatter(String(row[index] ?? "")));
  const widest = Math.max(1, ...labels.map((l) => l.length)) * CHAR + 16;
  const every = Math.max(
    1,
    Math.ceil(count / Math.max(2, Math.floor(innerW / widest))),
  );

  // A live chart has moved on by one point: start the new drawing one point to
  // the right, where the old one had it, and slide it into place. It slides at
  // the speed the points come in, and picks up from where the last slide is, so
  // the chart never stops or jumps between one point and the next.
  useLayoutEffect(() => {
    if (lastData.current === data) return;
    lastData.current = data;
    const now = performance.now();
    const gap = now - lastAt.current;
    const known = lastAt.current > 0 && gap > 30 && gap < 10000;
    lastAt.current = now;
    if (known) pace.current = pace.current * 0.5 + gap * 0.5;
    if (!isLive || count < 2 || innerW <= 0) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const step = innerW / (count - 1);
    const duration = liveDuration ?? pace.current;
    for (const el of [slideLabels.current, slideAreas.current]) {
      if (!el) continue;
      // What is left of the last slide is added to this one.
      const [last] = el.getAnimations();
      const progress = last?.effect?.getComputedTiming().progress ?? 1;
      const left = Math.min(step * (1 - progress), step);
      last?.cancel();
      el.animate(
        [
          { transform: `translateX(${step + left}px)` },
          { transform: "translateX(0)" },
        ],
        { duration: (duration * (step + left)) / step, easing: "linear" },
      );
    }
  }, [data, isLive, count, innerW, liveDuration]);

  function moveTo(event: PointerEvent<HTMLDivElement>) {
    if (!showTooltip || count === 0) return;
    const box = event.currentTarget.getBoundingClientRect();
    const x = event.clientX - box.left - margin.left;
    const i = count <= 1 ? 0 : Math.round((x / (innerW || 1)) * (count - 1));
    setActive(Math.min(Math.max(i, 0), count - 1));
  }

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

  const gradientOpacity = isStacked ? [0.6, 0.25] : [0.4, 0.03];
  const activeX = active === null ? 0 : xAt(active);
  const flip = active !== null && activeX > width / 2;

  let body: ReactNode = null;
  if (count === 0) {
    body = (
      <div className={styles.empty()} style={{ height }}>
        No data
      </div>
    );
  } else if (width > 0) {
    body = (
      <svg
        width={width}
        height={height}
        viewBox={`0 0 ${width} ${height}`}
        aria-hidden="true"
        className={styles.svg()}
      >
        <defs>
          <clipPath id={`${uid}-clip`}>
            <rect
              className="area-chart-reveal"
              x={margin.left - 2}
              y={0}
              width={innerW + margin.right + 2}
              height={height}
            />
          </clipPath>
          <clipPath id={`${uid}-lclip`}>
            <rect x={0} y={0} width={width} height={height} />
          </clipPath>
          {layers.map((layer) => (
            <linearGradient
              key={layer.key}
              id={`${uid}-${layer.key}`}
              x1="0"
              y1="0"
              x2="0"
              y2="1"
            >
              <stop
                offset="0%"
                stopColor={layer.color}
                stopOpacity={gradientOpacity[0]}
              />
              <stop
                offset="100%"
                stopColor={layer.color}
                stopOpacity={gradientOpacity[1]}
              />
            </linearGradient>
          ))}
        </defs>

        {grid === "horizontal" || grid === "both"
          ? ticks.map((t) => (
              <line
                key={t}
                className={styles.gridLine()}
                x1={margin.left}
                x2={margin.left + innerW}
                y1={yAt(t)}
                y2={yAt(t)}
                strokeDasharray="3 4"
              />
            ))
          : null}
        {grid === "vertical" || grid === "both"
          ? data.map((_, i) => (
              <line
                // biome-ignore lint/suspicious/noArrayIndexKey: the points are the positions
                key={i}
                className={styles.gridLine()}
                x1={xAt(i)}
                x2={xAt(i)}
                y1={margin.top}
                y2={margin.top + innerH}
                strokeDasharray="3 4"
              />
            ))
          : null}

        {showYAxis
          ? ticks.map((t, i) => (
              <text
                key={t}
                className={styles.axisText()}
                x={margin.left - 8}
                y={yAt(t)}
                textAnchor="end"
                dominantBaseline="central"
              >
                {yLabels[i]}
              </text>
            ))
          : null}
        {showXAxis ? (
          <g clipPath={`url(#${uid}-lclip)`}>
            <g ref={slideLabels}>
              {labels.map((label, i) => {
                const at = tick + i - off;
                if (((at % every) + every) % every !== 0) return null;
                const half = (label.length * CHAR) / 2;
                const x = xAt(i - off);
                const anchor =
                  x - half < 0 ? "start" : x + half > width ? "end" : "middle";
                return (
                  <text
                    // biome-ignore lint/suspicious/noArrayIndexKey: the labels are the positions
                    key={i}
                    className={styles.axisText()}
                    x={x}
                    y={height - margin.bottom + 8 + FONT}
                    textAnchor={anchor}
                  >
                    {label}
                  </text>
                );
              })}
            </g>
          </g>
        ) : null}

        <g clipPath={`url(#${uid}-clip)`}>
          <g ref={slideAreas}>
            {[...layers].reverse().map((layer) => {
              const top: Point[] = layer.top.map((v, i) => ({
                x: xAt(i - off),
                y: yAt(v),
              }));
              const bottom: Point[] = layer.base.map((v, i) => ({
                x: xAt(i - off),
                y: yAt(isStacked ? v : floor),
              }));
              // The stretches of the line with numbers, split at the gaps.
              const runs: { top: Point[]; bottom: Point[] }[] = [];
              let current: { top: Point[]; bottom: Point[] } | null = null;
              layer.defined.forEach((isDefined, i) => {
                if (isDefined) {
                  current ??= { top: [], bottom: [] };
                  current.top.push(top[i]);
                  current.bottom.push(bottom[i]);
                } else if (!connectNulls && current) {
                  runs.push(current);
                  current = null;
                }
              });
              if (current) runs.push(current);
              const lastAt = layer.defined.lastIndexOf(true);
              return (
                <g key={layer.key}>
                  {runs.map((run) => (
                    <g key={`${run.top[0].x}`}>
                      {run.top.length < 2 ? (
                        // One number between two gaps has no line to draw.
                        <circle
                          cx={run.top[0].x}
                          cy={run.top[0].y}
                          r={layer.strokeWidth * 1.5}
                          fill={layer.color}
                        />
                      ) : (
                        <>
                          {fill === "none" ? null : (
                            <path
                              d={areaPath(run.top, run.bottom, curve)}
                              fill={
                                fill === "gradient"
                                  ? `url(#${uid}-${layer.key})`
                                  : layer.color
                              }
                              fillOpacity={fill === "solid" ? 0.2 : 1}
                            />
                          )}
                          <path
                            d={linePath(run.top, curve)}
                            fill="none"
                            stroke={layer.color}
                            strokeWidth={layer.strokeWidth}
                            strokeDasharray={layer.isDashed ? "6 5" : undefined}
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                        </>
                      )}
                    </g>
                  ))}
                  {showDots
                    ? top.map((p, i) =>
                        layer.defined[i] ? (
                          <circle
                            // biome-ignore lint/suspicious/noArrayIndexKey: the points are the positions
                            key={i}
                            cx={p.x}
                            cy={p.y}
                            r={3}
                            fill={layer.color}
                          />
                        ) : null,
                      )
                    : null}
                  {isLive && lastAt >= 0 ? (
                    <g>
                      <circle
                        className="origin-center animate-ping [transform-box:fill-box] motion-reduce:animate-none"
                        cx={top[lastAt].x}
                        cy={top[lastAt].y}
                        r={4}
                        fill={layer.color}
                      />
                      <circle
                        cx={top[lastAt].x}
                        cy={top[lastAt].y}
                        r={4}
                        fill={layer.color}
                      />
                    </g>
                  ) : null}
                </g>
              );
            })}
          </g>
        </g>

        {active !== null ? (
          <g>
            <line
              className={styles.cursor()}
              x1={activeX}
              x2={activeX}
              y1={margin.top}
              y2={margin.top + innerH}
              strokeDasharray="3 3"
            />
            {layers.map((layer) =>
              layer.defined[active + off] ? (
                <circle
                  key={layer.key}
                  cx={activeX}
                  cy={yAt(layer.top[active + off])}
                  r={4.5}
                  fill="var(--card)"
                  stroke={layer.color}
                  strokeWidth={2}
                />
              ) : null,
            )}
          </g>
        ) : null}
      </svg>
    );
  } else {
    body = <div style={{ height }} />;
  }

  return (
    <figure
      aria-label={ariaLabel}
      className={cn(styles.root(), "m-0", className)}
    >
      <div
        ref={plot}
        className={styles.plot()}
        onPointerMove={moveTo}
        onPointerDown={moveTo}
        onPointerLeave={() => setActive(null)}
      >
        {body}
        {isLive && count > 0 ? (
          <span className={styles.live()}>
            <span aria-hidden="true" className={styles.liveDot()} />
            {liveLabel}
          </span>
        ) : null}
        {showTooltip && active !== null && count > 0 ? (
          <div
            className={styles.tooltip()}
            style={{
              top: margin.top,
              left: activeX,
              transform: `translateX(${flip ? "calc(-100% - 12px)" : "12px"})`,
            }}
          >
            <p className={cn(styles.tooltipTitle(), "m-0")}>
              {labels[active + off]}
            </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()}>
                    {layer.defined[active + off]
                      ? valueFormatter(layer.values[active + off])
                      : "—"}
                  </span>
                </div>
              ))}
              {isStacked && layers.length > 1 ? (
                <div
                  className={cn(styles.tooltipRow(), "mt-1 border-t pt-1.5")}
                >
                  <span className={styles.tooltipLabel()}>Total</span>
                  <span className={styles.tooltipValue()}>
                    {valueFormatter(
                      layers.reduce(
                        (sum, l) => sum + l.values[active + off],
                        0,
                      ),
                    )}
                  </span>
                </div>
              ) : null}
            </div>
          </div>
        ) : null}
      </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)}
                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">{labels[i + off]}</th>
              {all.map((s) => (
                <td key={s.key}>{valueFormatter(toNumber(row[s.key]))}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </figure>
  );
}

5. Use it

import { AreaChart } from "@/components/ui/area-chart/area-chart";

Anatomy

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

<AreaChart
  aria-label="Visitors by month"
  data={[{ month: "Jan", desktop: 186, mobile: 80 }, ...]}
  index="month"
  series={[
    { key: "desktop", label: "Desktop" },
    { key: "mobile", label: "Mobile" },
  ]}
/>
PartRendered asNotes
PlotsvgThe areas, the lines, the grid and the axes, drawn from the data at the width of the parent.
Area and linepathOne pair per series: a filled shape and the line along its top.
Axes and gridtext, lineRound numbers on the left, one label per point along the bottom, and the lines behind.
TooltipdivA card that follows the pointer with the values at the nearest point.
LegendbuttonOne button per series. Pressing it hides or shows the series.
Data tabletable, sr-onlyThe same data as a table for screen readers. The SVG is hidden from them.

Examples

Usage

Move the pointer over the chart to see the values.

Desktop visitors by month
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314
Jul356
Aug298

Multiple series

Add a series for each key. With more than one, the legend shows, and pressing a name hides that series.

Visitors by month and device
monthDesktopMobile
Jan18680
Feb305200
Mar237120
Apr273190
May209130
Jun314240
Jul356260
Aug298210

Stacked

isStacked piles the series on top of each other, so the top line is their total, and the tooltip adds a Total row.

Stacked visitors by month and device
monthDesktopMobileTablet
Jan1868032
Feb30520048
Mar23712041
Apr27319062
May20913055
Jun31424070
Jul35626084
Aug29821066

Curves

Monotone is smooth and never goes past the data. Linear is straight between points. Step is stairs, for values that hold until they change.

monotone

Visitors, monotone curve
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314
Jul356
Aug298

linear

Visitors, linear curve
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314
Jul356
Aug298

step

Visitors, step curve
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314
Jul356
Aug298

Fill

A gradient that fades downward, a flat tint, or no fill for lines only.

gradient

Visitors, gradient fill
monthDesktopMobile
Jan18680
Feb305200
Mar237120
Apr273190
May209130
Jun314240
Jul356260
Aug298210

solid

Visitors, solid fill
monthDesktopMobile
Jan18680
Feb305200
Mar237120
Apr273190
May209130
Jun314240
Jul356260
Aug298210

none

Visitors, none fill
monthDesktopMobile
Jan18680
Feb305200
Mar237120
Apr273190
May209130
Jun314240
Jul356260
Aug298210

Grid, axes and dots

The grid is horizontal by default, or vertical, both, or none. Each axis can be turned off, and dots mark every point.

Desktop visitors with a full grid and dots
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314
Jul356
Aug298

Formatting values

valueFormatter writes the numbers on the axis and in the tooltip, and indexFormatter the labels along the bottom.

Revenue by month
monthRevenue
Jan 2026$4,200
Feb 2026$5,800
Mar 2026$5,100
Apr 2026$7,300
May 2026$6,900
Jun 2026$9,200
Jul 2026$10,400
Aug 2026$9,800

Colors

A series takes the next chart color of the theme. Give color to choose one, any CSS color or a theme token.

Visitors in custom colors
monthDesktopMobile
Jan18680
Feb305200
Mar237120
Apr273190
May209130
Jun314240
Jul356260
Aug298210

Legend

Put the legend above the chart, or turn it off. One series has no legend unless showLegend is set.

Visitors with the legend on top
monthDesktopMobileTablet
Jan1868032
Feb30520048
Mar23712041
Apr27319062
May20913055
Jun31424070
Jul35626084
Aug29821066

Range and height

Fix the ends of the left axis with minValue and maxValue, choose how many numbers it has with yTickCount, and set the height in pixels.

Desktop visitors on a fixed scale
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314
Jul356
Aug298

Live

Set isLive for data that keeps coming in, such as a monitor. Each time the rows change (the oldest goes, a new one comes), the chart slides along by one point, marks the latest value with a pulsing dot, and shows a Live badge. It fetches nothing itself: useLiveData adds a row on a timer, and you can feed it from a socket or a request instead. It slides at the speed the rows come in, measured as they do, so it moves without a stop between points. Fix minValue and maxValue so the axis does not jump.

CPU usage

Live
CPU usage, updated every second
timeCPU
0s45%
1s58%
2s52%
3s50%
4s64%
5s66%
6s53%
7s51%
8s59%
9s50%
10s34%
11s36%
12s42%
13s30%
14s22%
15s33%
16s40%
17s32%
18s35%
19s52%
20s55%
21s48%
22s56%
23s68%
24s60%
25s50%
26s57%
27s59%
28s43%
29s35%
Live · 1.5s
CPU and memory, updated every second and a half
timeCPUMemory
0s45%60%
1s58%61%
2s52%62%
3s50%63%
4s64%64%
5s66%65%
6s53%66%
7s51%66%
8s59%66%
9s50%66%
10s34%65%
11s36%65%
12s42%64%
13s30%63%
14s22%62%
15s33%61%
16s40%60%
17s32%58%
18s35%57%
19s52%56%
20s55%55%
21s48%55%
22s56%54%
23s68%54%
24s60%54%
25s50%54%
26s57%55%
27s59%55%
28s43%56%
29s35%57%

No data

With no rows it says so instead of drawing an empty plot.

No data
No visitors yet
monthDesktop

Component API

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

PropTypeDefault
dataRecord<string, unknown>[]-
indexstring-
seriesAreaChartSeries[]-
aria-labelstring-
curve"monotone" | "linear" | "step""monotone"
isStackedbooleanfalse
fill"gradient" | "solid" | "none""gradient"
grid"horizontal" | "vertical" | "both" | "none""horizontal"
showXAxisbooleantrue
showYAxisbooleantrue
showTooltipbooleantrue
showLegendbooleantrue if more than one series
legendPosition"top" | "bottom""bottom"
showDotsbooleanfalse
strokeWidthnumber (px)2
connectNullsbooleanfalse
isLivebooleanfalse
liveLabelstring"Live"
liveDurationnumber (ms)the time between updates, measured
heightnumber (px)280
valueFormatter(value: number) => stringnumber with grouping
indexFormatter(value: string) => stringthe value
yTickCountnumber5
minValuenumber0, or lower if the data is
maxValuenumbera round number above the data
classNamestring-

AreaChartSeries

PropTypeDefault
keystring-
labelstringkey
colorstringthe next --chart-N
isDashedbooleanfalse
strokeWidthnumber (px)the chart's strokeWidth