function axisGrid(options?: AxisLayerOptions & { readonly background?: boolean }): LayerCreates 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;
backgroundadds arect.ct-grid-backgroundover the chart area, behind the lines.
Example
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()
]
});function axisLabels(options?: AxisLabelsOptions): LayerCreates 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={}
Example
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' })
]
});function band(options: BandOptions): LayerCreates a layer that fills the area between a low and a high edge (g.ct-band with a path.ct-band-area per piece; the band breaks at holes). Each edge is a constant value, values of its own (one per label) or a series, or series names a group and the band covers their minimum to their maximum at each value index. Constants and own values widen the Y axis to include them. On a preset, add it to layers.below to draw it behind the series; in a composed chart, list it before the series layers. It needs an X and a Y axis, from cartesianAxes or a preset's.
Parameters
optionsBandOptions
Example
import { band, lineChart } from 'chartist';
lineChart(
'#chart',
{
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
series: [{ name: 'visits', data: [12, 9, 7, 8, 5] }]
},
{ low: 0, layers: { below: [band({ low: 6, high: 10, mark: true })] } }
);function bar(options?: BarLayerOptions): LayerCreates 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.
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={}
Example
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'
});function line(options?: LineLayerOptions): LayerCreates 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.
Parameters
options?LineLayerOptions={}
Example
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()
]
});function determineAnchorPosition(center: Dot, label: Dot, direction: LabelDirection): AnchorPositionThe 1.x label anchor: start, middle or end by side and direction.
Parameters
centerDotlabelDotdirectionLabelDirection
function pie(options?: PieLayerOptions): LayerCreates 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={}
Example
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'
});interface AxisLayerClassNames extends AxisClassNamesThe classes axisGrid and axisLabels give what they draw. The defaults are the 1.x classes, so 1.x CSS applies.
Properties
readonly gridGroupstringThe group of all grid lines (
ct-grids).readonly labelGroupstringThe group of all labels (
ct-labels).readonly gridBackgroundstringThe rect behind the grid, with
background: true(ct-grid-background).readonly gridstringEach grid line (
ct-grid).readonly labelstringEach label (
ct-label).readonly horizontalstringGrid lines and labels of an X axis (
ct-horizontal).readonly verticalstringGrid lines and labels of a Y axis (
ct-vertical).readonly startstringLabels of an axis at the top or left (
ct-start).readonly endstringLabels of an axis at the bottom or right (
ct-end).readonly gridMinor?stringGrid lines at an axis's
minorTicks, next to thegridclass (ct-grid-minor).
interface AxisLayerOptionsThe options of axisGrid and axisLabels.
Properties
readonly axes?readonly string[]Axis ids to draw; default: all axes, in declaration order. An unknown id throws.
readonly classNames?Partial<AxisLayerClassNames>Replaces some of the classes; the others keep their 1.x names.
interface AxisLabelsOptions extends AxisLayerOptionsThe options of axisLabels: those of every axis layer, plus how the labels are drawn.
Properties
readonly axes?readonly string[]Axis ids to draw; default: all axes, in declaration order. An unknown id throws.
readonly classNames?Partial<AxisLayerClassNames>Replaces some of the classes; the others keep their 1.x names.
readonly labels?LabelModeHTML (
foreignObject) or SVGtext; default: the chart's mode.readonly 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. An axis's own
labelAlignwins over it. HTML labels ignore it (align them with CSS).
type BandEdgeValue = number | { readonly x: number; readonly y: number } | null | undefinedA value of a band edge given as values: a number, { x, y } on a scale X axis, or null for a hole.
type BandEdgeOption = number | readonly BandEdgeValue[] | string | { readonly series: number | string }An edge of a band: a constant value, values of its own (one per label, like a series that isn't in the data), a series by name, or a series by index or name as { series }.
interface BandOptionsThe options of the band layer: low and high edges, or a series group.
Properties
readonly low?BandEdgeOptionThe low edge: a constant value, values or a series.
readonly high?BandEdgeOptionThe high edge: a constant value, values or a series.
readonly series?readonly (string | number)[]A group of series, by index or name: the band covers their minimum to their maximum at each value index. Can't be combined with
lowandhigh.readonly x?stringThe id of the X axis to draw on; default: the first X axis.
readonly y?stringThe id of the Y axis to draw on; default: the first Y axis.
readonly lineSmooth?boolean | LineInterpolationHow the edges run between values, as
lineSmoothof the line layer:truesmooths them withInterpolation.monotoneCubic,falsedraws straight segments, or pass an interpolation.readonly align?'center' | 'start'Edge position on a step axis:
startof each step (1.x) or itscenter, where bars are centered.readonly className?stringA class added to the band's group, such as
ct-series-cfor a color.readonly mark?booleanGives the points and bars of every layer
ct-in-bandwhen their value at their value index lies between the band's edges (edges included), elsect-out-band. The value isy, orxwhen a value has noy(the bars of a horizontal bar chart). Nodes at an index where the band has a hole are left alone.readonly classNames?{ readonly band?: string; readonly area?: string; readonly inBand?: string; readonly outBand?: string }Replaces the classes of what the layer draws and marks:
band(ct-band),area(ct-band-area),inBand(ct-in-band) andoutBand(ct-out-band).
interface BarLayerOptionsThe options of the 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
readonly series?readonly (string | number)[]Series to draw, by index or name; default: all series.
readonly x?stringThe id of the X axis to draw on; default: the first X axis.
readonly y?stringThe id of the Y axis to draw on; default: the first Y axis.
readonly horizontalBars?booleanValues on the X axis, labels on the Y axis.
readonly stackBars?booleanStacks the bars of a label on each other;
stackModesays how. The value axis grows to fit the stacks (seeLayer.extent).readonly stackMode?boolean | 'accumulate' | 'accumulate-relative' | 'overlap'How stacked bars stack:
accumulate(default) adds each value to the ones before,accumulate-relativestacks positive values up and negative values down from zero, andoverlap(ortrue) draws every bar from zero, on top of each other.readonly seriesBarDistance?numberDistance between the bars of different series, in px.
readonly offset?numberMoves all bars of the layer along the label axis, in px: to the right for vertical bars, down for horizontal bars (negative values move them the other way). Two stacked bar layers with opposite offsets draw grouped stacks.
readonly distributeSeries?booleanOne series per value of a flat series (1.x
distributeSeries).readonly reverseData?booleanDraws the series in reverse order (1.x
reverseData). Can't be combined withseries.readonly classNames?{ readonly series?: string; readonly bar?: string }Replaces the classes of what the layer draws:
series(ct-series) andbar(ct-bar).
interface LineSeriesOptionsThe line options you can set per series: in the overrides of line, or the series option of lineChart.
Properties
readonly lineSmooth?boolean | LineInterpolationHow a line runs between its points:
truesmooths it withInterpolation.monotoneCubic,falsedraws straight segments (Interpolation.none), or pass an interpolation such asInterpolation.cardinal(),Interpolation.step()or your own.readonly showPoint?booleanDraws a point at each value.
readonly showLine?booleanDraws the lines.
readonly showArea?booleanFills the area between each line and
areaBase.readonly areaBase?numberThe value the areas close at, usually 0. It's kept within the Y axis range.
interface LineLayerOptions extends LineSeriesOptionsThe options of the 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
readonly lineSmooth?boolean | LineInterpolationHow a line runs between its points:
truesmooths it withInterpolation.monotoneCubic,falsedraws straight segments (Interpolation.none), or pass an interpolation such asInterpolation.cardinal(),Interpolation.step()or your own.readonly showPoint?booleanDraws a point at each value.
readonly showLine?booleanDraws the lines.
readonly showArea?booleanFills the area between each line and
areaBase.readonly areaBase?numberThe value the areas close at, usually 0. It's kept within the Y axis range.
readonly series?readonly (string | number)[]Series to draw, by index or name; default: all series.
readonly x?stringThe id of the X axis to draw on; default: the first X axis.
readonly y?stringThe id of the Y axis to draw on; default: the first Y axis.
readonly align?'center' | 'start'Point position on a step axis:
startof each step (1.x) or itscenter, where bars are centered.readonly overrides?Readonly<Record<string, LineSeriesOptions>>Option overrides per series name (the 1.x
seriesoption).readonly reverseData?booleanDraws the series in reverse order (1.x
reverseData). Can't be combined withseries.readonly classNames?{ readonly series?: string; readonly line?: string; readonly point?: string; readonly area?: string }Replaces the classes of what the layer draws:
series(ct-series),line(ct-line),point(ct-point) andarea(ct-area).
interface PieLayerOptionsThe options of the pie layer. Without them, it draws a filled pie from the top, with a label halfway out on each slice.
Properties
readonly startAngle?numberWhere the first slice starts, in degrees clockwise from the top.
readonly total?numberFixed total; slices are relative to it (gauges). Defaults to the sum.
readonly donut?booleanDraws a donut: rings instead of filled slices.
readonly donutWidth?string | numberDonut 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 setdonutWidththere if the page's CSS draws another width.readonly showLabel?booleanDraws a label for each slice; on by default.
readonly labelOffset?numberMoves the labels away from the center (positive) or toward it (negative), in px.
readonly 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) orcenter(in the middle; move them withlabelOffset).readonly labelTransform?(value: Label, index: number) => Label | null | undefinedFormats a slice's label: its entry in
labels, or else its value. Wins overlabelInterpolationFncwhen both are set.readonly labelInterpolationFnc?(value: Label, index: number) => Label | null | undefinedThe 1.x name of
labelTransform, which wins when both are set.readonly labelDirection?LabelDirectionWhich way labels anchor:
neutral(the default),explode(away from the center, for labels outside the pie) orimplode(toward it).readonly ignoreEmptyValues?booleanLeaves out the slices and labels of zero values.
readonly preventOverlappingLabelOffset?numberShifts labels that would overlap another one by this many px, up and left, judging the overlap by the length of the drawn label text.
readonly classNames?{ readonly series?: string; readonly slicePie?: string; readonly sliceDonut?: string; readonly label?: string }Replaces the classes of what the layer draws:
series(ct-series),slicePie(ct-slice-pie),sliceDonut(ct-slice-donut) andlabel(ct-label).
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).
interface LayerContextWhat a layer's compose gets: the data it draws, the area to draw in, the axes and ways to measure text and styles.
Properties
readonly dataPreparedDataThe prepared data; only the layer's series when it selects some.
readonly areaAreaThe drawing area, in px in the SVG.
readonly paddingChartPaddingThe chart's padding, in px.
readonly layerIndexnumberThe layer's index in the chart's
layers; part of its nodes' keys.readonly coordinatesCoordinatesThe chart's coordinate system.
readonly measureTextMeasureTextMeasures 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.
readonly measureStyle?MeasureStyleReads 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.
readonly axesChartAxesAxes created after
layout, when the chart has axes.readonly normalized?NormalizedChartDataThe data as the axes see it, when the chart has axes.
readonly 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.readonly labelsLabelModeHow label layers draw labels: chart option, else the renderer's.
readonly insetArea?Partial<Record<AxisSide, Area>>The boxes the layer reserved with
Layer.inset, one per side, in px in the SVG: just outside the axes on that side (and the boxes of layers listed before it), as long as the drawing area. Absent when the layer reserved no room.
interface ExtentContextWhat a layer's extent gets: its series as the axes see them, and the ids of the axes it draws on.
Properties
readonly normalizedNormalizedChartDataThe layer's series, normalized as for the axes (
{ x, y }values or holes); only the layer's series when it selects some.readonly axes{ readonly x?: string; readonly y?: string }The ids of the X and Y axis the layer draws on.
readonly transforms?{ readonly x?: AxisTransform; readonly y?: AxisTransform }The transforms of the X and Y axis the layer draws on, for axes that declare one (see
AxisTransform), such as a log axis.
interface LayerA layer renders series into the chart area. Built-in and custom layers use the same contract: the "Custom layers" guide explains each field and how to write and share a layer.
Properties
readonly typestringName used in error messages, e.g.
line.readonly chartType?stringThe kind of chart the layer draws, when
typedoesn't say it: achartwithoutclassNamegetsct-chart-barif a layer is abar, elsect-chart-pieorct-chart-donutfor apieordonut, elsect-chart-line. Without it,typecounts.readonly coordinatesreadonly Coordinates[]Coordinate systems the layer can draw in.
readonly axes?{ readonly x?: string; readonly y?: string }Axis ids to draw on; default: the first X and the first Y axis.
readonly 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
lowandhighstill win); on an axis several layers report a range for, the axis covers them all. Runs before the axes are created, on every layout.inset?(context: InsetContext) => Partial<ChartPadding> | undefinedReserves room outside the drawing area, in px per side, for something the layer draws next to the chart, such as an axis title or a legend. The room is added to the chart's padding, so the area shrinks and the axes stay next to it; the layer draws in the boxes its context gets as
insetArea. Layers that reserve room on the same side stack outward in the order oflayers. Runs on every layout, before thelayoutlisteners, so the room can depend on the chart's size. The "Custom layers" guide shows a layer that uses it.compose(context: LayerContext) => readonly SceneNode[]Draws the layer: returns its top-level nodes, usually one
seriesgroup per series. The pipeline keys their data nodes and passes every node with a role through thecomposelisteners.refine?(node: SceneNode, context: LayerContext) => SceneNode | undefinedRefines what the layers drew: once every layer has composed, called for each node with a role, from all layers (children before their parents), before the
composeevents, so listeners see the result. Return a changed node, such as one with a class added, orundefinedto leave it. The node keeps its key and its children whatever you return, and refining can't drop a node. With several refining layers, a node passes through them in the order oflayers. Leave it out when the layer only draws its own nodes: charts without a refining layer skip this step.annotate?(drawn: readonly SceneNode[], context: LayerContext) => SceneNode[]Draws from where the other layers drew, such as a label at each bar's end. Runs once the nodes of every layer without
annotateare composed, keyed, refined and through thecomposelisteners, so a bar a listener dropped isn't there and a moved one is where it ends up. It gets those finished top-level nodes in the order oflayers, not the nodes of other annotating layers. The nodes it returns are keyed, refined and emitted likecompose's, after them, at the layer's place inlayers; theircomposeevents come after the other layers'. Find the nodes you need withfindAll().keyframes?(previous: SceneNode, next: SceneNode, context: LayerContext, progress: readonly number[]) => Keyframes | undefinedGives the keyframes of an update animation for one of the layer's nodes, for attributes that don't move well number by number, such as an arc that should turn around its center. A renderer that animates updates (
smilAnimations()fromchartist/live) asks once per update, never per frame, with the progress points of the chart's easing: 0 is the previous node, 1 the new one, and points beyond them come from an easing that overshoots. Plugins withkeyframesare asked first. Leave it out to animate the layer's nodes number by number.
See also: https://chartist.dev/docs/custom-layers/