Menu

Components

Line Chart

Lines that follow numbers over time: how something changes, and how several things compare.

Introduction

Line Chart draws one or more series of numbers as lines. Use it for how something changes over time, when what matters is the path of each line and how they compare: response time by region, a price against its forecast.

  • 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. Lines can be thin or thick, solid or dashed, with or without dots.
  • A row with no number leaves a gap in the line, or the line is drawn across it with connectNulls. Hovering shows a dot on each line and a card with the values, and a dash for a missing number.
  • The legend lists the lines and hides or shows each one. Colors come from the theme in light and dark, and the chart draws in from the left, and not for people who prefer reduced motion.
  • isLive makes it a live chart that slides along as new rows arrive.
  • The SVG is hidden from screen readers, and the same data is there as a table, under the name you give with aria-label.

Line Chart is AreaChart without the area under the line, so it takes the same props (except fill and isStacked) and shares its files. It is a Client Component, so functions such as valueFormatter must be defined in a client file. 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

Line Chart is built on Area Chart: copy its files as described on its page, then add this one.

1. Add Area Chart

Its component, its styles and math, the chart colors of the theme, and the animations in globals.css.

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

2. Add the Line Chart file

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

import {
  AreaChart,
  type AreaChartProps,
  type AreaChartSeries,
} from "@/components/ui/area-chart/area-chart";

export type LineChartSeries = AreaChartSeries;

/** The props of `AreaChart`, less the ones about the area under the line: `fill` and `isStacked`. */
export type LineChartProps<T extends Record<string, unknown>> = Omit<
  AreaChartProps<T>,
  "fill" | "isStacked"
>;

/**
 * A line chart: one or more series of numbers as lines. Use it for how
 * something changes over time, when what matters is the path of each line and
 * how they compare, such as response time per region or a price against a
 * forecast.
 *
 * It is `AreaChart` with the area under the line left out, so it takes the
 * same props and behaves the same: SVG with no charting library, as wide as its
 * parent, a tooltip and a legend that hides series, colors from the theme, a
 * table for screen readers, and `isLive` for data that keeps coming in. It adds
 * nothing else to load.
 *
 * A row with no number for a series leaves a gap in its line, or is drawn
 * across with `connectNulls`. A series can be dashed with `isDashed`.
 *
 * @example
 * <LineChart
 *   aria-label="Response time by region"
 *   data={[{ hour: "00", eu: 120, us: 180 }, { hour: "01", eu: 110, us: 175 }]}
 *   index="hour"
 *   series={[{ key: "eu", label: "Europe" }, { key: "us", label: "US" }]}
 * />
 */
export function LineChart<T extends Record<string, unknown>>(
  props: LineChartProps<T>,
) {
  return <AreaChart {...props} fill="none" isStacked={false} />;
}

3. Use it

import { LineChart } from "@/components/ui/line-chart/line-chart";

Anatomy

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

<LineChart
  aria-label="Response time by region"
  data={[{ hour: "00", eu: 118, us: 176 }, ...]}
  index="hour"
  series={[
    { key: "eu", label: "Europe" },
    { key: "us", label: "US" },
  ]}
/>
PartRendered asNotes
PlotsvgThe lines, the grid and the axes, drawn from the data at the width of the parent.
LinepathOne per series. It breaks where a number is missing, unless connectNulls is set.
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, and a dot on each line.
LegendbuttonOne button per series. Pressing it hides or shows the line.
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.

Response time in Europe
hourEurope
00118 ms
03104 ms
06122 ms
09156 ms
12171 ms
15149 ms
18138 ms
21125 ms

Multiple series

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

Response time by region
hourEuropeUSAsia
00118 ms176 ms240 ms
03104 ms168 ms226 ms
06122 ms181 ms251 ms
09156 ms203 ms268 ms
12171 ms224 ms289 ms
15149 ms210 ms274 ms
18138 ms195 ms255 ms
21125 ms184 ms243 ms

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

Response time, monotone curve
hourEurope
00118
03104
06122
09156
12171
15149
18138
21125

linear

Response time, linear curve
hourEurope
00118
03104
06122
09156
12171
15149
18138
21125

step

Response time, step curve
hourEurope
00118
03104
06122
09156
12171
15149
18138
21125

Dots

showDots marks every point, which helps when there are few of them.

Response time with dots
hourEuropeUSAsia
00118 ms176 ms240 ms
03104 ms168 ms226 ms
06122 ms181 ms251 ms
09156 ms203 ms268 ms
12171 ms224 ms289 ms
15149 ms210 ms274 ms
18138 ms195 ms255 ms
21125 ms184 ms243 ms

Thickness

strokeWidth sets the thickness of every line, and a series can have its own.

Response time with thick lines
hourEuropeUSAsia
00118 ms176 ms240 ms
03104 ms168 ms226 ms
06122 ms181 ms251 ms
09156 ms203 ms268 ms
12171 ms224 ms289 ms
15149 ms210 ms274 ms
18138 ms195 ms255 ms
21125 ms184 ms243 ms

Dashed lines

isDashed tells a line from the others without another color: a forecast, a goal, an estimate.

Price, actual and forecast
monthActualForecast
Jan$120$0
Feb$132$0
Mar$128$0
Apr$145$145
May$0$152
Jun$0$160
Jul$0$171

Missing numbers

A row with null, undefined or an empty string has no number for that series. The line breaks there, and a number alone between two gaps is a dot. Set connectNulls to draw the line across instead.

A gap for each missing number

Orders per day, with gaps
dayOrders
Mon42
Tue58
Wed0
Thu64
Fri71
Sat0
Sun55

connectNulls

Orders per day, connected
dayOrders
Mon42
Tue58
Wed0
Thu64
Fri71
Sat0
Sun55

Grid and axes

The grid is horizontal by default, or vertical, both, or none. Each axis can be turned off.

Response time with a full grid
hourEuropeUSAsia
00118 ms176 ms240 ms
03104 ms168 ms226 ms
06122 ms181 ms251 ms
09156 ms203 ms268 ms
12171 ms224 ms289 ms
15149 ms210 ms274 ms
18138 ms195 ms255 ms
21125 ms184 ms243 ms

Formatting values

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

Response time by hour of the day
hourEuropeUSAsia
00:000.118 s0.176 s0.24 s
03:000.104 s0.168 s0.226 s
06:000.122 s0.181 s0.251 s
09:000.156 s0.203 s0.268 s
12:000.171 s0.224 s0.289 s
15:000.149 s0.21 s0.274 s
18:000.138 s0.195 s0.255 s
21:000.125 s0.184 s0.243 s

Colors

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

Response time in custom colors
hourEuropeUSAsia
00118 ms176 ms240 ms
03104 ms168 ms226 ms
06122 ms181 ms251 ms
09156 ms203 ms268 ms
12171 ms224 ms289 ms
15149 ms210 ms274 ms
18138 ms195 ms255 ms
21125 ms184 ms243 ms

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.

Response time on a fixed scale
hourEuropeUSAsia
00118 ms176 ms240 ms
03104 ms168 ms226 ms
06122 ms181 ms251 ms
09156 ms203 ms268 ms
12171 ms224 ms289 ms
15149 ms210 ms274 ms
18138 ms195 ms255 ms
21125 ms184 ms243 ms

Live

Set isLive for data that keeps coming in. It slides along as rows arrive, pulses on the latest value, and shows a Live badge, as in Area Chart. useLiveData adds a row on a timer. Use a straight curve for the smoothest movement, and fix minValue and maxValue so the axis does not jump.

Response time

Live
Response time, updated every second
timeEuropeUS
0s120 ms180 ms
1s136 ms190 ms
2s133 ms184 ms
3s134 ms194 ms
4s148 ms202 ms
5s151 ms194 ms
6s137 ms200 ms
7s133 ms205 ms
8s138 ms193 ms
9s127 ms196 ms
10s108 ms197 ms
11s106 ms182 ms
12s109 ms183 ms
13s96 ms183 ms
14s87 ms168 ms
15s99 ms169 ms
16s107 ms170 ms
17s101 ms157 ms
18s107 ms161 ms
19s127 ms165 ms
20s134 ms155 ms
21s129 ms164 ms
22s139 ms171 ms
23s152 ms164 ms
24s145 ms175 ms
25s134 ms184 ms
26s139 ms179 ms
27s138 ms190 ms
28s119 ms198 ms
29s107 ms191 ms

No data

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

No data
No measurements yet
hourEurope

Component API

LineChart takes the props below, and each item of series takes the second table. Everything else about AreaChart applies too.

PropTypeDefault
dataRecord<string, unknown>[]-
indexstring-
seriesLineChartSeries[]-
aria-labelstring-
curve"monotone" | "linear" | "step""monotone"
strokeWidthnumber (px)2
showDotsbooleanfalse
connectNullsbooleanfalse
grid"horizontal" | "vertical" | "both" | "none""horizontal"
showXAxisbooleantrue
showYAxisbooleantrue
showTooltipbooleantrue
showLegendbooleantrue if more than one series
legendPosition"top" | "bottom""bottom"
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
isLivebooleanfalse
liveLabelstring"Live"
liveDurationnumber (ms)the time between updates, measured
classNamestring-

LineChartSeries

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