# Chart axes

> Linear, logarithmic, time, category and time-category axes with nice ticks, calendar-aware time ticks, ranges, multiple axes, label overlap strategies, edge labels and zoom ranges.

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

Axes are `xAxis`, `yAxis` and any number of extra `axes` (each with an
`id` and a `direction`); a series picks its axes with `series.xAxis` /
`series.yAxis`, and `axis.position: 'end'` opposes an axis.
Every axis option below is a field of `xAxis`, `yAxis`, an `axes` entry or
a `ChartAxis` child of `Chart` (`@salmonui/charts/chart`).

## Panes

`panes` splits the plot into rows and columns; an axis picks its pane with
`axis.pane`, and its series follow it:

```tsx
<Chart
  panes={{ rows: ['70%', '30%'] }}
  axes={[{ id: 'volume', direction: 'y', pane: { row: 1 }, title: 'Volume' }]}
  series={[
    { type: 'line', xField: 'date', yField: 'close' },
    { type: 'column', xField: 'date', yField: 'volume', yAxis: 'volume' },
  ]}
/>
```

Axes on the left or right take a row (`pane.row`), axes on the top or
bottom a column (`pane.column`); `pane.span` covers several. A size is px,
`'n%'` of the plot or `{ size }`; unsized panes share the rest equally.
Axes of one side in different panes share one slot instead of stacking
outward, and each axis draws its line and title along its own pane.

## Scales

- `scale: 'linear'` (the default for numbers) uses 1-2-5 nice ticks.
- `scale: 'time'` (the default for `Date` values and ISO date strings)
  ticks on calendar boundaries: local midnight, the first of a month, ...
  in the chart `timeZone`. `axis.interval: { unit, step }` fixes the
  interval and `axis.format` takes a date skeleton (`'yMMMd'`) or
  `Intl.DateTimeFormatOptions`. Without `timeZone`, server and
  client render in UTC.
- `scale: 'category'` (the default for strings) and `scale: 'timeCategory'`
  (dates without gaps) place one band per value;
  `axis.labelPlacement: 'between' | 'on'` puts labels between ticks or on
  them, and `axis.indexed: true` gives every point index its own band, so
  repeated categories stay separate.
- `scale: 'log'` with `axis.base`.

### Live demo: Axis scales and ranges

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

Time and time-category axes with calendar intervals, linear and log value axes, an indexed category axis with label placement, and axis ranges with includeZero, padding, min, max, interval and tickCount.

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

// Trading days only (weekends missing): a 'time' axis shows the gaps, 'timeCategory' closes them.
const days = Array.from({ length: 30 }, (_, i) => new Date(Date.UTC(2026, 2, 2 + i))).filter((d) => d.getUTCDay() % 6 !== 0);
const closes = days.map((date, i) => ({ date, close: 180 + 12 * Math.sin(i / 3) + i }));

const growth = Array.from({ length: 10 }, (_, i) => ({ year: 2016 + i, users: Math.round(30 * 2.4 ** i) }));

// Two "Mon" categories: only indexed: true keeps them apart.
const shifts = [
  { day: 'Mon', output: 42 },
  { day: 'Tue', output: 47 },
  { day: 'Wed', output: 51 },
  { day: 'Mon', output: 39 },
  { day: 'Tue', output: 44 },
];

type Unit = 'day' | 'week';
type Padding = 'auto' | 'none' | 'normal' | 'additional' | 'round';

export default function ChartAxisScalesDemo() {
  const [timeScale, setTimeScale] = useState<'time' | 'timeCategory'>('time');
  const [unit, setUnit] = useState<Unit>('week');
  const [valueScale, setValueScale] = useState<'linear' | 'log'>('log');
  const [base, setBase] = useState(10);
  const [includeZero, setIncludeZero] = useState(false);
  const [padding, setPadding] = useState<Padding>('auto');
  const [indexed, setIndexed] = useState(true);
  const [placement, setPlacement] = useState<'between' | 'on'>('between');
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Date scale
          <Select aria-label="Date scale" data={[{ value: 'time', label: 'time' }, { value: 'timeCategory', label: 'timeCategory' }]} value={timeScale} onValueChange={(value) => value != null && setTimeScale(value as 'time' | 'timeCategory')} />
        </label>
        <label>
          Interval
          <Select aria-label="Interval" data={[{ value: 'day', label: '2 days' }, { value: 'week', label: '1 week' }]} value={unit} onValueChange={(value) => value != null && setUnit(value as Unit)} disabled={timeScale !== 'time'} />
        </label>
        <Checkbox checked={includeZero} onCheckedChange={(checked) => setIncludeZero(checked)}>includeZero</Checkbox>
        <label>
          Padding
          <Select aria-label="Padding" data={(['auto', 'none', 'normal', 'additional', 'round'] as const).map((p) => ({ value: p, label: p }))} value={padding} onValueChange={(value) => value != null && setPadding(value as Padding)} />
        </label>
      </div>
      <Chart
        title="Closing price"
        data={closes}
        height={240}
        timeZone="UTC"
        locale="en-US"
        legend={false}
        xAxis={{ scale: timeScale, interval: timeScale === 'time' ? (unit === 'day' ? { unit: 'day', step: 2 } : { unit: 'week', step: 1 }) : undefined, format: 'MMMd', labelOverlap: 'hide' }}
        yAxis={{ includeZero, padding, format: 'c0' }}
        series={[{ type: 'line', name: 'Close', xField: 'date', yField: 'close', markers: timeScale === 'timeCategory' }]}
      />
      <div className="demo-toolbar">
        <label>
          Value scale
          <Select aria-label="Value scale" data={[{ value: 'linear', label: 'linear' }, { value: 'log', label: 'log' }]} value={valueScale} onValueChange={(value) => value != null && setValueScale(value as 'linear' | 'log')} />
        </label>
        <label>
          Log base
          <Select aria-label="Log base" data={[{ value: 2, label: '2' }, { value: 10, label: '10' }]} value={base} onValueChange={(value) => value != null && setBase(Number(value))} disabled={valueScale !== 'log'} />
        </label>
      </div>
      <Chart
        title="Users per year"
        data={growth}
        height={240}
        legend={false}
        xAxis={{ scale: 'linear', min: 2016, max: 2025, interval: 1, formatLabel: (v) => String(v) }}
        yAxis={{ scale: valueScale, base, format: 'n0' }}
        series={[{ type: 'line', name: 'Users', xField: 'year', yField: 'users', markers: true }]}
      />
      <div className="demo-toolbar">
        <Checkbox checked={indexed} onCheckedChange={(checked) => setIndexed(checked)}>indexed</Checkbox>
        <label>
          Label placement
          <Select aria-label="Label placement" data={[{ value: 'between', label: 'between' }, { value: 'on', label: 'on' }]} value={placement} onValueChange={(value) => value != null && setPlacement(value as 'between' | 'on')} />
        </label>
      </div>
      <Chart
        title="Output per shift"
        data={shifts}
        height={220}
        legend={false}
        xAxis={{ scale: 'category', indexed, labelPlacement: placement }}
        yAxis={{ min: 0, max: 60, tickCount: 4 }}
        series={[{ type: 'column', name: 'Output', xField: 'day', yField: 'output' }]}
      />
    </div>
  );
}
```

## Ranges

`axis.min`, `axis.max`, `axis.interval` (numeric step), `axis.tickCount`,
`axis.includeZero` and `axis.padding: 'auto' | 'none' | 'normal' |
'additional' | 'round'` replace `minimum`, `maximum`, `interval`,
`desiredIntervals`, `startFromZero` and `rangePadding`.

## Labels

`axis.labelOverlap` resolves crowded labels: `'hide'` (keep every n-th),
`'trim'`, `'wrap'`, `'stagger'`, `'rotate45'` or `'rotate90'`, and
`axis.labelAngle` sets a fixed rotation. Widths come from a deterministic
text-width table, so server and client agree without measuring text.
`axis.edgeLabels: 'hide' | 'shift'` keeps the first and last
label inside the chart.

`axis.labelPosition` and `axis.tickPosition` (`'inside' | 'outside'`) put
the labels and the tick marks inside or outside the plot independently,
and `axis.plotOffset` (px) pads both ends of the axis.
`axis.ticks: false`, `axis.line: false`, `axis.hidden`, `axis.gridLines`
and `axis.minorTicks` toggle the parts of an axis; `axis.title`
with `axis.titleAngle` (degrees) names it. `axis.format` takes a
preset (`'n1'`, `'c0'`, `'p0'`), a `{value}` template or `Intl` options,
`axis.formatLabel(value)` returns the text, and `axis.renderLabel(ctx)`
returns SVG text content (a string or `<tspan>`s) for a tick.

Formats use the same grammar and output as Data Grid `column.format`:
presets (`'n2'`, `'c2'`, `'p1'`), `Intl.NumberFormatOptions` /
`Intl.DateTimeFormatOptions` and date skeletons (`'yMMMd'`, `'Hm'`), in
the chart `locale` and `timeZone`. There is no catalog-wide
locale context, so `locale` is a prop; set it so the server and the
client format alike.
`onAxisLabelClick({ axisId, value, text, index }, event)` reports a click
on a tick label, and `axis.domain(computed)` adjusts the computed range.

```tsx
<Chart
  data={sales}
  xAxis={{
    labelGroups: [
      { levels: [{ from: 'Jan', to: 'Mar', label: 'Q1' }, { from: 'Apr', to: 'Jun', label: 'Q2' }] },
      { levels: [{ from: 'Jan', to: 'Jun', label: 'H1' }], border: 'brace' },
    ],
  }}
  onAxisLabelGroupClick={({ label }) => console.log(label)}
  series={[{ type: 'column', xField: 'month', yField: 'north' }]}
/>
```

`axis.labelGroups` draws multi-level labels: one row per group (a column
on a vertical axis), one cell per level from a category (or value) to
another, with `border: 'rectangle' | 'brace' | 'curlyBrace' | 'none' |
'noTop' | 'noTopBottom'`; `onAxisLabelGroupClick` reports a click on a
cell.

### Live demo: Axis labels, formats and groups

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

Crowded category labels resolved by hiding, trimming, wrapping, staggering or rotating; edge labels; inside labels and ticks; label formats, functions and SVG content; multi-level label groups; label clicks and locales.

`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 { ChartLabelOverlap } from '@salmonui/charts/chart';

const products = ['Espresso machine', 'Milk frother', 'Burr grinder', 'Kettle with thermometer', 'Pour-over dripper', 'Cold brew jar', 'Tamper', 'Scale with timer'];
const units = products.map((product, i) => ({ product, units: 120 + ((i * 53) % 140) }));

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const revenue = months.map((month, i) => ({ month, revenue: 1_200_000 + Math.round(400_000 * Math.sin(i / 2)) + i * 50_000 }));

const quarter = (label: string, from: number) => ({ from: months[from]!, to: months[from + 2]!, label });

export default function ChartAxisLabelsDemo() {
  const [overlap, setOverlap] = useState<ChartLabelOverlap>('wrap');
  const [edge, setEdge] = useState<'none' | 'hide' | 'shift'>('shift');
  const [inside, setInside] = useState(false);
  const [locale, setLocale] = useState('en-US');
  const [clicked, setClicked] = useState('nothing yet');
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Label overlap
          <Select aria-label="Label overlap" data={(['none', 'hide', 'trim', 'wrap', 'stagger', 'rotate45', 'rotate90'] as const).map((o) => ({ value: o, label: o }))} value={overlap} onValueChange={(value) => value != null && setOverlap(value as ChartLabelOverlap)} />
        </label>
        <label>
          Edge labels
          <Select aria-label="Edge labels" data={[{ value: 'none', label: 'none' }, { value: 'hide', label: 'hide' }, { value: 'shift', label: 'shift' }]} value={edge} onValueChange={(value) => value != null && setEdge(value as 'none' | 'hide' | 'shift')} />
        </label>
        <Checkbox checked={inside} onCheckedChange={(checked) => setInside(checked)}>Labels and ticks inside</Checkbox>
      </div>
      <Chart
        title="Units by product"
        data={units}
        height={300}
        legend={false}
        xAxis={{ labelOverlap: overlap, maxLabelWidth: 80, edgeLabels: edge }}
        yAxis={{ labelPosition: inside ? 'inside' : 'outside', tickPosition: inside ? 'inside' : 'outside', plotOffset: 8, formatLabel: (v) => `${String(v)} pcs` }}
        onAxisLabelClick={(ctx) => setClicked(`${ctx.axisId} axis: ${ctx.text}`)}
        series={[{ type: 'column', name: 'Units', xField: 'product', yField: 'units' }]}
      />
      <div className="demo-toolbar">
        <label>
          Locale
          <Select aria-label="Locale" data={[{ value: 'en-US', label: 'en-US' }, { value: 'de-DE', label: 'de-DE' }, { value: 'ja-JP', label: 'ja-JP' }]} value={locale} onValueChange={(value) => value != null && setLocale(String(value))} />
        </label>
      </div>
      <Chart
        title="Revenue"
        data={revenue}
        height={300}
        legend={false}
        locale={locale}
        xAxis={{
          labelGroups: [{ levels: [quarter('Q1', 0), quarter('Q2', 3), quarter('Q3', 6), quarter('Q4', 9)] }, { levels: [{ from: 'Jan', to: 'Jun', label: 'H1' }, { from: 'Jul', to: 'Dec', label: 'H2' }], border: 'brace' }],
          renderLabel: (ctx) => (ctx.index % 3 === 0 ? <tspan fontWeight="bold">{ctx.text}</tspan> : ctx.text),
        }}
        yAxis={{ format: { style: 'currency', currency: 'EUR', notation: 'compact' }, domain: ([, max]) => [0, Math.ceil(max / 500_000) * 500_000] }}
        onAxisLabelClick={(ctx) => setClicked(`${ctx.axisId} axis: ${ctx.text}`)}
        onAxisLabelGroupClick={(ctx) => setClicked(`label group ${ctx.group}, level ${ctx.level}: ${ctx.label}`)}
        series={[{ type: 'area', name: 'Revenue', xField: 'month', yField: 'revenue', curve: 'monotone' }]}
      />
      <p className="demo-status" aria-live="polite">
        Clicked: <code>{clicked}</code>
      </p>
    </div>
  );
}
```

## Crossing and bands

`axis.crossAt: { value, axis }` draws the axis line where the crossing
axis (default: the primary axis of the other direction) has `value`; the
labels stay at the plot edge unless `axis.labelsAtCross` moves them with
the line. `axis.reversed` inverts an axis.
`axis.bands: [{ from, to, every, until, layer, label, color, crossFrom,
crossTo }]` shades ranges behind or over the series, repeating with
`every`, and `crossFrom` / `crossTo` limit a band to a segment of the
crossing axis; `axis.lines` draws labelled value lines.

### Live demo: Multiple axes, panes, crossing and bands

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

A chart with three value axes, a pane for one of them, grid lines and minor ticks, axis titles, value bands and lines, and a second chart whose axes cross at zero and can be reversed.

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

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const plant = months.map((month, i) => ({
  month,
  index: i,
  output: 900 + Math.round(180 * Math.sin(i / 2)),
  temperature: Math.round(14 + 9 * Math.sin(((i - 3) / 12) * 2 * Math.PI)),
  defects: 3 + ((i * 7) % 6),
}));
const balance = Array.from({ length: 21 }, (_, i) => ({ x: i - 10, y: Math.round((i - 10) ** 3 / 40 - (i - 10) * 2) }));

type Grid = 'none' | 'major' | 'both';

export default function ChartAxisLayoutDemo() {
  const [panes, setPanes] = useState(true);
  const [opposed, setOpposed] = useState(true);
  const [grid, setGrid] = useState<Grid>('major');
  const [reversed, setReversed] = useState(false);
  const [labelsAtCross, setLabelsAtCross] = useState(true);
  const [titleAngle, setTitleAngle] = useState(-90);
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <Checkbox checked={panes} onCheckedChange={(checked) => setPanes(checked)}>Defects in their own pane</Checkbox>
        <Checkbox checked={opposed} onCheckedChange={(checked) => setOpposed(checked)}>Temperature axis at the end</Checkbox>
        <label>
          Grid lines
          <Select aria-label="Grid lines" data={[{ value: 'none', label: 'false' }, { value: 'major', label: 'major' }, { value: 'both', label: 'both (with minor ticks)' }]} value={grid} onValueChange={(value) => value != null && setGrid(value as Grid)} />
        </label>
        <label>
          Title angle
          <Select aria-label="Title angle" data={[{ value: -90, label: '-90' }, { value: 0, label: '0' }, { value: 90, label: '90' }]} value={titleAngle} onValueChange={(value) => value != null && setTitleAngle(Number(value))} />
        </label>
      </div>
      <Chart
        title="Plant output"
        data={plant}
        height={380}
        panes={panes ? { rows: ['70%', '30%'] } : undefined}
        yAxis={{ title: 'Units', titleAngle, gridLines: grid === 'none' ? false : grid, minorTicks: grid === 'both' ? 1 : undefined, bands: [{ from: 1000, to: 1100, label: 'Target zone', color: '#15803d' }], lines: [{ value: 800, label: 'Minimum', lineStyle: 'dashed', color: '#dc2626' }] }}
        xAxis={{ bands: [{ from: 5, to: 7, label: 'Summer shutdown', layer: 'behind' }] }}
        axes={[
          { id: 'temp', direction: 'y', position: opposed ? 'end' : 'start', title: '°C', titleAngle, gridLines: false },
          { id: 'defects', direction: 'y', title: 'Defects', titleAngle, pane: panes ? { row: 1 } : undefined, position: panes ? 'start' : 'end', gridLines: false, ticks: false, line: false },
        ]}
        series={[
          { type: 'column', name: 'Output', xField: 'month', yField: 'output' },
          { type: 'line', name: 'Temperature', xField: 'month', yField: 'temperature', yAxis: 'temp', markers: true },
          { type: 'column', name: 'Defects', xField: 'month', yField: 'defects', yAxis: 'defects' },
        ]}
      />
      <div className="demo-toolbar">
        <Checkbox checked={reversed} onCheckedChange={(checked) => setReversed(checked)}>Reverse the y axis</Checkbox>
        <Checkbox checked={labelsAtCross} onCheckedChange={(checked) => setLabelsAtCross(checked)}>Labels at the crossing</Checkbox>
      </div>
      <Chart
        title="Axes crossing at zero"
        data={balance}
        height={280}
        legend={false}
        xAxis={{ crossAt: { value: 0 }, labelsAtCross }}
        yAxis={{ crossAt: { value: 0 }, labelsAtCross, reversed }}
        series={[{ type: 'line', name: 'y', xField: 'x', yField: 'y', curve: 'natural' }]}
      />
    </div>
  );
}
```

## Zoom range

The zoom range is a controlled triad: `zoomRange` / `defaultZoomRange` /
`onZoomRangeChange`, keyed by axis id in data units
(`{ x: [start, end] }`). Ticks are recomputed for the visible range.
`onVisibleRangeChange({ axisId, range })` fires once per committed change of
a continuous axis (never per drag frame), the hook for loading the data of
the visible range from the application or a `@salmonui/data` source.
See [Chart interaction](https://salmonui.dev/docs/data-visualization/chart-interaction).

The zoom range demo is on [Chart interaction](https://salmonui.dev/docs/data-visualization/chart-interaction).
Every axis field is listed under `ChartAxisOptions` in the
[API reference](https://salmonui.dev/docs/reference/charts/chart).

## Axis scrollbar

There is no axis scrollbar, because it does not fit the Chart
bundle budget and its job is already covered: a zoomed chart pans by drag,
wheel and keyboard and through the zoom toolbar. To see and move the zoomed
window, link a [RangeSelector](https://salmonui.dev/docs/data-visualization/range-selector):

```tsx
const [zoom, setZoom] = useState<ChartZoomRange>({ x: [0, 100] });

<Chart zoom zoomRange={zoom} onZoomRangeChange={(range) => setZoom(range)} /* ... */ />
<RangeSelector value={zoom.x} onValueCommit={(x) => setZoom({ x })} /* ... */ />
```

Run code that reacts to scrolling in `onZoomRangeChange`.
