# Chart

> One Chart component with a series collection covering line, area, column, bar, scatter, bubble, financial, waterfall, histogram, box plot and Pareto series, with curves, stacks and data colors.

Canonical: https://salmonui.dev/docs/data-visualization/chart

`Chart` lives in `@salmonui/charts/chart` (CSS: `@salmonui/charts/chart/styles.css`).
It is one component with a `series` collection: mixed types combine freely
in one chart.

```tsx
import { Chart } from '@salmonui/charts/chart';
import '@salmonui/charts/chart/styles.css';

<Chart
  title="Sales"
  data={rows}
  series={[
    { type: 'column', xField: 'month', yField: 'north', name: 'North' },
    { type: 'line', xField: 'month', yField: 'south', name: 'South', curve: 'monotone', markers: true },
  ]}
/>;
```

Series can also be written as children, which compile to the same model
(and render identically on the server):

```tsx
import { Chart, ChartAxis, ChartSeries } from '@salmonui/charts/chart';

<Chart data={rows}>
  <ChartSeries type="line" xField="month" yField="north" />
  <ChartAxis direction="y" title="Units" />
</Chart>
```

## Series types

| `type` | Covers | Notes |
| --- | --- | --- |
| `'line'` | line, spline, step line, multicolored line | `curve`, `segments` |
| `'area'` | area, spline area, step area, range area, spline and step range area | `lowField` + `highField` draw a range |
| `'column'`, `'bar'` | column, bar, range column | `bar` transposes; `lowField` + `highField` for ranges |
| `'scatter'`, `'bubble'` | scatter, bubble | `markers.shape`, `sizeField`, `radius: [min, max]` |
| `'hilo'`, `'ohlc'`, `'candle'` | high-low, high-low-open-close, candlestick | `openField`, `highField`, `lowField`, `closeField`; candles use the `success` / `danger` seeds, `upColor`, `downColor`, `hollow`; `volumeField` draws volume columns in the bottom fifth of the plot, in the candle colors, and adds the volume to the tooltip |
| `'waterfall'` | waterfall | `totals`, `subtotals` (indexes or a predicate), `connectors` |
| `'histogram'` | histogram | automatic bins or `binWidth`, `normalCurve` |
| `'boxPlot'` | box and whisker | `yField` holds an array per category; `quartileMethod: 'exclusive' \| 'inclusive' \| 'normal'`, `mean`, `outliers` |
| `'pareto'` | Pareto | sorted columns plus the cumulative percent line on a generated secondary axis; `pareto: { line, markers, color }` |

`orientation="horizontal"` transposes the whole chart, so bars combine with
lines and every other series type.

### Live demo: Lines, steps and areas

Live demo: https://salmonui.dev/demos/data-visualization/chart-line-area

A Chart with a range area, a segmented line and an area on a second axis; switch the curve, the step position and the risers, and hide a series.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { Chart } from '@salmonui/charts/chart';
import type { ChartCurve } from '@salmonui/charts/chart';

// Nested records: `yField: 'temp.avg'` reads a dotted path.
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const weather = months.map((month, i) => {
  const avg = Math.round((12 + 10 * Math.sin(((i - 3) / 12) * 2 * Math.PI)) * 10) / 10;
  return { month, index: i + 1, temp: { avg, low: Math.round((avg - 4 - (i % 3)) * 10) / 10, high: Math.round((avg + 5 + (i % 2)) * 10) / 10 }, rain: 40 + ((i * 37) % 60) };
});

export default function ChartLineAreaDemo() {
  const [curve, setCurve] = useState<ChartCurve>('monotone');
  const [stepPosition, setStepPosition] = useState<'start' | 'center' | 'end'>('center');
  const [risers, setRisers] = useState(true);
  const [showRain, setShowRain] = useState(true);
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Curve
          <Select aria-label="Curve" data={(['linear', 'natural', 'monotone', 'cardinal', 'clamped', 'step'] as const).map((c) => ({ value: c, label: c }))} value={curve} onValueChange={(value) => value != null && setCurve(value as ChartCurve)} />
        </label>
        <label>
          Step position
          <Select aria-label="Step position" data={[{ value: 'start', label: 'start' }, { value: 'center', label: 'center' }, { value: 'end', label: 'end' }]} value={stepPosition} onValueChange={(value) => value != null && setStepPosition(value as 'start' | 'center' | 'end')} disabled={curve !== 'step'} />
        </label>
        <Checkbox checked={risers} onCheckedChange={(checked) => setRisers(checked)} disabled={curve !== 'step'}>Risers</Checkbox>
        <Checkbox checked={showRain} onCheckedChange={(checked) => setShowRain(checked)}>Rain series</Checkbox>
      </div>
      <Chart
        title="Temperature and rain"
        subtitle="Range area, line and a segmented area"
        data={weather}
        height={320}
        yAxis={{ title: '°C' }}
        axes={[{ id: 'rain', direction: 'y', position: 'end', title: 'mm', gridLines: false }]}
        series={[
          { type: 'area', name: 'Low to high', xField: 'month', lowField: 'temp.low', highField: 'temp.high', curve, opacity: 0.35, order: 0 },
          {
            type: 'line',
            name: 'Average',
            xField: 'month',
            yField: 'temp.avg',
            curve,
            stepPosition,
            risers,
            markers: true,
            // A data color per segment along y: blue below 8 °C, orange above 18 °C.
            segments: [
              { until: 8, color: '#2563eb' },
              { until: 18, color: '#6b7280' },
              { color: '#c2410c', lineStyle: 'dashed' },
            ],
            segmentAxis: 'y',
          },
          { type: 'area', name: 'Rain', xField: 'month', yField: 'rain', yAxis: 'rain', curve, hidden: !showRain, opacity: 0.25, lineStyle: 'dotted' },
        ]}
      />
    </div>
  );
}
```

## Curves and steps

`series.curve` is `'linear'` (default), `'natural'`, `'monotone'` (no
overshoot), `'cardinal'` with `series.tension`, `'clamped'` or `'step'`.
Steps take `stepPosition: 'start' | 'center' | 'end'` and
`risers: false` to draw the steps without vertical risers.

## Stacks and groups

`series.stack: true | 'percent'` stacks series that share a value axis;
positive and negative values stack separately and `stackGroup` keeps
several stacks side by side. `stackLabels` draws the totals.
Columns of different series sit side by side; `grouping="overlap"`
overlaps them, `series.group` overlaps a subset, `bandWidth` (fraction of
the category, or px above 1) and `gap` size them.

### Live demo: Columns, bars and stacks

Live demo: https://salmonui.dev/demos/data-visualization/chart-columns-stacks

Column and bar series stacked, stacked to 100 % or grouped side by side or overlapping, with stack totals, band widths, range columns and a horizontal chart that combines bars with a line.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Chart } from '@salmonui/charts/chart';
import { Slider } from '@salmonui/inputs/slider';
import { Select } from '@salmonui/dropdowns/select';

const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
const sales = quarters.map((quarter, i) => ({
  quarter,
  north: 42 + i * 6,
  south: 30 + ((i * 7) % 12),
  west: 18 + i * 4,
  returns: -(4 + (i % 3) * 2),
  low: 20 + i * 3,
  high: 48 + i * 5,
  target: 36 + i * 4,
}));

type Stack = 'none' | 'stack' | 'percent';

export default function ChartColumnsStacksDemo() {
  const [stack, setStack] = useState<Stack>('stack');
  const [type, setType] = useState<'column' | 'bar'>('column');
  const [grouping, setGrouping] = useState<'sideBySide' | 'overlap'>('sideBySide');
  const [bandWidth, setBandWidth] = useState(0.7);
  const stacked = stack === 'none' ? undefined : stack === 'percent' ? ('percent' as const) : true;
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Type
          <Select aria-label="Type" data={['column', 'bar']} value={type} onValueChange={(value) => value != null && setType(value as 'column' | 'bar')} />
        </label>
        <label>
          Stack
          <Select aria-label="Stack" data={[{ value: 'none', label: 'none' }, { value: 'stack', label: 'stack: true' }, { value: 'percent', label: 'stack: percent' }]} value={stack} onValueChange={(value) => value != null && setStack(value as Stack)} />
        </label>
        <label>
          Grouping
          <Select aria-label="Grouping" data={['sideBySide', 'overlap']} value={grouping} onValueChange={(value) => value != null && setGrouping(value as 'sideBySide' | 'overlap')} disabled={stack !== 'none'} />
        </label>
        <Slider label="Band width" min={0.2} max={1} step={0.1} value={bandWidth} onValueChange={setBandWidth} style={{ inlineSize: 160 }} />
      </div>
      <Chart
        title="Units by region"
        data={sales}
        height={300}
        grouping={grouping}
        stackLabels={stacked === true}
        series={[
          { type, name: 'North', xField: 'quarter', yField: 'north', stack: stacked, bandWidth, gap: 0.1 },
          { type, name: 'South', xField: 'quarter', yField: 'south', stack: stacked, bandWidth, gap: 0.1 },
          { type, name: 'West', xField: 'quarter', yField: 'west', stack: stacked, bandWidth, gap: 0.1 },
          { type, name: 'Returns', xField: 'quarter', yField: 'returns', stack: stacked, bandWidth, gap: 0.1 },
        ]}
      />
      <Chart
        title="Price range and target"
        subtitle="Horizontal orientation: range bars combined with a line"
        data={sales}
        height={260}
        orientation="horizontal"
        series={[
          { type: 'column', name: 'Price range', xField: 'quarter', lowField: 'low', highField: 'high' },
          { type: 'line', name: 'Target', xField: 'quarter', yField: 'target', markers: true },
        ]}
      />
    </div>
  );
}
```

## Appearance and data colors

`name`, `hidden`, `order` and `opacity` set a series' legend name,
initial visibility, drawing order and opacity. Colors default to the derived palette slot (`--salmon-chart-1`
onward); `series.color`, `palette`, `colorField` and segment colors are
data colors, used as given. `lineStyle: 'solid' | 'dashed' | 'dotted'`
sets the stroke pattern. Segments color a line by value along
`segmentAxis`. `colorRanges` colors points by y value range and
feeds the range and gradient legends (see
[Chart elements](https://salmonui.dev/docs/data-visualization/chart-elements)).

### Live demo: Scatter, bubble and data colors

Live demo: https://salmonui.dev/demos/data-visualization/chart-scatter-bubble

Scatter series with marker shapes, a bubble chart sized by population and colored per point, and columns colored by value ranges with a series, point, range or gradient legend.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Chart } from '@salmonui/charts/chart';
import type { ChartMarkerShape } from '@salmonui/charts/chart';
import { Select } from '@salmonui/dropdowns/select';

// Deterministic sample: height (cm) and weight (kg) of two groups.
const people = Array.from({ length: 40 }, (_, i) => {
  const h = 150 + ((i * 53) % 45);
  return { group: i % 2 ? 'B' : 'A', height: h, weight: Math.round(h * 0.45 - 20 + ((i * 29) % 17)) };
});
const groupA = people.filter((p) => p.group === 'A');
const groupB = people.filter((p) => p.group === 'B');

// Countries: GDP per capita (k$), life expectancy and population (sizeField).
const countries = [
  { name: 'Aland', gdp: 12, life: 68, pop: 40, color: '#2563eb' },
  { name: 'Borea', gdp: 24, life: 74, pop: 120, color: '#7c3aed' },
  { name: 'Corin', gdp: 35, life: 79, pop: 65, color: '#0f766e' },
  { name: 'Dalvi', gdp: 48, life: 81, pop: 18, color: '#b45309' },
  { name: 'Estra', gdp: 8, life: 63, pop: 210, color: '#be123c' },
  { name: 'Fenn', gdp: 56, life: 83, pop: 9, color: '#4d7c0f' },
];

const yields = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map((day, i) => ({ day, yield: 20 + ((i * 41) % 70) }));

type LegendMode = 'series' | 'point' | 'range' | 'gradient';

export default function ChartScatterBubbleDemo() {
  const [shape, setShape] = useState<ChartMarkerShape>('circle');
  const [mode, setMode] = useState<LegendMode>('range');
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Group B marker
          <Select aria-label="Group B marker" data={['circle', 'rectangle', 'triangle', 'diamond', 'cross', 'plus', 'star', 'pentagon']} value={shape} onValueChange={(value) => value != null && setShape(value as ChartMarkerShape)} />
        </label>
        <label>
          Yield legend mode
          <Select aria-label="Yield legend mode" data={['series', 'point', 'range', 'gradient']} value={mode} onValueChange={(value) => value != null && setMode(value as LegendMode)} />
        </label>
      </div>
      <Chart
        title="Height and weight"
        height={280}
        xAxis={{ title: 'Height (cm)', min: 145, max: 200 }}
        yAxis={{ title: 'Weight (kg)', min: 40, max: 90 }}
        series={[
          { type: 'scatter', name: 'Group A', data: groupA, xField: 'height', yField: 'weight' },
          { type: 'scatter', name: 'Group B', data: groupB, xField: 'height', yField: 'weight', markers: { shape, size: 9 } },
        ]}
      />
      <Chart
        title="Wealth and health"
        data={countries}
        height={300}
        xAxis={{ title: 'GDP per capita (k$)', min: 0, max: 65 }}
        yAxis={{ title: 'Life expectancy', min: 55, max: 90 }}
        legend={{ mode: 'point' }}
        series={[{ type: 'bubble', name: 'Countries', xField: 'gdp', yField: 'life', sizeField: 'pop', radius: [6, 30], colorField: 'color', tooltipField: 'name' }]}
      />
      <Chart
        title="Yield by day"
        data={yields}
        height={260}
        legend={{ mode }}
        colorRanges={[
          { from: 0, to: 40, colors: ['#dc2626'], label: 'Low' },
          { from: 40, to: 70, colors: ['#b45309'], label: 'Medium' },
          { from: 70, to: 100, colors: ['#15803d'], label: 'High' },
        ]}
        series={[{ type: 'column', name: 'Yield', xField: 'day', yField: 'yield' }]}
      />
    </div>
  );
}
```

### Live demo: Financial series

Live demo: https://salmonui.dev/demos/data-visualization/chart-financial

Candle, OHLC and high-low series over daily prices, with hollow candles and volume columns in the candle colors.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { Chart } from '@salmonui/charts/chart';

// 30 trading days of deterministic prices (UTC dates, so server and client agree).
const prices = Array.from({ length: 30 }, (_, i) => {
  const open = 100 + 8 * Math.sin(i / 4) + (i % 5);
  const close = open + 3 * Math.sin(i * 1.7);
  return {
    date: new Date(Date.UTC(2026, 0, 5 + i)),
    open: Math.round(open * 100) / 100,
    close: Math.round(close * 100) / 100,
    high: Math.round((Math.max(open, close) + 1.5 + (i % 3)) * 100) / 100,
    low: Math.round((Math.min(open, close) - 1.2 - (i % 4) * 0.5) * 100) / 100,
    volume: 1200 + ((i * 377) % 900),
  };
});

type Kind = 'candle' | 'ohlc' | 'hilo';

export default function ChartFinancialDemo() {
  const [type, setType] = useState<Kind>('candle');
  const [hollow, setHollow] = useState(false);
  const [volume, setVolume] = useState(true);
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Series type
          <Select aria-label="Series type" data={[{ value: 'candle', label: 'candle' }, { value: 'ohlc', label: 'ohlc' }, { value: 'hilo', label: 'hilo' }]} value={type} onValueChange={(value) => value != null && setType(value as Kind)} />
        </label>
        <Checkbox checked={hollow} onCheckedChange={(checked) => setHollow(checked)} disabled={type !== 'candle'}>Hollow candles</Checkbox>
        <Checkbox checked={volume} onCheckedChange={(checked) => setVolume(checked)} disabled={type !== 'candle'}>Volume</Checkbox>
      </div>
      <Chart
        title="ACME daily prices"
        data={prices}
        height={340}
        timeZone="UTC"
        locale="en-US"
        xAxis={{ format: 'MMMd' }}
        yAxis={{ format: 'c0' }}
        tooltip
        series={[
          {
            type,
            name: 'ACME',
            xField: 'date',
            openField: 'open',
            highField: 'high',
            lowField: 'low',
            closeField: 'close',
            hollow,
            volumeField: type === 'candle' && volume ? 'volume' : undefined,
          },
        ]}
      />
    </div>
  );
}
```

## Error bars

`series.errorBars: { kind, amount, direction, caps, axis }` draws whiskers:
`kind` is `'fixed'`, `'percent'`, `'standardDeviation'`,
`'standardError'` or `'custom'` (`plusField` / `minusField`), `direction`
`'both' | 'plus' | 'minus'`, and `axis` `'y'` (default), `'x'` (continuous
x axes) or `'both'`.

### Live demo: Waterfall, histogram, box plot, Pareto and error bars

Live demo: https://salmonui.dev/demos/data-visualization/chart-statistical

The statistical Chart series: a profit bridge with subtotals and totals, a histogram with a normal curve, box plots with three quartile methods, a Pareto chart and columns with five kinds of error bars.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Select } from '@salmonui/dropdowns/select';
import { Chart } from '@salmonui/charts/chart';
import type { ChartErrorBars } from '@salmonui/charts/chart';

const cashFlow = [
  { step: 'Revenue', amount: 420 },
  { step: 'Cost of sales', amount: -180 },
  { step: 'Gross profit', amount: 0 },
  { step: 'Marketing', amount: -60 },
  { step: 'R&D', amount: -75 },
  { step: 'Other income', amount: 25 },
  { step: 'Net profit', amount: 0 },
];

// 200 response times (ms) from a deterministic, roughly normal mix.
const responses = Array.from({ length: 200 }, (_, i) => ({ ms: Math.round(220 + 40 * (Math.sin(i * 12.9898) + Math.sin(i * 78.233) + Math.sin(i * 37.719))) }));

const teams = ['Alpha', 'Beta', 'Gamma', 'Delta'].map((team, t) => ({
  team,
  hours: Array.from({ length: 15 }, (_, i) => 30 + t * 3 + ((i * (7 + t)) % 14) + (i === 3 ? 18 : 0)),
}));

const defects = [
  { cause: 'Misalignment', count: 12 },
  { cause: 'Scratches', count: 46 },
  { cause: 'Wrong part', count: 8 },
  { cause: 'Missing screw', count: 27 },
  { cause: 'Dent', count: 19 },
  { cause: 'Other', count: 5 },
];

const trials = [
  { dose: 'Placebo', effect: 12, plus: 4, minus: 3 },
  { dose: '10 mg', effect: 21, plus: 5, minus: 4 },
  { dose: '20 mg', effect: 34, plus: 6, minus: 6 },
  { dose: '40 mg', effect: 41, plus: 9, minus: 5 },
];

type ErrorKind = ChartErrorBars['kind'];

export default function ChartStatisticalDemo() {
  const [quartile, setQuartile] = useState<'exclusive' | 'inclusive' | 'normal'>('exclusive');
  const [binWidth, setBinWidth] = useState(20);
  const [errorKind, setErrorKind] = useState<ErrorKind>('custom');
  return (
    <div className="demo-stack">
      <Chart
        title="Profit bridge"
        data={cashFlow}
        height={280}
        yAxis={{ format: 'c0' }}
        legend={false}
        series={[{ type: 'waterfall', name: 'Amount', xField: 'step', yField: 'amount', subtotals: [2], totals: [6], connectors: true, labels: true }]}
      />
      <div className="demo-toolbar">
        <label>
          Bin width (ms)
          <Select aria-label="Bin width (ms)" data={[{ value: 10, label: '10' }, { value: 20, label: '20' }, { value: 40, label: '40' }]} value={binWidth} onValueChange={(value) => value != null && setBinWidth(Number(value))} />
        </label>
      </div>
      <Chart title="Response times" data={responses} height={260} legend={false} series={[{ type: 'histogram', name: 'Requests', yField: 'ms', binWidth, normalCurve: true }]} />
      <div className="demo-toolbar">
        <label>
          Quartile method
          <Select aria-label="Quartile method" data={[{ value: 'exclusive', label: 'exclusive' }, { value: 'inclusive', label: 'inclusive' }, { value: 'normal', label: 'normal' }]} value={quartile} onValueChange={(value) => value != null && setQuartile(value as 'exclusive' | 'inclusive' | 'normal')} />
        </label>
      </div>
      <Chart
        title="Weekly hours per team"
        data={teams}
        height={280}
        legend={false}
        series={[{ type: 'boxPlot', name: 'Hours', xField: 'team', yField: 'hours', quartileMethod: quartile, mean: true, outliers: true }]}
      />
      <Chart title="Defects by cause" data={defects} height={280} series={[{ type: 'pareto', name: 'Defects', xField: 'cause', yField: 'count', pareto: { line: true, markers: true } }]} />
      <div className="demo-toolbar">
        <label>
          Error bar kind
          <Select aria-label="Error bar kind" data={[{ value: 'custom', label: 'custom (plus / minus fields)' }, { value: 'fixed', label: 'fixed (3)' }, { value: 'percent', label: 'percent (15)' }, { value: 'standardDeviation', label: 'standardDeviation' }, { value: 'standardError', label: 'standardError' }]} value={errorKind} onValueChange={(value) => value != null && setErrorKind(value as ErrorKind)} />
        </label>
      </div>
      <Chart
        title="Effect by dose"
        data={trials}
        height={260}
        legend={false}
        series={[
          {
            type: 'column',
            name: 'Effect',
            xField: 'dose',
            yField: 'effect',
            errorBars: { kind: errorKind, amount: errorKind === 'percent' ? 15 : errorKind === 'fixed' ? 3 : 1, plusField: 'plus', minusField: 'minus', caps: true },
          },
        ]}
      />
    </div>
  );
}
```

## Live data

`data` is reactive: a new array (for example the old one with a point
appended and the oldest dropped) lays the chart out again, within 2 ms for
a 1,000-point window (`chart-perf.spec.ts`). `api.appendPoints(seriesId,
points, { maxPoints })` streams points through the chart store without a
React render of the parent; `@salmonui/data` live sources feed either.

## Descriptions

`series.description` is appended to the chart summary and the accessible
table caption, so screen readers hear what each series means; keyboard focus
moves through the series in `series` order.

### Live demo: Live data and empty state

Live demo: https://salmonui.dev/demos/data-visualization/chart-live

Stream server load into one chart through reactive data and into another through api.appendPoints, clear the data to see the empty state, with series descriptions for screen readers.

`Demo.tsx`:

```tsx
'use client';

import { useEffect, useRef, useState } from 'react';
import { Chart } from '@salmonui/charts/chart';
import type { ChartApi } from '@salmonui/charts/chart';
import { Button } from '@salmonui/buttons/button';

const WINDOW = 60;
const sample = (t: number) => ({ t, cpu: Math.round(45 + 25 * Math.sin(t / 7) + 10 * Math.sin(t * 1.3)), memory: Math.round(60 + 8 * Math.sin(t / 11)) });
const initial = Array.from({ length: WINDOW }, (_, i) => sample(i));

export default function ChartLiveDemo() {
  const [running, setRunning] = useState(false);
  const [rows, setRows] = useState(initial);
  const streamed = useRef<ChartApi>(null);
  const tick = useRef(WINDOW);

  useEffect(() => {
    if (!running) return undefined;
    const timer = window.setInterval(() => {
      const point = sample(tick.current++);
      // Reactive data: a new array (the oldest point dropped) lays the first chart out again.
      setRows((r) => [...r.slice(r.length >= WINDOW ? 1 : 0), point]);
      // Streaming: the second chart takes the point through its store, without a React render.
      streamed.current?.appendPoints('cpu', [point], { maxPoints: WINDOW });
    }, 250);
    return () => window.clearInterval(timer);
  }, [running]);

  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <Button variant="outline" type="button" onClick={() => setRunning((r) => !r)} aria-pressed={running}>
          {running ? 'Pause' : 'Start'} stream
        </Button>
        <Button variant="outline" type="button" onClick={() => setRows([])}>
          Clear data
        </Button>
        <Button variant="outline" type="button" onClick={() => setRows(initial)}>
          Restore data
        </Button>
      </div>
      <Chart
        title="Server load (reactive data)"
        data={rows}
        height={240}
        yAxis={{ min: 0, max: 100, format: '{value}%' }}
        renderEmpty={() => <span>No samples yet: press Restore data</span>}
        series={[
          { id: 'cpu', name: 'CPU', xField: 't', yField: 'cpu', description: 'CPU use of the web server in percent, sampled four times a second.' },
          { id: 'memory', name: 'Memory', xField: 't', yField: 'memory', description: 'Memory use in percent.' },
        ]}
      />
      <Chart
        ref={streamed}
        title="CPU (streamed with appendPoints)"
        data={initial}
        height={200}
        yAxis={{ min: 0, max: 100 }}
        series={[{ id: 'cpu', name: 'CPU', xField: 't', yField: 'cpu', description: 'The same CPU samples, streamed into the chart store.' }]}
      />
    </div>
  );
}
```

## Polar and radar

```tsx
import { Chart } from '@salmonui/charts/chart';
import { polar } from '@salmonui/charts/chart/features';

<Chart
  coordinate="radar"
  features={[polar]}
  xAxis={{ startAngle: 0 }}
  radius={0.9}
  data={wind}
  series={[
    { type: 'area', xField: 'direction', yField: 'speed' },
    { type: 'line', xField: 'direction', yField: 'gust', closed: false },
  ]}
/>;
```

`coordinate: 'polar' | 'radar'` maps x to the angle (clockwise from
`xAxis.startAngle`, counterclockwise with `xAxis.reversed`) and y to the
radius from the center (`yAxis.reversed` inverts it); `radius` (0..1)
shrinks the circle. Polar charts draw circles, radar charts polygons
between the spokes. Every polar and radar draw type is a series type:
`line`, spline (`curve`), `area`, spline area, `column` (wedges, side by
side per series), range column (`lowField` / `highField`), `scatter`, and
the stacking variants with `stack`; lines and areas close back to the
first point unless `series.closed` is `false`. Hover, focus, tooltips,
selection and the accessible table work as on cartesian charts.

The polar layout is an opt-in feature: pass `features={[polar]}` from
`@salmonui/charts/chart/features`. It renders on the server and the client alike; a chart without it
never loads the code, draws the frame only and warns in development.
`features={[interactions]}` bundles the zoom, pan, selection and drag code
so it is ready on the first pointer event instead of loading after
hydration.

### Live demo: Polar and radar charts

Live demo: https://salmonui.dev/demos/data-visualization/chart-polar

Wind speed by direction on polar circles or radar polygons, drawn as lines, areas, wedges or points, stacked or not, from any start angle.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Chart } from '@salmonui/charts/chart';
import { polar } from '@salmonui/charts/chart/features';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Slider } from '@salmonui/inputs/slider';
import { Select } from '@salmonui/dropdowns/select';

const wind = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].map((direction, i) => ({
  direction,
  speed: 8 + ((i * 5) % 9),
  gust: 14 + ((i * 7) % 11),
  calm: 2 + (i % 3),
}));

type DrawType = 'line' | 'area' | 'column' | 'scatter';

export default function ChartPolarDemo() {
  const [coordinate, setCoordinate] = useState<'polar' | 'radar'>('polar');
  const [drawType, setDrawType] = useState<DrawType>('column');
  const [stacked, setStacked] = useState(false);
  const [startAngle, setStartAngle] = useState(0);
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Coordinate
          <Select aria-label="Coordinate" data={['polar', 'radar']} value={coordinate} onValueChange={(value) => value != null && setCoordinate(value as 'polar' | 'radar')} />
        </label>
        <label>
          Series type
          <Select aria-label="Series type" data={['line', 'area', 'column', 'scatter']} value={drawType} onValueChange={(value) => value != null && setDrawType(value as DrawType)} />
        </label>
        <Checkbox checked={stacked} onCheckedChange={(checked) => setStacked(checked)}>
          Stacked
        </Checkbox>
        <Slider label="Start angle" min={0} max={315} step={45} value={startAngle} onValueChange={setStartAngle} style={{ inlineSize: 160 }} />
      </div>
      <Chart
        title="Wind by direction"
        coordinate={coordinate}
        features={[polar]}
        xAxis={{ startAngle }}
        radius={0.9}
        data={wind}
        height={380}
        series={[
          { type: drawType, name: 'Calm', xField: 'direction', yField: 'calm', stack: stacked || undefined },
          { type: drawType, name: 'Speed', xField: 'direction', yField: 'speed', stack: stacked || undefined },
          { type: drawType, name: 'Gust', xField: 'direction', yField: 'gust', stack: stacked || undefined },
        ]}
      />
    </div>
  );
}
```

## Field mapping

`xField`, `yField`, `lowField`, `highField`, `openField`, `closeField`,
`sizeField`, `colorField` and `tooltipField` read plain records, including
dotted paths such as `'price.close'`; `series.xAxis` / `series.yAxis` bind a
series to an axis by id. Per-series `data` overrides the chart
`data`.

## State, events and accessibility

Every interactive state is a controlled triad you can also leave
uncontrolled: `hiddenSeries` / `defaultHiddenSeries` /
`onHiddenSeriesChange`, `selectedPoints` / `defaultSelectedPoints` /
`onSelectedPointsChange` and `zoomRange` / `defaultZoomRange` /
`onZoomRangeChange`. Point and plot events (`onPointClick`,
`onPlotClick`, ...) are covered in
[Chart interaction](https://salmonui.dev/docs/data-visualization/chart-interaction).

The chart is a `<figure>` named by `title` (or `aria-label` /
`aria-labelledby`) with an automatic summary and a visually hidden data
table; the plot is one tab stop with arrow-key navigation between points
and the legend is a toolbar of toggle buttons
([Chart interaction](https://salmonui.dev/docs/data-visualization/chart-interaction),
"Keyboard").

The server renders the final SVG at the nominal size (`width`, else 600
px, and `height`, default 300) and the client relays out once after
hydration if the measured size differs, so there are no hydration
warnings; set `locale` and `timeZone` so the server and the browser format
alike ([Rendering and colors](https://salmonui.dev/docs/data-visualization/rendering-and-colors)).

## Features and templates

Features load from their props through lazy chunks; nothing is registered
up front. Two features are explicit opt-in imports because they do not fit
the Chart bundle budget:

```tsx
import { polar, interactions } from '@salmonui/charts/chart/features';
import { technicalIndicators } from '@salmonui/charts/chart/indicators';

<Chart coordinate="polar" features={[polar]} /* ... */ />;
<Chart indicators={indicators} features={[technicalIndicators]} /* ... */ />;
```

Passing `interactions` is optional and makes zoom, pan and selection ready on
the first pointer event.

Custom content comes from render props, never from HTML string templates:
a string template would need HTML parsing and a sanitizer on the render
path and could not be type-checked. Use a tooltip `render`,
`series.renderMarker`, an axis `renderLabel` or `renderEmpty`:

```tsx
<Chart tooltip={{ render: ({ header, points }) => <div>{header}: {points[0]?.yText}</div> }} /* ... */ />
```

## Data, state and lifecycle

**Data.** `Chart` and the other visualizations take an array in
`data`. Load the rows through a `@salmonui/data` source or your own fetch
and pass the result; `Kanban` takes a `@salmonui/data` source directly.

**Persistence.** Components never write to `localStorage`, and
server output never depends on client storage. To restore a view, store the
controlled values from their change callbacks and pass them back:
`zoomRange`, `hiddenSeries` and `selectedPoints` on `Chart`, `value` on
gauges, `path` on `TreeMap`, `view` on `GeoMap` and `columnOrder` on
`Kanban`.

**Lifecycle.** React owns the lifecycle and renders stay pure, so
there are no load or loaded events that mutate the instance. Configure the
chart through props, and run code that needs the rendered chart in an
effect that reads the `ref`. There is no animation-complete callback.

**Updates.** Props are reactive: a changed prop re-renders
only the affected part, so there is no refresh method. If you mutated data
in place, pass a new array. `series` and `axes` are plain arrays with one
source of truth, so there are no methods that add or remove series or axes:
keep them in application state and update the arrays. For streaming, use
`api.appendPoints(seriesId, points)`.

**WebMCP.** WebMCP is a browser API proposal, so components do not
register tools. Your application can register its own tools against the
`ref` APIs.

## 3D and specialized charts

There are no 3D charts, because 3D perspective distorts length and area
judgments and has poor accessibility.

- **3D column and bar series.** Use `Chart` with `column` and `bar`
  series, in any stacking mode.
- **Depth, rotation and tilt.** Not supported. Scientific 3D
  plotting would be a separate WebGL product.
- **3D pie and donut.** Use
  [PieChart](https://salmonui.dev/docs/data-visualization/pie-chart), which has pie, donut,
  explode, labels, legend, tooltip, selection and export.
- **3D legend, tooltip, labels, selection, export and print.** Each
  is available on the flat `Chart` or `PieChart`.
- **Smith chart.** Not built, because it serves radio-frequency
  engineering only; use a dedicated RF plotting library. `coordinate`
  accepts `cartesian`, `polar` and `radar`.
- **Chart wizard.** There is no built-in chart wizard. `Chart` props
  are plain data, so an application can build a guided editor on top.

Every prop is listed in the [API reference](https://salmonui.dev/docs/reference/charts/chart).
