> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Chart

Draw any chart that [TanStack Charts](https://tanstack.com/charts) can describe, with native elements. Describe the chart with TanStack's `defineChart`, and pass it to `<ui-chart>`. It draws the chart, and handles touch, tooltips, screen readers, pan and zoom, and dark mode.

For one series, the [Line](/dolan/line-chart.md), [Area](/dolan/area-chart.md), [Bar](/dolan/bar-chart.md), [Scatter](/dolan/scatter-chart.md) and [Candlestick](/dolan/candlestick-chart.md) presets are quicker. Use `<ui-chart>` for several series, overlays, or marks the presets don't offer.


## Installation

```bash
npx @blotch/dolan add chart
```

```typescript
import { UiChart, tooltip } from '../components/ui/chart';
```

`dolan add` also installs the npm packages the chart imports: `@tanstack/charts`, `d3-shape` and `d3-shape`'s types, `@types/d3-shape`. If that install fails, it prints the command to run yourself.

## Usage

```typescript title="src/app/revenue.ts"
import { Component, computed, input } from '@angular/core';
import { scaleBand } from '@tanstack/charts/scales/band';
import { scaleLinear } from '@tanstack/charts/scales/linear';
import { barY, defineChart } from '@tanstack/charts/universal';
import { UiChart, tooltip } from '../components/ui/chart';

type Sale = { month: string; value: number };

@Component({
  selector: 'app-revenue',
  imports: [UiChart],
  template: `<ui-chart [definition]="definition()" label="Monthly revenue" />`,
})
export class Revenue {
  readonly sales = input.required<readonly Sale[]>();

  protected readonly definition = computed(() =>
    defineChart({
      marks: [barY(this.sales(), { x: 'month', y: 'value' })],
      scales: {
        x: { scale: () => scaleBand().padding(0.2) },
        y: { scale: scaleLinear, nice: true, grid: true },
      },
      tooltip,
    }),
  );
}
```

- A **definition** maps fields of your data to a mark's channels (`x`, `y`, `fill`, …) and configures the scales.
- Import `defineChart` and the marks from `@tanstack/charts/universal`, the entry point without browser code. Scales come from `@tanstack/charts/scales/*`.
- The [TanStack Charts docs](https://tanstack.com/charts) cover every mark, scale and option. Don't use `@tanstack/charts/angular`: it draws into the browser DOM, which [Lynx](/guide/glossary.md#lynx) doesn't have.

### Data from a signal

The example builds the definition in a `computed()`, so the chart redraws when the data changes. Bind it with `[definition]="definition()"`.

A chart whose data never changes can take a plain field: `[definition]="definition"`.

### Size

Without `width` or `height`, the chart fills its container's width and is 200px tall. It redraws when its layout changes, such as on rotation. Set the height with a class, or fix either side in px:

```angular-html
<ui-chart [definition]="definition" class="h-64" />
<ui-chart [definition]="definition" [width]="320" [height]="180" />
```

### Series and marks

Put every series in one array and split them with the `z` channel. Each series takes the next palette color, `var(--chart-1)` to `var(--chart-5)`.

```typescript
const revenue = [
  { month: 1, series: 'This year', value: 12 },
  { month: 1, series: 'Last year', value: 8 },
  // ...
];

protected readonly definition = defineChart({
  marks: [lineY(revenue, { x: 'month', y: 'value', z: 'series' })],
  scales: {
    x: { scale: scaleLinear },
    y: { scale: scaleLinear, nice: true, grid: true },
  },
  focus: 'group-x',
  tooltip,
});
```

- `focus: 'group-x'` focuses every series at the touched x value, so the tooltip lists them together.
- If each series is its own array, give each a mark with a fixed `z`: `lineY(lastYear, { x: 'month', y: 'value', z: () => 'Last year' })`.
- For a legend, lay out `<view>` swatches next to the chart. The `bg-chart-1` to `bg-chart-5` classes match the series colors.

List several marks to layer them. They share the scales, and each draws over the ones before it:

```typescript
marks: [
  barY(revenue, { x: 'month', y: 'value', fill: 'var(--primary)', radius: 4 }),
  ruleY([60], { stroke: 'var(--destructive)', strokeOpacity: 1, strokeDasharray: '4 4' }),
],
```

- Rules don't take focus, so a touch still lands on the bars.
- For a trend line, use `linearRegressionY(points, { x: 'x', y: 'y', ci: 0 })` before a `dot` mark. `ci: 0` leaves out the confidence band.
- For smooth lines and areas, pass `curve: d3Curve(curveMonotoneX)`, with `curveMonotoneX` from `d3-shape`. It never overshoots the data.

To keep a preset's axes and styling, start from its definition function and add marks. Each preset exports one, such as `lineChartDefinition`:

```typescript
const base = lineChartDefinition({ data: revenue, smooth: true, yMin: 0 });

protected readonly withTarget = defineChart({
  ...base,
  marks: [...base.marks, ruleY([20], { stroke: 'var(--muted-foreground)' })],
});
```

### Tooltips

Put `tooltip` in the definition to show a tooltip for the touched point. Without it, a touch still focuses points and emits `focusChange`.

- Import `tooltip` from the chart component, not from `@tanstack/charts/tooltip`, which is built from browser DOM elements. This one draws native views.
- Pass TanStack's tooltip options with `use`, as in `tooltip: { use: tooltip, sticky: false }`. See [`tooltip`](#tooltip) for the options it reads.

To lay out the tooltip yourself, put an `<ng-template uiChartTooltip>` inside the chart. The chart still places the tooltip and draws its card.

```angular-html
<ui-chart [definition]="definition" label="Monthly revenue">
  <ng-template uiChartTooltip let-tooltip>
    <text class="text-sm font-semibold text-card-foreground">
      {{ tooltip.primaryPoint.yValue }}k
    </text>
  </ng-template>
</ui-chart>
```

- **Import `UiChartTooltip` and `LYNX_ELEMENTS`** in your component.
- **The template gets a [`UiChartTooltipContext`](#uicharttooltip).** A point's `datum` is typed `unknown` there, so read its fields in a component method that casts it.

### Touch, selection and zoom

- **Scrub:** touch and drag. Focus follows the nearest point, which the chart highlights and shows in the tooltip.
- **Tap:** emits the point from `pointSelect` and pins the tooltip. While it's pinned, touches don't move focus. The next tap unpins it. With `sticky: false`, a tap doesn't pin.
- If a scrolling parent takes over the touch, focus clears. A pinned tooltip stays.

```typescript
// <ui-chart [definition]="definition" (pointSelect)="onSelect($event)" />
protected onSelect(point: ChartPoint | null): void {
  this.selected.set(point ? (point.datum as Sale) : null);
}
```

- **`ChartPoint` comes from `@tanstack/charts/types`.** Its `datum` is the row you passed to the mark.
- **Both outputs fire inside the touch,** so they can change signals or navigate, as a tap handler can.
- **A TanStack `selection` controller** in the definition is told about each tap.

By default, a touch focuses the nearest point within 48px (`maxFocusDistance`). Set `focus` in the definition to change that: `'nearest-x'` prefers the closest x value, `'group-x'` takes every series at that x, and `false` turns focus off.

#### Pan and zoom

Set `zoomable` to let users drag to pan, with **+**, **−** and **1:1** (reset) buttons in the top-right corner.

```angular-html
<ui-chart [definition]="definition" zoomable zoomAxes="x" />
```

- Zoom works on continuous axes in `scales.x` and `scales.y`, such as `scaleLinear`. Band and point scales don't zoom, and an axis missing from `scales` stays fixed.
- On a zoomable chart, a drag pans instead of moving focus. A short tap still selects a point.
- There's no pinch to zoom, because Lynx has no native pinch handler yet.
- For your own controls, set `showZoomControls` to `false` and call `zoomIn()`, `zoomOut()` or `resetZoom()` from a `viewChild.required(UiChart)`.
- Zooming doesn't touch your data or definition. The chart sets TanStack's `viewport` option on the zoomed scales.

### Theming and dark mode

Give marks theme colors as CSS variables, such as `var(--primary)` or the palette `var(--chart-1)` to `var(--chart-5)`. They switch with dark mode.

- **Fixed colors** such as `#2563eb` stay the same in both modes.
- **Marks without a color** take the palette in order.
- **Text and gridlines** follow `var(--foreground)`.

Charts follow the app's appearance, as the [theme](/dolan/theming.md#dark-mode) and the icons do. To change a theme color, or keep one chart light or dark, see [Chart Colors](/dolan/chart-colors.md).

## API

### UiChart

| Input              | Type                            | Default                                                                             | Description                                                               |
| ------------------ | ------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| `definition`       | `ChartDefinition`               | Required                                                                            | The chart to draw: what `defineChart` returns.                            |
| `width`            | `number`                        | _fills container_                                                                   | Fixed width in px.                                                        |
| `height`           | `number`                        | `200`                                                                               | Fixed height in px. Without it, 200px or a height class.                  |
| `label`            | `string`                        | `'Chart'`                                                                           | What a screen reader announces for the chart.                             |
| `colorScheme`      | `'light' \| 'dark' \| 'system'` | _from [`provideChartTheme`](/dolan/chart-colors.md#providecharttheme)_ (`'system'`) | Which color table the marks use. `'system'` follows the app's appearance. |
| `zoomable`         | `boolean`                       | `false`                                                                             | Drag to pan, with zoom buttons.                                           |
| `zoomAxes`         | `'x' \| 'y' \| 'xy'`            | `'xy'`                                                                              | Which axes pan and zoom.                                                  |
| `showZoomControls` | `boolean`                       | `true`                                                                              | Show the +/−/1:1 buttons when zoomable.                                   |
| `minZoom`          | `number`                        | `1`                                                                                 | Smallest zoom. `1` shows all the data.                                    |
| `maxZoom`          | `number`                        | `8`                                                                                 | Largest zoom.                                                             |
| `zoomStep`         | `number`                        | `1.4`                                                                               | Zoom factor per button press or method call.                              |
| `class`            | `string`                        | `''`                                                                                | Extra Tailwind classes for the chart's root view.                         |

| Output        | Type                 | Description                                                                                    |
| ------------- | -------------------- | ---------------------------------------------------------------------------------------------- |
| `focusChange` | `ChartPoint \| null` | The focused point (first of a focused group) each time focus moves. `null` when it clears.     |
| `pointSelect` | `ChartPoint \| null` | The point a tap landed on, or `null` for empty space. Emits on every tap, including unpinning. |

| Method        | Description                                                      |
| ------------- | ---------------------------------------------------------------- |
| `zoomIn()`    | Zooms in by `zoomStep` around the center of the visible window.  |
| `zoomOut()`   | Zooms out by `zoomStep` around the center of the visible window. |
| `resetZoom()` | Shows the whole chart again.                                     |
| `dismiss()`   | Clears focus and unpins the tooltip.                             |

A `ChartPoint` has `datum` (your row), `xValue`, `yValue`, `groupLabel` (the series name), `x` and `y` (its position in px), and `color`.

### UiChartTooltip

`<ng-template uiChartTooltip let-tooltip>` replaces the tooltip's contents. Its context is a `UiChartTooltipContext`:

| Property       | Type                            | Description                                     |
| -------------- | ------------------------------- | ----------------------------------------------- |
| `points`       | `readonly ChartPoint[]`         | The focused points, in the tooltip's row order. |
| `primaryPoint` | `ChartPoint`                    | The touched point, whatever the row order.      |
| `content`      | `ChartTooltipContent \| string` | The default title and rows, already formatted.  |
| `pinned`       | `boolean`                       | Whether a tap has pinned the tooltip.           |
| `dismiss`      | `() => void`                    | Clears focus and unpins the tooltip.            |

### tooltip

The tooltip token: `tooltip` alone, or `{ use: tooltip, ...options }`. `<ui-chart>` reads the TanStack options below. Options that style the browser tooltip's DOM, such as `className` and `portal`, have no effect.

| Option        | Default     | Description                                                            |
| ------------- | ----------- | ---------------------------------------------------------------------- |
| `items`       | x and y     | Rows for a single focused point: channels, datum fields, or text.      |
| `content`     | _automatic_ | A function that returns the title and rows.                            |
| `format`      | —           | A function that returns text for the primary point, instead of rows.   |
| `formatGroup` | —           | A function that returns text for the whole focused group.              |
| `sort`        | `'visual'`  | Row order when several points have focus.                              |
| `anchor`      | `'point'`   | What the tooltip follows: `'point'`, `'pointer'`, `'group-center'`, …. |
| `placement`   | `'auto'`    | Side of the anchor, or a list to try in order. Kept inside the chart.  |
| `offset`      | `10`        | Gap between the anchor and the tooltip, in px.                         |
| `sticky`      | `true`      | A tap pins the tooltip until the next tap.                             |
| `visibility`  | `'focus'`   | `'pinned'` shows the tooltip only once a tap pins it.                  |

:::details Migrating from the old chart components
`<ui-cartesian-chart>` and its `<ui-*-series>` children are gone, and so is the `ChartPoint` type from `cartesian-chart`.

- **Single-series charts keep their preset,** which now fills its container's width (it was 320px).
- **Use `XYDatum` and `CandlestickDatum`** for the point types.
- **Set a color scheme** to match how your app switches `.dark`.
- **Pinch to zoom is gone.**
- **Several series move to `<ui-chart>`,** with one mark per series:

| Before                    | After                                                                  |
| ------------------------- | ---------------------------------------------------------------------- |
| `<ui-line-series>`        | `lineY`, plus `dot` for the dots.                                      |
| `<ui-area-series>`        | `areaY` with `y1` set to the baseline, plus `lineY`.                   |
| `<ui-bar-series>`         | `barY` for category x values, `rect` for numbers.                      |
| `<ui-scatter-series>`     | `dot`.                                                                 |
| `<ui-candlestick-series>` | The marks of `candlestickChartDefinition` (`link` and `rect`).         |
| `xDomain` / `yDomain`     | `scales.x` / `scales.y` with `scale: () => scaleLinear().domain([…])`. |
| `xAxisLabel`, `xTicks`    | `axis: { label: '…', ticks: { values: […] } }` on the scale.           |
| `(pointTap)`              | `(pointSelect)` on `<ui-chart>`. The item is `point.datum`.            |

:::

## Accessibility

The chart is one accessibility element. Set `label` on every chart to say what it shows. The default is `'Chart'`.

- A screen reader announces the `label`, then the focused point's series, x value and y value.
- Two custom actions, **Next point** and **Previous point**, step focus through the points and show the tooltip.

## Related

- [Line Chart](/dolan/line-chart.md), [Area Chart](/dolan/area-chart.md), [Bar Chart](/dolan/bar-chart.md), [Scatter Chart](/dolan/scatter-chart.md) and [Candlestick Chart](/dolan/candlestick-chart.md): presets for one series
- [Chart Colors](/dolan/chart-colors.md): change the colors, or pin a chart to light or dark
- [Theming](/dolan/theming.md): the theme colors marks can use
- [Dark mode](/guide/dark-mode.md): switch the app's `.dark` class
- [`<svg>`](/api/elements/svg.md): the element the marks are drawn with
