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.
isLivemakes 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 clsxManual 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" },
]}
/>| Part | Rendered as | Notes |
|---|---|---|
| Plot | svg | The lines, the grid and the axes, drawn from the data at the width of the parent. |
| Line | path | One per series. It breaks where a number is missing, unless connectNulls is set. |
| Axes and grid | text, line | Round numbers on the left, one label per point along the bottom, and the lines behind. |
| Tooltip | div | A card that follows the pointer with the values at the nearest point, and a dot on each line. |
| Legend | button | One button per series. Pressing it hides or shows the line. |
| Data table | table, sr-only | The 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.
| hour | Europe |
|---|---|
| 00 | 118 ms |
| 03 | 104 ms |
| 06 | 122 ms |
| 09 | 156 ms |
| 12 | 171 ms |
| 15 | 149 ms |
| 18 | 138 ms |
| 21 | 125 ms |
Multiple series
Add a series for each key. With more than one, the legend shows, and pressing a name hides that line.
| hour | Europe | US | Asia |
|---|---|---|---|
| 00 | 118 ms | 176 ms | 240 ms |
| 03 | 104 ms | 168 ms | 226 ms |
| 06 | 122 ms | 181 ms | 251 ms |
| 09 | 156 ms | 203 ms | 268 ms |
| 12 | 171 ms | 224 ms | 289 ms |
| 15 | 149 ms | 210 ms | 274 ms |
| 18 | 138 ms | 195 ms | 255 ms |
| 21 | 125 ms | 184 ms | 243 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
| hour | Europe |
|---|---|
| 00 | 118 |
| 03 | 104 |
| 06 | 122 |
| 09 | 156 |
| 12 | 171 |
| 15 | 149 |
| 18 | 138 |
| 21 | 125 |
linear
| hour | Europe |
|---|---|
| 00 | 118 |
| 03 | 104 |
| 06 | 122 |
| 09 | 156 |
| 12 | 171 |
| 15 | 149 |
| 18 | 138 |
| 21 | 125 |
step
| hour | Europe |
|---|---|
| 00 | 118 |
| 03 | 104 |
| 06 | 122 |
| 09 | 156 |
| 12 | 171 |
| 15 | 149 |
| 18 | 138 |
| 21 | 125 |
Dots
showDots marks every point, which helps when there are few of them.
| hour | Europe | US | Asia |
|---|---|---|---|
| 00 | 118 ms | 176 ms | 240 ms |
| 03 | 104 ms | 168 ms | 226 ms |
| 06 | 122 ms | 181 ms | 251 ms |
| 09 | 156 ms | 203 ms | 268 ms |
| 12 | 171 ms | 224 ms | 289 ms |
| 15 | 149 ms | 210 ms | 274 ms |
| 18 | 138 ms | 195 ms | 255 ms |
| 21 | 125 ms | 184 ms | 243 ms |
Thickness
strokeWidth sets the thickness of every line, and a series can have its own.
| hour | Europe | US | Asia |
|---|---|---|---|
| 00 | 118 ms | 176 ms | 240 ms |
| 03 | 104 ms | 168 ms | 226 ms |
| 06 | 122 ms | 181 ms | 251 ms |
| 09 | 156 ms | 203 ms | 268 ms |
| 12 | 171 ms | 224 ms | 289 ms |
| 15 | 149 ms | 210 ms | 274 ms |
| 18 | 138 ms | 195 ms | 255 ms |
| 21 | 125 ms | 184 ms | 243 ms |
Dashed lines
isDashed tells a line from the others without another color: a forecast, a goal, an estimate.
| month | Actual | Forecast |
|---|---|---|
| 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
| day | Orders |
|---|---|
| Mon | 42 |
| Tue | 58 |
| Wed | 0 |
| Thu | 64 |
| Fri | 71 |
| Sat | 0 |
| Sun | 55 |
connectNulls
| day | Orders |
|---|---|
| Mon | 42 |
| Tue | 58 |
| Wed | 0 |
| Thu | 64 |
| Fri | 71 |
| Sat | 0 |
| Sun | 55 |
Grid and axes
The grid is horizontal by default, or vertical, both, or none. Each axis can be turned off.
| hour | Europe | US | Asia |
|---|---|---|---|
| 00 | 118 ms | 176 ms | 240 ms |
| 03 | 104 ms | 168 ms | 226 ms |
| 06 | 122 ms | 181 ms | 251 ms |
| 09 | 156 ms | 203 ms | 268 ms |
| 12 | 171 ms | 224 ms | 289 ms |
| 15 | 149 ms | 210 ms | 274 ms |
| 18 | 138 ms | 195 ms | 255 ms |
| 21 | 125 ms | 184 ms | 243 ms |
Formatting values
valueFormatter writes the numbers on the axis and in the tooltip, and indexFormatter the labels along the bottom.
| hour | Europe | US | Asia |
|---|---|---|---|
| 00:00 | 0.118 s | 0.176 s | 0.24 s |
| 03:00 | 0.104 s | 0.168 s | 0.226 s |
| 06:00 | 0.122 s | 0.181 s | 0.251 s |
| 09:00 | 0.156 s | 0.203 s | 0.268 s |
| 12:00 | 0.171 s | 0.224 s | 0.289 s |
| 15:00 | 0.149 s | 0.21 s | 0.274 s |
| 18:00 | 0.138 s | 0.195 s | 0.255 s |
| 21:00 | 0.125 s | 0.184 s | 0.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.
| hour | Europe | US | Asia |
|---|---|---|---|
| 00 | 118 ms | 176 ms | 240 ms |
| 03 | 104 ms | 168 ms | 226 ms |
| 06 | 122 ms | 181 ms | 251 ms |
| 09 | 156 ms | 203 ms | 268 ms |
| 12 | 171 ms | 224 ms | 289 ms |
| 15 | 149 ms | 210 ms | 274 ms |
| 18 | 138 ms | 195 ms | 255 ms |
| 21 | 125 ms | 184 ms | 243 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.
| hour | Europe | US | Asia |
|---|---|---|---|
| 00 | 118 ms | 176 ms | 240 ms |
| 03 | 104 ms | 168 ms | 226 ms |
| 06 | 122 ms | 181 ms | 251 ms |
| 09 | 156 ms | 203 ms | 268 ms |
| 12 | 171 ms | 224 ms | 289 ms |
| 15 | 149 ms | 210 ms | 274 ms |
| 18 | 138 ms | 195 ms | 255 ms |
| 21 | 125 ms | 184 ms | 243 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
| time | Europe | US |
|---|---|---|
| 0s | 120 ms | 180 ms |
| 1s | 136 ms | 190 ms |
| 2s | 133 ms | 184 ms |
| 3s | 134 ms | 194 ms |
| 4s | 148 ms | 202 ms |
| 5s | 151 ms | 194 ms |
| 6s | 137 ms | 200 ms |
| 7s | 133 ms | 205 ms |
| 8s | 138 ms | 193 ms |
| 9s | 127 ms | 196 ms |
| 10s | 108 ms | 197 ms |
| 11s | 106 ms | 182 ms |
| 12s | 109 ms | 183 ms |
| 13s | 96 ms | 183 ms |
| 14s | 87 ms | 168 ms |
| 15s | 99 ms | 169 ms |
| 16s | 107 ms | 170 ms |
| 17s | 101 ms | 157 ms |
| 18s | 107 ms | 161 ms |
| 19s | 127 ms | 165 ms |
| 20s | 134 ms | 155 ms |
| 21s | 129 ms | 164 ms |
| 22s | 139 ms | 171 ms |
| 23s | 152 ms | 164 ms |
| 24s | 145 ms | 175 ms |
| 25s | 134 ms | 184 ms |
| 26s | 139 ms | 179 ms |
| 27s | 138 ms | 190 ms |
| 28s | 119 ms | 198 ms |
| 29s | 107 ms | 191 ms |
No data
With no rows it says so instead of drawing an empty plot.
| hour | Europe |
|---|
Component API
LineChart takes the props below, and each item of series takes the second table. Everything else about AreaChart applies too.
| Prop | Type | Default |
|---|---|---|
| data | Record<string, unknown>[] | - |
| index | string | - |
| series | LineChartSeries[] | - |
| aria-label | string | - |
| curve | "monotone" | "linear" | "step" | "monotone" |
| strokeWidth | number (px) | 2 |
| showDots | boolean | false |
| connectNulls | boolean | false |
| grid | "horizontal" | "vertical" | "both" | "none" | "horizontal" |
| showXAxis | boolean | true |
| showYAxis | boolean | true |
| showTooltip | boolean | true |
| showLegend | boolean | true if more than one series |
| legendPosition | "top" | "bottom" | "bottom" |
| height | number (px) | 280 |
| valueFormatter | (value: number) => string | number with grouping |
| indexFormatter | (value: string) => string | the value |
| yTickCount | number | 5 |
| minValue | number | 0, or lower if the data is |
| maxValue | number | a round number above the data |
| isLive | boolean | false |
| liveLabel | string | "Live" |
| liveDuration | number (ms) | the time between updates, measured |
| className | string | - |
LineChartSeries
| Prop | Type | Default |
|---|---|---|
| key | string | - |
| label | string | key |
| color | string | the next --chart-N |
| isDashed | boolean | false |
| strokeWidth | number (px) | the chart's strokeWidth |