# Layers (Chartist API)

> What chart() draws: lines, bars, pies, grids and labels, each a layer over the same data.

## axisGrid

*experimental*

```ts
function axisGrid(options?: AxisLayerOptions & { readonly background?: boolean }): Layer
```

Creates a layer that draws the grid lines of the named axes (default: all) in `g.ct-grids`, one `line.ct-grid` per tick. List it first, so the series draw over it.

Parameters:

- `options?: AxisLayerOptions & { readonly background?: boolean }` The axes to draw and their classes; `background` adds a   `rect.ct-grid-background` over the chart area, behind the lines.

```ts
import {
  autoScaleAxis,
  axisGrid,
  axisLabels,
  cartesianAxes,
  chart,
  line,
  stepAxis
} from 'chartist';

const hours = ['6am', '9am', '12pm', '3pm', '6pm'];

chart('#chart', {
  data: { labels: hours, series: [[12, 17, 23, 21, 15]] },
  axes: cartesianAxes([
    { id: 'time', side: 'bottom', type: stepAxis(), ticks: hours },
    { id: 'celsius', side: 'left', type: autoScaleAxis() }
  ]),
  // Horizontal lines only, on a background rect.
  layers: [
    axisGrid({ axes: ['celsius'], background: true }),
    line(),
    axisLabels()
  ]
});
```

## axisLabels

*experimental*

```ts
function axisLabels(options?: AxisLabelsOptions): Layer
```

Creates a layer that draws the labels of the named axes (default: all) in `g.ct-labels`, each on its axis's side. Axes on the same side stack outward, each in its own `offset`. List it last, so the labels draw over the series.

Labels are HTML in a `foreignObject` (as in 1.x) or SVG `text`: the chart's `labels` option decides, unless the layer sets its own.

Parameters:

- `options?: AxisLabelsOptions`

```ts
import {
  autoScaleAxis,
  axisGrid,
  axisLabels,
  cartesianAxes,
  chart,
  line,
  stepAxis
} from 'chartist';

const weeks = ['W1', 'W2', 'W3', 'W4'];

chart('#chart', {
  data: { labels: weeks, series: [[3, 5, 4, 8]] },
  axes: cartesianAxes([
    { id: 'week', side: 'bottom', type: stepAxis(), ticks: weeks },
    { id: 'km', side: 'left', type: autoScaleAxis(), low: 0 }
  ]),
  layers: [
    axisGrid(),
    line(),
    // SVG text instead of HTML, e.g. to export the SVG.
    axisLabels({ labels: 'svg' })
  ]
});
```

## bar

*experimental*

```ts
function bar(options?: BarLayerOptions): Layer
```

Creates a layer that draws series as bars, in the markup of the 1.x bar chart (`g.ct-series` with a `line.ct-bar` per value). The label axis is X (Y with `horizontalBars`), the value axis the other one; both come from [`cartesianAxes`](https://chartist.dev/api/scales/#cartesianAxes).

Bars grow from zero on the value axis, so keep zero on it: `low: 0`, or `referenceValue: 0`. On a step axis they sit in the middle of each step.

Parameters:

- `options?: BarLayerOptions`

```ts
import {
  autoScaleAxis,
  axisGrid,
  axisLabels,
  bar,
  cartesianAxes,
  chart,
  stepAxis
} from 'chartist';

const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];

chart('#chart', {
  data: {
    labels: quarters,
    series: [
      [800, 1200, 1400, 1300],
      [200, 400, 500, 300]
    ]
  },
  axes: cartesianAxes([
    { id: 'quarter', side: 'bottom', type: stepAxis(), ticks: quarters },
    { id: 'sales', side: 'left', type: autoScaleAxis(), low: 0 }
  ]),
  layers: [axisGrid(), bar({ seriesBarDistance: 12 }), axisLabels()],
  className: 'ct-chart-bar'
});
```

## line

*experimental*

```ts
function line(options?: LineLayerOptions): Layer
```

Creates a layer that draws series as lines, with points and optional areas, in the markup of the 1.x line chart (`g.ct-series` with `path.ct-line`, `line.ct-point` and `path.ct-area`). It needs an X and a Y axis, from [`cartesianAxes`](https://chartist.dev/api/scales/#cartesianAxes).

Parameters:

- `options?: LineLayerOptions`

```ts
import {
  autoScaleAxis,
  axisGrid,
  axisLabels,
  cartesianAxes,
  chart,
  line,
  stepAxis
} from 'chartist';

const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];

chart('#chart', {
  data: {
    labels: days,
    series: [
      { name: 'visits', data: [12, 9, 7, 8, 5] },
      { name: 'sales', data: [2, 1, 3.5, 7, 3] }
    ]
  },
  axes: cartesianAxes([
    { id: 'day', side: 'bottom', type: stepAxis(), ticks: days },
    { id: 'count', side: 'left', type: autoScaleAxis(), low: 0 }
  ]),
  layers: [
    axisGrid(),
    line({ showArea: true, overrides: { sales: { showArea: false } } }),
    axisLabels()
  ]
});
```

## determineAnchorPosition

```ts
function determineAnchorPosition(center: Dot, label: Dot, direction: LabelDirection): AnchorPosition
```

The 1.x label anchor: `start`, `middle` or `end` by side and direction.

Parameters:

- `center: Dot`
- `label: Dot`
- `direction: LabelDirection`

## pie

*experimental*

```ts
function pie(options?: PieLayerOptions): Layer
```

Creates a layer that draws a flat series as pie or donut slices with labels, in the markup of the 1.x pie chart (a `g.ct-series` per slice, then a group of `text.ct-label`). It draws in polar coordinates, so the chart needs `coordinates: 'polar'` and no axes. With several series, it draws one slice per series, from each series' first value.

Parameters:

- `options?: PieLayerOptions`

```ts
import { chart, pie } from 'chartist';

chart('#chart', {
  data: {
    labels: ['Rent', 'Food', 'Fun'],
    series: [50, 30, 20]
  },
  coordinates: 'polar',
  layers: [pie({ donut: true, donutWidth: 30 })],
  className: 'ct-chart-donut'
});
```

## AxisLayerClassNames

```ts
interface AxisLayerClassNames extends AxisClassNames
```

The classes [`axisGrid`](https://chartist.dev/api/layers/#axisGrid) and [`axisLabels`](https://chartist.dev/api/layers/#axisLabels) give what they draw. The defaults are the 1.x classes, so 1.x CSS applies.

Properties:

- `gridGroup: string` The group of all grid lines (`ct-grids`).
- `labelGroup: string` The group of all labels (`ct-labels`).
- `gridBackground: string` The rect behind the grid, with `background: true` (`ct-grid-background`).
- `grid: string` Each grid line (`ct-grid`).
- `label: string` Each label (`ct-label`).
- `horizontal: string` Grid lines and labels of an X axis (`ct-horizontal`).
- `vertical: string` Grid lines and labels of a Y axis (`ct-vertical`).
- `start: string` Labels of an axis at the top or left (`ct-start`).
- `end: string` Labels of an axis at the bottom or right (`ct-end`).

## AxisLayerOptions

*experimental*

```ts
interface AxisLayerOptions
```

The options of [`axisGrid`](https://chartist.dev/api/layers/#axisGrid) and [`axisLabels`](https://chartist.dev/api/layers/#axisLabels).

Properties:

- `axes?: readonly string[]` Axis ids to draw; default: all axes, in declaration order. An unknown id throws.
- `classNames?: Partial<AxisLayerClassNames>` Replaces some of the classes; the others keep their 1.x names.

## AxisLabelsOptions

*experimental*

```ts
interface AxisLabelsOptions extends AxisLayerOptions
```

The options of [`axisLabels`](https://chartist.dev/api/layers/#axisLabels): those of every axis layer, plus how the labels are drawn.

Properties:

- `axes?: readonly string[]` Axis ids to draw; default: all axes, in declaration order. An unknown id throws.
- `classNames?: Partial<AxisLayerClassNames>` Replaces some of the classes; the others keep their 1.x names.
- `labels?: LabelMode` HTML (`foreignObject`) or SVG `text`; default: the chart's mode.
- `align?: Partial<LabelAlign>` Aligns SVG text labels in their box, on every axis of the layer; default: as the 1.x CSS aligns HTML labels. HTML labels ignore it (align them with CSS).

## BarLayerOptions

*experimental*

```ts
interface BarLayerOptions
```

The options of the [`bar`](https://chartist.dev/api/layers/#bar) layer. Without them, it draws the bars of each label side by side, 15 px apart, on the first X and Y axis.

Properties:

- `series?: readonly (string | number)[]` Series to draw, by index or name; default: all series.
- `x?: string` The id of the X axis to draw on; default: the first X axis.
- `y?: string` The id of the Y axis to draw on; default: the first Y axis.
- `horizontalBars?: boolean` Values on the X axis, labels on the Y axis.
- `stackBars?: boolean` Stacks the bars of a label on each other; `stackMode` says how. The value axis grows to fit the stacks (see [`Layer.extent`](https://chartist.dev/api/layers/#Layer.extent)).
- `stackMode?: boolean | 'accumulate' | 'accumulate-relative' | 'overlap'` How stacked bars stack: `accumulate` (default) adds each value to the ones before, `accumulate-relative` stacks positive values up and negative values down from zero, and `overlap` (or `true`) draws every bar from zero, on top of each other.
- `seriesBarDistance?: number` Distance between the bars of different series, in px.
- `distributeSeries?: boolean` One series per value of a flat series (1.x `distributeSeries`).
- `reverseData?: boolean` Draws the series in reverse order (1.x `reverseData`). Can't be combined with `series`.
- `classNames?: { … }` Replaces the classes of what the layer draws: `series` (`ct-series`) and `bar` (`ct-bar`).

## LineSeriesOptions

```ts
interface LineSeriesOptions
```

The line options you can set per series: in the `overrides` of [`line`](https://chartist.dev/api/layers/#line), or the `series` option of `lineChart`.

Properties:

- `lineSmooth?: boolean | LineInterpolation` How a line runs between its points: `true` smooths it with `Interpolation.monotoneCubic`, `false` draws straight segments (`Interpolation.none`), or pass an interpolation such as `Interpolation.cardinal()`, `Interpolation.step()` or your own.
- `showPoint?: boolean` Draws a point at each value.
- `showLine?: boolean` Draws the lines.
- `showArea?: boolean` Fills the area between each line and `areaBase`.
- `areaBase?: number` The value the areas close at, usually 0. It's kept within the Y axis range.

## LineLayerOptions

*experimental*

```ts
interface LineLayerOptions extends LineSeriesOptions
```

The options of the [`line`](https://chartist.dev/api/layers/#line) layer. Without them, it draws every series as a smooth line with points and no area, on the first X and Y axis.

Properties:

- `lineSmooth?: boolean | LineInterpolation` How a line runs between its points: `true` smooths it with `Interpolation.monotoneCubic`, `false` draws straight segments (`Interpolation.none`), or pass an interpolation such as `Interpolation.cardinal()`, `Interpolation.step()` or your own.
- `showPoint?: boolean` Draws a point at each value.
- `showLine?: boolean` Draws the lines.
- `showArea?: boolean` Fills the area between each line and `areaBase`.
- `areaBase?: number` The value the areas close at, usually 0. It's kept within the Y axis range.
- `series?: readonly (string | number)[]` Series to draw, by index or name; default: all series.
- `x?: string` The id of the X axis to draw on; default: the first X axis.
- `y?: string` The id of the Y axis to draw on; default: the first Y axis.
- `align?: 'center' | 'start'` Point position on a step axis: `start` of each step (1.x) or its `center`, where bars are centered.
- `overrides?: Readonly<Record<string, LineSeriesOptions>>` Option overrides per series name (the 1.x `series` option).
- `reverseData?: boolean` Draws the series in reverse order (1.x `reverseData`). Can't be combined with `series`.
- `classNames?: { … }` Replaces the classes of what the layer draws: `series` (`ct-series`), `line` (`ct-line`), `point` (`ct-point`) and `area` (`ct-area`).

## PieLayerOptions

*experimental*

```ts
interface PieLayerOptions
```

The options of the [`pie`](https://chartist.dev/api/layers/#pie) layer. Without them, it draws a filled pie from the top, with a label halfway out on each slice.

Properties:

- `startAngle?: number` Where the first slice starts, in degrees clockwise from the top.
- `total?: number` Fixed total; slices are relative to it (gauges). Defaults to the sum.
- `donut?: boolean` Draws a donut: rings instead of filled slices.
- `donutWidth?: string | number` Donut ring width in px, or a share of the radius (`'25%'`). Without it, the stylesheet sets the width (`--ct-donut-width`, 60px by default), and in the browser the ring is laid out for the width the stylesheet gives a slice. Without a DOM (`toScene()`, `renderToString()`), it's laid out for 60 px, so set `donutWidth` there if the page's CSS draws another width.
- `showLabel?: boolean` Draws a label for each slice; on by default.
- `labelOffset?: number` Moves the labels away from the center (positive) or toward it (negative), in px.
- `labelPosition?: 'center' | 'inside' | 'outside'` Where labels go: `inside` (the default: halfway out on a pie, on the middle of a donut's ring), `outside` (at the outer edge) or `center` (in the middle; move them with `labelOffset`).
- `labelInterpolationFnc?: (value: Label, index: number) => Label | null | undefined` Formats a slice's label: its entry in `labels`, or else its value.
- `labelDirection?: LabelDirection` Which way labels anchor: `neutral` (the default), `explode` (away from the center, for labels outside the pie) or `implode` (toward it).
- `ignoreEmptyValues?: boolean` Leaves out the slices and labels of zero values.
- `preventOverlappingLabelOffset?: number` Shifts labels that would overlap another one by this many px, up and left, judging the overlap by the length of the drawn label text.
- `classNames?: { … }` Replaces the classes of what the layer draws: `series` (`ct-series`), `slicePie` (`ct-slice-pie`), `sliceDonut` (`ct-slice-donut`) and `label` (`ct-label`).

## Coordinates

```ts
type Coordinates = 'cartesian' | 'polar'
```

The coordinate system a chart draws in: `cartesian` places values on X and Y axes (lines, bars), `polar` around a center (pies and donuts).

## LayerContext

```ts
interface LayerContext
```

What a layer's `compose` gets: the data it draws, the area to draw in, the axes and ways to measure text and styles.

Properties:

- `data: PreparedData` The prepared data; only the layer's series when it selects some.
- `area: Area` The drawing area, in px in the SVG.
- `padding: ChartPadding` The chart's padding, in px.
- `layerIndex: number` The layer's index in the chart's `layers`; part of its nodes' keys.
- `coordinates: Coordinates` The chart's coordinate system.
- `measureText: MeasureText` Measures text with the renderer's metrics (in the browser, with the page's fonts and the chart's classes), for layers that lay out labels.
- `measureStyle?: MeasureStyle` Reads computed styles with the renderer (in the browser, with the page's CSS and the chart's classes), for layout that depends on the stylesheet, such as a donut's ring width. Absent without a DOM.
- `axes: ChartAxes` Axes created after `layout`, when the chart has axes.
- `normalized?: NormalizedChartData` The data as the axes see it, when the chart has axes.
- `seriesIndexes?: readonly number[]` Chart-wide index of each series in `data` (a layer may select a subset of the series). Absent when the layer draws all series.
- `labels: LabelMode` How label layers draw labels: chart option, else the renderer's.

## ExtentContext

*experimental*

```ts
interface ExtentContext
```

What a layer's `extent` gets: its series as the axes see them, and the ids of the axes it draws on.

Properties:

- `normalized: NormalizedChartData` The layer's series, normalized as for the axes (`{ x, y }` values or holes); only the layer's series when it selects some.
- `axes: { … }` The ids of the X and Y axis the layer draws on.

## Layer

*experimental*

```ts
interface Layer
```

A layer renders series into the chart area. Built-in and custom layers use the same contract.

Properties:

- `type: string` Name used in error messages, e.g. `line`.
- `chartType?: string` The kind of chart the layer draws, when `type` doesn't say it: a [`chart`](https://chartist.dev/api/chart/#chart) without `className` gets `ct-chart-bar` if a layer is a `bar`, else `ct-chart-pie` or `ct-chart-donut` for a `pie` or `donut`, else `ct-chart-line`. Without it, `type` counts.
- `coordinates: readonly Coordinates[]` Coordinate systems the layer can draw in.
- `axes?: { … }` Axis ids to draw on; default: the first X and the first Y axis.
- `series?: readonly (string | number)[]` Series to draw, by index or name; default: all series.
- `extent?: (context: ExtentContext) => Readonly<Record<string, AxisExtent>>` Reports the range of values the layer needs on its axes beyond the values themselves, by axis id, such as the sums of stacked bars. Scale axes include it in the range they fit to the data (an axis's own `low` and `high` still win); on an axis several layers report a range for, the axis covers them all. Runs before the axes are created, on every layout.
- `compose: (context: LayerContext) => readonly SceneNode[]` Draws the layer: returns its top-level nodes, usually one `series` group per series. The pipeline keys their data nodes and passes every node with a role through the `compose` listeners.
