Chartist

Search

Find a guide, an API entry or an example.

Try

Layers

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

axisGrid

Source
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.

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()
  ]
});

axisLabels

Source
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 = {}

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' })
  ]
});

band

Source
function band(options: BandOptions): Layer

Creates 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

options BandOptions

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 })] } }
);

bar

Source
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.

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'
});

line

Source
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.

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()
  ]
});

determineAnchorPosition

Source
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

Source
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 = {}

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'
});

AxisLayerClassNames

Source
interface AxisLayerClassNames extends AxisClassNames

The classes axisGrid and axisLabels give what they draw. The defaults are the 1.x classes, so 1.x CSS applies.

Properties

readonly gridGroup string

The group of all grid lines (ct-grids).

readonly labelGroup string

The group of all labels (ct-labels).

readonly gridBackground string

The rect behind the grid, with background: true (ct-grid-background).

readonly grid string

Each grid line (ct-grid).

readonly label string

Each label (ct-label).

readonly horizontal string

Grid lines and labels of an X axis (ct-horizontal).

readonly vertical string

Grid lines and labels of a Y axis (ct-vertical).

readonly start string

Labels of an axis at the top or left (ct-start).

readonly end string

Labels of an axis at the bottom or right (ct-end).

readonly gridMinor? string

Grid lines at an axis's minorTicks, next to the grid class (ct-grid-minor).

AxisLayerOptions

Source
interface AxisLayerOptions

The 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.

AxisLabelsOptions

Source
interface AxisLabelsOptions extends AxisLayerOptions

The 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? LabelMode

HTML (foreignObject) or SVG text; 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 labelAlign wins over it. HTML labels ignore it (align them with CSS).

BandEdgeValue

Source
type BandEdgeValue = number | { readonly x: number; readonly y: number } | null | undefined

A value of a band edge given as values: a number, { x, y } on a scale X axis, or null for a hole.

BandEdgeOption

Source
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 }.

BandOptions

Source
interface BandOptions

The options of the band layer: low and high edges, or a series group.

Properties

readonly low? BandEdgeOption

The low edge: a constant value, values or a series.

readonly high? BandEdgeOption

The 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 low and high.

readonly x? string

The id of the X axis to draw on; default: the first X axis.

readonly y? string

The id of the Y axis to draw on; default: the first Y axis.

readonly lineSmooth? boolean | LineInterpolation

How the edges run between values, as lineSmooth of the line layer: true smooths them with Interpolation.monotoneCubic, false draws straight segments, or pass an interpolation.

readonly align? 'center' | 'start'

Edge position on a step axis: start of each step (1.x) or its center, where bars are centered.

readonly className? string

A class added to the band's group, such as ct-series-c for a color.

readonly mark? boolean

Gives the points and bars of every layer ct-in-band when their value at their value index lies between the band's edges (edges included), else ct-out-band. The value is y, or x when a value has no y (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) and outBand (ct-out-band).

BarLayerOptions

Source
interface BarLayerOptions

The 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? string

The id of the X axis to draw on; default: the first X axis.

readonly y? string

The id of the Y axis to draw on; default: the first Y axis.

readonly horizontalBars? boolean

Values on the X axis, labels on the Y axis.

readonly 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).

readonly 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.

readonly seriesBarDistance? number

Distance between the bars of different series, in px.

readonly offset? number

Moves 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? boolean

One series per value of a flat series (1.x distributeSeries).

readonly reverseData? boolean

Draws the series in reverse order (1.x reverseData). Can't be combined with series.

readonly classNames? { readonly series?: string; readonly bar?: string }

Replaces the classes of what the layer draws: series (ct-series) and bar (ct-bar).

LineSeriesOptions

Source
interface LineSeriesOptions

The line options you can set per series: in the overrides of line, or the series option of lineChart.

Properties

readonly 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.

readonly showPoint? boolean

Draws a point at each value.

readonly showLine? boolean

Draws the lines.

readonly showArea? boolean

Fills the area between each line and areaBase.

readonly areaBase? number

The value the areas close at, usually 0. It's kept within the Y axis range.

LineLayerOptions

Source
interface LineLayerOptions extends LineSeriesOptions

The 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 | 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.

readonly showPoint? boolean

Draws a point at each value.

readonly showLine? boolean

Draws the lines.

readonly showArea? boolean

Fills the area between each line and areaBase.

readonly areaBase? number

The 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? string

The id of the X axis to draw on; default: the first X axis.

readonly y? string

The id of the Y axis to draw on; default: the first Y axis.

readonly align? 'center' | 'start'

Point position on a step axis: start of each step (1.x) or its center, where bars are centered.

readonly overrides? Readonly<Record<string, LineSeriesOptions>>

Option overrides per series name (the 1.x series option).

readonly reverseData? boolean

Draws the series in reverse order (1.x reverseData). Can't be combined with series.

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) and area (ct-area).

PieLayerOptions

Source
interface PieLayerOptions

The 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? number

Where the first slice starts, in degrees clockwise from the top.

readonly total? number

Fixed total; slices are relative to it (gauges). Defaults to the sum.

readonly donut? boolean

Draws a donut: rings instead of filled slices.

readonly 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.

readonly showLabel? boolean

Draws a label for each slice; on by default.

readonly labelOffset? number

Moves 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) or center (in the middle; move them with labelOffset).

readonly labelTransform? (value: Label, index: number) => Label | null | undefined

Formats a slice's label: its entry in labels, or else its value. Wins over labelInterpolationFnc when both are set.

readonly labelInterpolationFnc? (value: Label, index: number) => Label | null | undefined

The 1.x name of labelTransform, which wins when both are set.

readonly labelDirection? LabelDirection

Which way labels anchor: neutral (the default), explode (away from the center, for labels outside the pie) or implode (toward it).

readonly ignoreEmptyValues? boolean

Leaves out the slices and labels of zero values.

readonly 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.

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) and label (ct-label).

Coordinates

Source
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

Source
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

readonly data PreparedData

The prepared data; only the layer's series when it selects some.

readonly area Area

The drawing area, in px in the SVG.

readonly padding ChartPadding

The chart's padding, in px.

readonly layerIndex number

The layer's index in the chart's layers; part of its nodes' keys.

readonly coordinates Coordinates

The chart's coordinate system.

readonly 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.

readonly 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.

readonly axes ChartAxes

Axes created after layout, when the chart has axes.

readonly normalized? NormalizedChartData

The 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 labels LabelMode

How 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.

ExtentContext

Source
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

readonly 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.

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.

Layer

Source
interface Layer

A 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 type string

Name used in error messages, e.g. line.

readonly chartType? string

The kind of chart the layer draws, when type doesn't say it: a 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.

readonly coordinates readonly 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 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.

inset? (context: InsetContext) => Partial<ChartPadding> | undefined

Reserves 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 of layers. Runs on every layout, before the layout listeners, 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 series group per series. The pipeline keys their data nodes and passes every node with a role through the compose listeners.

refine? (node: SceneNode, context: LayerContext) => SceneNode | undefined

Refines 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 compose events, so listeners see the result. Return a changed node, such as one with a class added, or undefined to 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 of layers. 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 annotate are composed, keyed, refined and through the compose listeners, 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 of layers, not the nodes of other annotating layers. The nodes it returns are keyed, refined and emitted like compose's, after them, at the layer's place in layers; their compose events come after the other layers'. Find the nodes you need with findAll().

keyframes? (previous: SceneNode, next: SceneNode, context: LayerContext, progress: readonly number[]) => Keyframes | undefined

Gives 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() from chartist/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 with keyframes are asked first. Leave it out to animate the layer's nodes number by number.

See also: https://chartist.dev/docs/custom-layers/