# Chart elements

> Titles, the legend toolbar with toggling and paging, data labels, last-value badges, inline series labels and annotations.

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

## Title

`title` and `subtitle` are drawn at the top, start-aligned, and label the
`<figure>` through its `figcaption`. For a custom heading, omit
`title` and pass `aria-labelledby` with the heading's id, or `aria-label`;
they name the figure and the focusable plot and win over `title` and the
generated summary (`aria-labelledby` first). The title position is
fixed, which keeps a consistent reading order for assistive technology; for
a custom layout, render your own heading next to the chart and reference it
with `aria-labelledby`. Without any of them, the accessible name comes from
the generated data summary.

## Legend

The legend appears with two or more series (`legend` forces it,
`legend={false}` hides it). It is drawn in the SVG and covered by an APG
Toolbar of toggle buttons: one tab stop, arrow keys between items (mirrored
in RTL), `aria-pressed` for the visible state, and the full series name as
the accessible name even when the drawn label is truncated.

Toggling proposes a change of the `hiddenSeries` / `defaultHiddenSeries` /
`onHiddenSeriesChange(ids, event)` triad; `legend={{ toggle: false }}` makes
the buttons plain. `legend={{ overflow: 'page' }}` pages a long
legend with previous / next buttons; `legend.title` and
`legend.maxLabelWidth` add a title and truncate labels with an ellipsis.

`legend.position` is `'auto'`, `'top'`, `'bottom'`, `'start'` or `'end'`;
`align: 'start' | 'center' | 'end'` places the legend along that edge and
`orientation: 'vertical'` lays a top or bottom legend out in one column
(side legends are always one column, top and bottom legends wrap in rows by
default); `columns` fixes a grid and `reverse` flips the order.

`legend.mode` picks the items:

- `'series'` (default): one toggle per series.
- `'point'`: one item per point of the first visible series, in the point
  colors (`colorField`, `colorRanges`, `getPointStyle`).
- `'range'`: one item per `colorRanges` entry (`label`, or `from – to`).
- `'gradient'`: one key with the `colorRanges` colors from the lowest
  `from` to the highest `to`.

Point, range and gradient items are keys: they highlight on hover and focus
but do not toggle. `colorRanges={[{ from, to, colors, label }]}` colors every
point by its y value (several colors split the range into equal steps;
data colors).

`legend.renderItem(item)` returns custom content for an item (an icon, an
image, rich text): it is rendered inside the item's toolbar button, on the
server too, and replaces the drawn symbol and text; the accessible name
stays the series name. Custom items are HTML, so they are not part of the
exported SVG. For a legend image, render an `<img>` in
`renderItem`:

```tsx
<Chart legend={{ renderItem: (item) => <><img src={`/icons/${item.id}.svg`} alt="" width={12} />{item.label}</> }} ... />
```

`series.legendShape` picks the drawn symbol per series: any marker shape
(`'circle'`, `'rectangle'`, `'triangle'`, `'diamond'`, `'star'`, ...) or
`'seriesType'` (default, a symbol for the series type).

### Live demo: Legend

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

A ten-series legend with positions, alignment, wrapping or paging, a title, truncated labels, legend shapes, custom items and a controlled list of hidden series.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Chart } from '@salmonui/charts/chart';
import type { ChartLegendShape, ChartSeriesOptions } from '@salmonui/charts/chart';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';

const cities = ['Amsterdam', 'Barcelona', 'Copenhagen', 'Dublin', 'Edinburgh', 'Florence', 'Geneva', 'Helsinki', 'Istanbul (European side)', 'Jerusalem'];
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
const visitors = months.map((month, m) => Object.fromEntries([['month', month], ...cities.map((c, i) => [c, 20 + ((m * 7 + i * 11) % 30)])]));
const shapes: readonly ChartLegendShape[] = ['seriesType', 'circle', 'rectangle', 'triangle', 'diamond', 'star', 'pentagon', 'cross', 'horizontalLine', 'invertedTriangle'];

type Position = 'auto' | 'top' | 'bottom' | 'start' | 'end';
type Align = 'start' | 'center' | 'end';

export default function ChartLegendDemo() {
  const [position, setPosition] = useState<Position>('bottom');
  const [align, setAlign] = useState<Align>('center');
  const [overflow, setOverflow] = useState<'wrap' | 'page'>('page');
  const [vertical, setVertical] = useState(false);
  const [reverse, setReverse] = useState(false);
  const [custom, setCustom] = useState(false);
  const [toggle, setToggle] = useState(true);
  const [hidden, setHidden] = useState<readonly string[]>(['Geneva', 'Helsinki']);

  const series: ChartSeriesOptions[] = cities.map((c, i) => {
    const shape = shapes[i] ?? 'seriesType';
    return { type: 'line', name: c, xField: 'month', yField: c, legendShape: shape, markers: { shape: shape === 'seriesType' ? 'circle' : shape } };
  });

  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Position
          <Select aria-label="Position" data={['auto', 'top', 'bottom', 'start', 'end']} value={position} onValueChange={(value) => value != null && setPosition(value as Position)} />
        </label>
        <label>
          Align
          <Select aria-label="Align" data={['start', 'center', 'end']} value={align} onValueChange={(value) => value != null && setAlign(value as Align)} />
        </label>
        <label>
          Overflow
          <Select aria-label="Overflow" data={['wrap', 'page']} value={overflow} onValueChange={(value) => value != null && setOverflow(value as 'wrap' | 'page')} />
        </label>
        <Checkbox checked={vertical} onCheckedChange={(checked) => setVertical(checked)}>
          Vertical
        </Checkbox>
        <Checkbox checked={reverse} onCheckedChange={(checked) => setReverse(checked)}>
          Reverse
        </Checkbox>
        <Checkbox checked={custom} onCheckedChange={(checked) => setCustom(checked)}>
          Custom items
        </Checkbox>
        <Checkbox checked={toggle} onCheckedChange={(checked) => setToggle(checked)}>
          Toggle on click
        </Checkbox>
      </div>
      <Chart
        title="Visitors per city (thousands)"
        data={visitors}
        height={360}
        legend={{
          position,
          align,
          overflow,
          orientation: vertical ? 'vertical' : 'horizontal',
          reverse,
          toggle,
          title: 'Cities',
          maxLabelWidth: 90,
          renderItem: custom
            ? (item) => (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, opacity: item.hidden ? 0.5 : 1 }}>
                  <span aria-hidden="true" style={{ inlineSize: 10, blockSize: 10, borderRadius: 'var(--salmon-radius-sm)', background: item.color }} />
                  {item.label.slice(0, 3).toUpperCase()}
                </span>
              )
            : undefined,
        }}
        hiddenSeries={hidden}
        onHiddenSeriesChange={(ids) => setHidden(ids)}
        series={series}
      />
      <p className="demo-status" aria-live="polite">
        hiddenSeries: <code>{hidden.join(', ') || 'none'}</code>{' '}
        <Button variant="outline" type="button" onClick={() => setHidden([])}>
          Show all
        </Button>
      </p>
    </div>
  );
}
```

## Data labels

`series.labels` (or `{ position, format, angle, showZero }`) prints values
at the points; `format` is a preset (`'n0'`, `'c2'`, `'p1'`), a `{value}`
template or a function of the point.
`labels.render(ctx)` returns SVG content placed at the label anchor
(`<text>`, `<tspan>`s, an `<image>`), so custom labels stay in the drawing
and the export.

Smart labels: `labels.overlap` decides what a label that collides
with an earlier one does: `'hide'`, `'shiftY'` / `'shiftX'` (moved up to
three label sizes, inside the plot), `'rotate90'`, or `'none'` (default).
One collision pass runs over every series that sets it, earlier series
first, with the text-width table (identical on the server).
`labels.dedupe` drops a label that repeats the previous label of its
series.

## Markers

`series.markers` (`true` or `{ shape, size, filled }`) draws a symbol per
point. `series.renderMarker(ctx)` returns SVG content centered on each point
instead, for images (`<image href>`) or any custom shape:

```tsx
{ type: 'line', xField: 'month', yField: 'sales', markers: true, renderMarker: () => <image href="/pin.svg" x={-6} y={-6} width={12} height={12} /> }
```

## Badges and inline labels

`series.lastValue` draws the last value at the plot edge and
`series.inlineLabel` the series name at the end of the line.

## Annotations

`annotations={[{ x, y, content }]}` places any `ReactNode` at data
coordinates (`units: 'data'`, default) or pixels (`units: 'pixel'`), on the
axes named by `xAxis` / `yAxis`.

### Live demo: Titles, data labels, markers and annotations

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

A titled column chart with positioned, rotated and templated data labels and annotations, and a line chart with marker shapes, custom SVG markers and labels, smart label overlap, last-value badges and inline series labels.

`Demo.tsx`:

```tsx
'use client';

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

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug'];
const prices = months.map((month, i) => ({ month, coffee: 4.1 + ((i * 3) % 5) / 10, tea: 4.0 + ((i * 2) % 5) / 10, cocoa: 3.2 + i * 0.12 }));
const signups = months.map((month, i) => ({ month, signups: i === 3 ? 0 : 120 + ((i * 47) % 90) }));

type Position = NonNullable<ChartDataLabels['position']>;
type Overlap = NonNullable<ChartDataLabels['overlap']>;

export default function ChartLabelsMarkersDemo() {
  const [position, setPosition] = useState<Position>('top');
  const [angle, setAngle] = useState(0);
  const [showZero, setShowZero] = useState(true);
  const [overlap, setOverlap] = useState<Overlap>('shiftY');
  const [dedupe, setDedupe] = useState(false);
  const [badges, setBadges] = useState(true);
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Label position
          <Select aria-label="Label position" data={['outside', 'top', 'middle', 'bottom', 'auto']} value={position} onValueChange={(value) => value != null && setPosition(value as Position)} />
        </label>
        <label>
          Angle
          <Select aria-label="Angle" data={[{ value: 0, label: '0' }, { value: -45, label: '-45' }, { value: -90, label: '-90' }]} value={angle} onValueChange={(value) => value != null && setAngle(Number(value))} />
        </label>
        <Checkbox checked={showZero} onCheckedChange={(checked) => setShowZero(checked)}>
          showZero
        </Checkbox>
      </div>
      <Chart
        title="Sign-ups"
        subtitle="April had a site outage"
        data={signups}
        height={260}
        legend={false}
        annotations={[{ x: 'Apr', y: 60, content: <span className="demo-badge">Outage</span> }, { x: 128, y: 18, units: 'pixel', content: <span className="demo-badge" data-tone="info">Preliminary</span> }]}
        series={[
          {
            type: 'column',
            name: 'Sign-ups',
            xField: 'month',
            yField: 'signups',
            labels: { position, angle, showZero, format: '{value} users' },
          },
        ]}
      />
      <div className="demo-toolbar">
        <label>
          Label overlap
          <Select aria-label="Label overlap" data={['none', 'hide', 'shiftY', 'shiftX', 'rotate90']} value={overlap} onValueChange={(value) => value != null && setOverlap(value as Overlap)} />
        </label>
        <Checkbox checked={dedupe} onCheckedChange={(checked) => setDedupe(checked)}>
          dedupe
        </Checkbox>
        <Checkbox checked={badges} onCheckedChange={(checked) => setBadges(checked)}>
          Last value and inline labels
        </Checkbox>
      </div>
      <Chart
        title="Price per kilo"
        data={prices}
        height={300}
        legend={false}
        yAxis={{ format: 'c2' }}
        locale="en-US"
        series={[
          { type: 'line', name: 'Coffee', xField: 'month', yField: 'coffee', markers: { shape: 'diamond', size: 8 }, labels: { format: 'c1', overlap, dedupe }, lastValue: badges, inlineLabel: badges },
          { type: 'line', name: 'Tea', xField: 'month', yField: 'tea', markers: { shape: 'triangle', size: 8, filled: false }, labels: { format: 'c1', overlap, dedupe }, lastValue: badges ? { format: 'c2' } : false, inlineLabel: badges },
          {
            type: 'line',
            name: 'Cocoa',
            xField: 'month',
            yField: 'cocoa',
            // Custom SVG markers and labels rendered from functions.
            renderMarker: (p) => <rect x={-5} y={-5} width={10} height={10} rx={2} fill={p.color} />,
            labels: { position: 'bottom', render: (p) => <tspan fontStyle="italic">{p.index % 2 === 0 ? p.yText : ''}</tspan> },
            inlineLabel: badges,
          },
        ]}
      />
    </div>
  );
}
```

All of these are `Chart` props or `series` fields of
`@salmonui/charts/chart` (`ChartLegendOptions`, `ChartDataLabels`,
`ChartMarkers`, `ChartAnnotation` in the
[API reference](https://salmonui.dev/docs/reference/charts/chart)).
