### Install Chartist.js
Source: https://context7.com/chartist-js/chartist/llms.txt
Install Chartist.js using npm, yarn, or pnpm.
```bash
npm install chartist
# or
yarn add chartist
# or
pnpm add chartist
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/chartist-js/chartist/blob/main/CONTRIBUTING.md
Navigate to your local repository and install all necessary dependencies using pnpm.
```bash
pnpm i
```
--------------------------------
### Start Local Development Server
Source: https://github.com/chartist-js/chartist/blob/main/website/README.md
Starts a local development server for live preview. Changes are reflected without a server restart.
```bash
pnpm start
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/chartist-js/chartist/blob/main/website/README.md
Installs project dependencies using pnpm. This is the first step before running any other commands.
```bash
pnpm install
```
--------------------------------
### Install Chartist.js
Source: https://github.com/chartist-js/chartist/blob/main/README.md
Install Chartist.js using your preferred package manager.
```sh
pnpm add chartist
# or
yarn add chartist
# or
npm i chartist
```
--------------------------------
### Chartist.js Plugin Example
Source: https://context7.com/chartist-js/chartist/llms.txt
Register plugins via the `plugins` option during chart setup. Plugins receive the chart instance and optional configuration. This example shows a plugin that logs all draw events.
```typescript
import { LineChart, Plugin } from 'chartist';
// A simple plugin that logs all draw events
const logPlugin: Plugin = (chart, options = {}) => {
chart.on('draw', data => {
console.log(`[${options.prefix ?? 'plugin'}] drew: ${data.type}`);
});
};
new LineChart(
'#chart',
{ labels: ['A', 'B', 'C'], series: [[1, 2, 3]] },
{
plugins: [
[logPlugin, { prefix: 'myApp' }], // [PluginFn, pluginOptions]
logPlugin // or just the function (no options)
]
}
);
```
--------------------------------
### Install pnpm
Source: https://github.com/chartist-js/chartist/blob/main/CONTRIBUTING.md
Install the pnpm package manager globally. This is a prerequisite for managing project dependencies.
```bash
npm install -g pnpm
```
--------------------------------
### Start Storybook
Source: https://github.com/chartist-js/chartist/blob/main/CONTRIBUTING.md
Run Storybook to view and interact with Chartist components in a local development environment.
```bash
pnpm start:storybook
```
--------------------------------
### Stacked Bar Chart Example
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/examples/bar-chart.mdx
Illustrates the creation of stacked bar charts, where segments of bars are stacked on top of each other to show proportions.
```javascript
import React from 'react';
import ContextProvider from '../ContextProvider';
export default function App() {
return (
{({ branch, theme }) => (
)}
);
}
```
--------------------------------
### Install Chartist.js with npm
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/index.mdx
Use this command to add Chartist.js to your project using the npm package manager.
```bash
npm install --save chartist
```
--------------------------------
### Install Chartist.js with pnpm
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/index.mdx
Use this command to add Chartist.js to your project using the pnpm package manager.
```bash
pnpm add chartist
```
--------------------------------
### Install Chartist.js with yarn
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/index.mdx
Use this command to add Chartist.js to your project using the yarn package manager.
```bash
yarn add chartist
```
--------------------------------
### Axis Types Configuration
Source: https://context7.com/chartist-js/chartist/llms.txt
Demonstrates how to configure different axis types for charts, including AutoScaleAxis, StepAxis, and FixedScaleAxis, with examples for Y-axis and X-axis.
```APIDOC
## Axis Types
### `AutoScaleAxis` (default Y-axis)
Automatically computes a nice scale from the data range. Accepts `low`, `high`, `onlyInteger`, `scaleMinSpace`, `referenceValue`.
### `StepAxis` (default X-axis)
Projects values by evenly spacing steps. Used for label-based axes. Accepts `ticks` (array of labels) and `stretch` (equivalent to `fullWidth`).
### `FixedScaleAxis`
Projects numeric or `Date` values onto a fixed scale. Required for time-series data. Accepts `low`, `high`, `divisor`, `ticks`.
```ts
import { LineChart, FixedScaleAxis, AutoScaleAxis } from 'chartist';
new LineChart('#chart', {
series: [{
name: 'temps',
data: [
{ x: new Date('2024-06-01'), y: 22 },
{ x: new Date('2024-06-15'), y: 28 },
{ x: new Date('2024-07-01'), y: 31 }
]
}]
}, {
axisX: {
type: FixedScaleAxis,
divisor: 3,
labelInterpolationFnc: v => new Date(v).toLocaleDateString('en', { month: 'short', day: 'numeric' })
},
axisY: {
type: AutoScaleAxis,
onlyInteger: true,
low: 0
}
});
```
```
--------------------------------
### Importing Chartist Types with TypeScript
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/whats-new-in-v1.md
Demonstrates how to import type definitions for various Chartist chart data and options when using TypeScript. Ensure you have the Chartist types installed.
```typescript
import type {
BarChartData,
BarChartOptions,
LineChartData,
LineChartOptions,
PieChartData,
PieChartOptions
} from 'chartist'
```
--------------------------------
### Overlapping Bar Chart Example
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/examples/bar-chart.mdx
Demonstrates how to create overlapping bar charts, often useful for comparing multiple data series on mobile devices.
```javascript
import React from 'react';
import ContextProvider from '../ContextProvider';
export default function App() {
return (
{({ branch, theme }) => (
)}
);
}
```
--------------------------------
### Configuring Fixed and Auto Scale Axes
Source: https://context7.com/chartist-js/chartist/llms.txt
Configure chart axes using FixedScaleAxis for time-series data and AutoScaleAxis for automatically computed scales. This example sets up custom date formatting for the X-axis and integer-only scaling for the Y-axis.
```typescript
import { LineChart, FixedScaleAxis, AutoScaleAxis } from 'chartist';
new LineChart('#chart', {
series: [{
name: 'temps',
data: [
{ x: new Date('2024-06-01'), y: 22 },
{ x: new Date('2024-06-15'), y: 28 },
{ x: new Date('2024-07-01'), y: 31 }
]
}]
}, {
axisX: {
type: FixedScaleAxis,
divisor: 3,
labelInterpolationFnc: v => new Date(v).toLocaleDateString('en', { month: 'short', day: 'numeric' })
},
axisY: {
type: AutoScaleAxis,
onlyInteger: true,
low: 0
}
});
```
--------------------------------
### Animating Chart Elements with SMIL via Draw Event
Source: https://context7.com/chartist-js/chartist/llms.txt
Apply SMIL animations to chart elements like lines and areas by intercepting the 'draw' event. This example animates the 'd' attribute of paths, scaling them from a collapsed state to their final form.
```typescript
import 'chartist/dist/index.css';
import { LineChart, easings } from 'chartist';
const chart = new LineChart(
'#chart',
{
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
series: [
[1, 5, 2, 5, 4, 3],
[2, 3, 4, 8, 1, 2],
[5, 4, 3, 2, 1, 0.5]
]
},
{ low: 0, showArea: true, showPoint: false, fullWidth: true }
);
chart.on('draw', data => {
if (data.type === 'line' || data.type === 'area') {
// Animate the SVG path 'd' attribute from a scaled-down version to the real path
data.element.animate({
d: {
begin: 2000 * data.index,
dur: 2000,
from: data.path
.clone()
.scale(1, 0) // collapse to X-axis
.translate(0, data.chartRect.height()) // shift down
.stringify(),
to: data.path.clone().stringify(),
easing: easings.easeOutQuint
}
});
}
});
```
--------------------------------
### Deploy Website to GitHub Pages
Source: https://github.com/chartist-js/chartist/blob/main/website/README.md
Builds the website and pushes it to the 'gh-pages' branch, suitable for GitHub Pages hosting. Ensure to replace '' with your actual username.
```bash
GIT_USER= USE_SSH=true pnpm deploy
```
--------------------------------
### Build Static Website Content
Source: https://github.com/chartist-js/chartist/blob/main/website/README.md
Generates static website files into the 'build' directory. These files can be hosted on any static hosting service.
```bash
pnpm build
```
--------------------------------
### Responsive Line Chart Options
Source: https://context7.com/chartist-js/chartist/llms.txt
Configures a line chart to adapt its appearance based on screen size using media queries. Import 'chartist' CSS and the LineChart class. Options are provided as an array of [mediaQuery, options] pairs.
```typescript
import 'chartist/dist/index.css';
import { LineChart, ResponsiveOptions, LineChartOptions } from 'chartist';
const responsiveOptions: ResponsiveOptions = [
['screen and (min-width: 641px) and (max-width: 1024px)', {
showPoint: false,
axisX: {
labelInterpolationFnc: value => String(value).slice(0, 3) // Mon, Tue…
}
}],
['screen and (max-width: 640px)', {
showLine: false,
axisX: {
labelInterpolationFnc: value => String(value)[0] // M, T, W…
}
}]
];
new LineChart(
'#chart',
{ labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], series: [[5, 2, 4, 2, 0]] },
{ showArea: true },
responsiveOptions
);
```
--------------------------------
### Create a Bar Chart with Chartist.js
Source: https://github.com/chartist-js/chartist/blob/main/README.md
Import and instantiate a BarChart with data and options. Configure axis labels to display only on even indices.
```js
import { BarChart } from 'chartist';
new BarChart('#chart', {
labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'],
series: [
[1, 2, 4, 8, 6, -2, -1, -4, -6, -2]
]
}, {
high: 10,
low: -10,
axisX: {
labelInterpolationFnc: (value, index) => (index % 2 === 0 ? value : null)
}
});
```
--------------------------------
### Create Donut and Gauge Charts
Source: https://context7.com/chartist-js/chartist/llms.txt
For donut charts, set `donut: true` and `donutWidth`. For gauge charts, use `startAngle` and `total` to define the arc and scale.
```typescript
import 'chartist/dist/index.css';
import { PieChart } from 'chartist';
// Donut chart
new PieChart('#donut', { series: [10, 20, 50, 20] }, {
donut: true,
donutWidth: 60, // pixels or '30%'
showLabel: false
});
// Gauge chart: draws only 3/4 of the circle (270° arc)
new PieChart('#gauge', { series: [20, 10, 30, 40] }, {
donut: true,
donutWidth: 20,
startAngle: 270, // start at the bottom
total: 200, // sum of series must equal this for a full circle
showLabel: false
});
```
--------------------------------
### Chart.js Event System with .on() and .off()
Source: https://context7.com/chartist-js/chartist/llms.txt
Demonstrates how to subscribe to and unsubscribe from chart events using the .on() and .off() methods. This system allows for custom handling of chart lifecycle events like drawing, creation, and data updates. Wildcard '*' can be used to listen to all events.
```typescript
import { BarChart } from 'chartist';
const chart = new BarChart('#chart', {
labels: ['A', 'B', 'C'],
series: [[3, 1, 4]]
});
// Typed draw handler
chart.on('draw', data => {
if (data.type === 'bar') {
// data.element is an Svg wrapper; data.x1/y1/x2/y2 are bar coordinates
data.element.attr({ style: 'stroke: tomato; stroke-width: 20px' });
}
if (data.type === 'label') {
console.log(`Label: ${data.text} at (${data.x}, ${data.y})`);
}
});
// Wildcard listener for debugging
chart.on('*', (event, data) => console.log(event, data));
// Unsubscribe a specific handler
const handler = (data: any) => console.log(data);
chart.on('created', handler);
chart.off('created', handler);
```
--------------------------------
### Create a Basic Line Chart
Source: https://context7.com/chartist-js/chartist/llms.txt
Generates a responsive multi-series line chart with area fill and point display. Listen to draw events for custom element manipulation. Updates data dynamically and detaches the chart to clean up resources.
```typescript
import 'chartist/dist/index.css';
import { LineChart, Interpolation } from 'chartist';
// Basic multi-series line chart with area fill and full-width expansion
const chart = new LineChart(
'#chart',
{
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
series: [
[5, 2, 4, 2, 0, 3, 7],
[3, 1, 6, 4, 2, 5, 8]
]
},
{
low: 0,
high: 10,
showArea: true, // draw filled area under line
showPoint: true, // draw data-point dots
showLine: true,
fullWidth: true, // stretch to last grid line
lineSmooth: Interpolation.monotoneCubic(), // smooth without overshooting
chartPadding: { top: 15, right: 15, bottom: 5, left: 10 },
axisX: {
showGrid: true,
labelInterpolationFnc: (value, index) =>
index % 2 === 0 ? value : null // show every other label
},
axisY: {
offset: 40,
onlyInteger: true,
scaleMinSpace: 20
}
}
);
// Listen to every drawn element
chart.on('draw', data => {
if (data.type === 'point') {
console.log(`Point at (${data.x}, ${data.y}), value: ${data.value}`);
}
});
// Dynamically update data without recreating
chart.update(
{ labels: ['Mon', 'Tue', 'Wed'], series: [[1, 3, 2]] },
{ high: 5 }
);
// Clean up event listeners and media-query observers
chart.detach();
```
--------------------------------
### Create Pie Chart with Custom Labels
Source: https://context7.com/chartist-js/chartist/llms.txt
Use `showLabel: true` and `labelPosition: 'outside'` for visible labels. Customize label content with `labelInterpolationFnc`. `chartPadding` adds space around the chart.
```typescript
import 'chartist/dist/index.css';
import { PieChart } from 'chartist';
// Simple pie chart with custom label interpolation
new PieChart(
'#chart',
{
series: [20, 10, 30, 40],
labels: ['Cats', 'Dogs', 'Birds', 'Fish']
},
{
showLabel: true,
labelPosition: 'outside', // 'inside' | 'outside' | 'center'
labelOffset: 20,
labelDirection: 'explode', // 'neutral' | 'explode' | 'implode'
labelInterpolationFnc: (value, index) =>
['Cats', 'Dogs', 'Birds', 'Fish'][index],
chartPadding: 30,
ignoreEmptyValues: true
}
);
```
--------------------------------
### Import Chartist.js CSS and Classes
Source: https://context7.com/chartist-js/chartist/llms.txt
Import the required CSS for default styles and the necessary chart classes from the Chartist library.
```typescript
import 'chartist/dist/index.css';
import { LineChart, BarChart, PieChart } from 'chartist';
```
--------------------------------
### Animated Donut Chart with Stroke-Dashoffset
Source: https://context7.com/chartist-js/chartist/llms.txt
Creates an animated donut chart where slices animate in sequentially using stroke-dashoffset. Ensure the 'chartist' library and its CSS are imported. The animation for each slice depends on the completion of the previous one.
```typescript
import 'chartist/dist/index.css';
import { PieChart, easings, AnimationDefinition } from 'chartist';
const chart = new PieChart(
'#chart',
{ series: [10, 20, 50, 20, 5], labels: [1, 2, 3, 4, 5] },
{ donut: true, showLabel: false }
);
chart.on('draw', data => {
if (data.type === 'slice') {
const pathLength = data.element.getNode().getTotalLength();
data.element.attr({ 'stroke-dasharray': `${pathLength}px ${pathLength}px` });
const animDef: Record = {
'stroke-dashoffset': {
id: `anim${data.index}`,
dur: 1000,
from: `-${pathLength}px`,
to: '0px',
easing: easings.easeOutQuint,
fill: 'freeze'
}
};
if (data.index !== 0) {
animDef['stroke-dashoffset'].begin = `anim${data.index - 1}.end`;
}
data.element.attr({ 'stroke-dashoffset': `-${pathLength}px` });
data.element.animate(animDef, false); // false = not guided mode
}
});
```
--------------------------------
### Create Pie Chart with Per-Slice Class Names and Meta Data
Source: https://context7.com/chartist-js/chartist/llms.txt
Assign custom class names and meta data to slices by structuring the `series` data as objects. Use the 'draw' event to access slice data and apply custom logic.
```typescript
import 'chartist/dist/index.css';
import { PieChart } from 'chartist';
new PieChart('#chart', {
series: [
{ value: 20, name: 'Revenue', className: 'slice-revenue', meta: { id: 1 } },
{ value: 10, name: 'Costs', className: 'slice-costs', meta: { id: 2 } },
{ value: 70, name: 'Profit', className: 'slice-profit', meta: { id: 3 } }
]
}).on('draw', data => {
if (data.type === 'slice') {
console.log(`Slice "${data.series.name}": ${data.value} / ${data.totalDataSum}`);
}
});
```
--------------------------------
### Interpolation.simple
Source: https://context7.com/chartist-js/chartist/llms.txt
Provides simple bezier smoothing for lines with a configurable `divisor` option to control the smoothing factor.
```APIDOC
## Interpolation.simple(options?)
Simple bezier smoothing with configurable `divisor`.
```ts
import { LineChart, Interpolation } from 'chartist';
new LineChart('#chart', { labels: [1,2,3,4,5], series: [[1,2,8,1,7]] }, {
lineSmooth: Interpolation.simple({ divisor: 2 })
});
```
```
--------------------------------
### Interpolation.step
Source: https://context7.com/chartist-js/chartist/llms.txt
Applies a step interpolation to lines, creating a stepped effect instead of diagonal lines. It accepts an options object with `postpone` and `fillHoles`.
```APIDOC
## Interpolation.step(options?)
Steps instead of diagonal lines. Accepts `postpone` (default `true` — step at current value) and `fillHoles`.
```ts
import { LineChart, Interpolation } from 'chartist';
new LineChart('#chart', { labels: [1,2,3,4,5], series: [[1,2,8,1,7]] }, {
lineSmooth: Interpolation.step({ postpone: false })
});
```
```
--------------------------------
### Chart.js Default Chart Sizing and Drawing Options
Source: https://github.com/chartist-js/chartist/wiki/Default-options-list
Configures the overall dimensions and drawing behavior of the chart, including width, height, line and point visibility, area drawing, and smoothing. Adjust these to control the chart's appearance and responsiveness.
```javascript
// Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
width: undefined,
// Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
height: undefined,
// If the line should be drawn or not
showLine: true,
// If dots should be drawn or not
showPoint: true,
// If the line chart should draw an area
showArea: false,
// The base for the area chart that will be used to close the area shape (is normally 0)
areaBase: 0,
// Specify if the lines should be smoothed. This value can be true or false where true will result in smoothing using the default smoothing interpolation function Chartist.Interpolation.cardinal and false results in Chartist.Interpolation.none. You can also choose other smoothing / interpolation functions available in the Chartist.Interpolation module, or write your own interpolation function. Check the examples for a brief description.
lineSmooth: true,
// If the line chart should add a background fill to the .ct-grids group.
showGridBackground: false,
// Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
low: undefined,
// Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
high: undefined,
// Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
chartPadding: {
top: 15,
right: 15,
bottom: 5,
left: 10
},
// When set to true, the last grid line on the x-axis is not drawn and the chart elements will expand to the full available width of the chart. For the last label to be drawn correctly you might need to add chart padding or offset the last label with a draw event handler.
fullWidth: false,
// If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
reverseData: false,
// Override the class names that get used to generate the SVG structure of the chart
classNames: {
chart: 'ct-chart-line',
label: 'ct-label',
labelGroup: 'ct-labels',
series: 'ct-series'
```
--------------------------------
### Line Chart with Named Series and Per-Series Options
Source: https://context7.com/chartist-js/chartist/llms.txt
Applies distinct rendering options to individual series by referencing their names in the series options map. Includes responsive overrides for different screen sizes.
```typescript
import 'chartist/dist/index.css';
import { LineChart, Interpolation } from 'chartist';
new LineChart(
'#chart',
{
labels: ['1', '2', '3', '4', '5', '6', '7', '8'],
series: [
{ name: 'temperature', data: [5, 2, -4, 2, 0, -2, 5, -3] },
{ name: 'humidity', data: [4, 3, 5, 3, 1, 3, 6, 4] },
{ name: 'pressure', data: [2, 4, 3, 1, 4, 5, 3, 2] }
]
},
{
fullWidth: true,
series: {
temperature: { lineSmooth: Interpolation.step() },
humidity: { lineSmooth: Interpolation.cardinal({ tension: 0.5 }), showArea: true },
pressure: { showPoint: false }
}
},
// Responsive overrides: different options per breakpoint
[
['screen and (max-width: 480px)', {
series: {
temperature: { lineSmooth: Interpolation.none() },
humidity: { showArea: false }
}
}]
]
);
```
--------------------------------
### Svg Wrapper Usage
Source: https://context7.com/chartist-js/chartist/llms.txt
Explains how to use the `Svg` wrapper for programmatic SVG creation, attribute manipulation, class management, animations, and DOM traversal within Chartist.js charts.
```APIDOC
## SVG Wrapper (`Svg`)
`Svg` is a fluent DOM wrapper around SVG elements that enables programmatic SVG creation, attribute setting, class management, and SMIL animations. It is used internally for all chart drawing and exposed for use in `draw` event handlers and plugins.
```ts
import { Svg, easings } from 'chartist';
// Wrap an existing SVG node
const svgEl = document.querySelector('svg')!;
const svg = new Svg(svgEl);
// Create child elements fluently
const group = svg.elem('g', {}, 'my-group');
const rect = group.elem('rect', { x: 10, y: 10, width: 100, height: 50 }, 'my-rect');
// Get/set attributes
rect.attr({ fill: 'steelblue', rx: 4 });
const fillValue = rect.attr('fill'); // 'steelblue'
// Class management
rect.addClass('highlighted');
rect.removeClass('highlighted');
const classes = rect.classes(); // ['my-rect']
// Animate with SMIL (guided mode handles fill-freeze and beginElement internally)
rect.animate({
x: {
dur: 500,
from: 10,
to: 200,
easing: easings.easeOutQuart // or a [cx1, cy1, cx2, cy2] bezier array
},
opacity: {
dur: '500ms',
from: 0,
to: 1
}
}, true /* guided */);
// Navigate the tree
const parent = rect.parent();
const root = rect.root();
const found = svg.querySelector('.my-rect');
const list = svg.querySelectorAll('rect');
// Embed HTML via foreignObject
svg.foreignObject('Hello
', { x: 0, y: 0, width: 200, height: 50 });
// Remove element
rect.remove();
```
```
--------------------------------
### Step Interpolation for Line Charts
Source: https://context7.com/chartist-js/chartist/llms.txt
Use Interpolation.step to create step-like lines instead of diagonal ones. The 'postpone' option defaults to true, determining if the step occurs at the current value.
```typescript
import { LineChart, Interpolation } from 'chartist';
new LineChart('#chart', { labels: [1,2,3,4,5], series: [[1,2,8,1,7]] }, {
lineSmooth: Interpolation.step({ postpone: false })
});
```
--------------------------------
### SMIL Animations via draw Event
Source: https://context7.com/chartist-js/chartist/llms.txt
Shows how to intercept drawn elements in the `draw` event to apply SMIL animations to various chart components like bars, lines, areas, points, or slices.
```APIDOC
## SMIL Animations via `draw` Event
Intercept every drawn element in the `draw` event to add SMIL animations to bars, lines, areas, points, or slices.
```ts
import 'chartist/dist/index.css';
import { LineChart, easings } from 'chartist';
const chart = new LineChart(
'#chart',
{
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
series: [
[1, 5, 2, 5, 4, 3],
[2, 3, 4, 8, 1, 2],
[5, 4, 3, 2, 1, 0.5]
]
},
{ low: 0, showArea: true, showPoint: false, fullWidth: true }
);
chart.on('draw', data => {
if (data.type === 'line' || data.type === 'area') {
// Animate the SVG path 'd' attribute from a scaled-down version to the real path
data.element.animate({
d: {
begin: 2000 * data.index,
dur: 2000,
from: data.path
.clone()
.scale(1, 0) // collapse to X-axis
.translate(0, data.chartRect.height()) // shift down
.stringify(),
to: data.path.clone().stringify(),
easing: easings.easeOutQuint
}
});
}
});
```
```
--------------------------------
### Create Stacked Bar Chart with Formatted Y-Axis Labels
Source: https://context7.com/chartist-js/chartist/llms.txt
Use `stackBars: true` and `stackMode: 'accumulate'` for stacked bars. Customize Y-axis labels using `labelInterpolationFnc` to format values.
```typescript
import 'chartist/dist/index.css';
import { BarChart } from 'chartist';
// Stacked bar chart with formatted Y-axis labels
new BarChart(
'#chart',
{
labels: ['Q1', 'Q2', 'Q3', 'Q4'],
series: [
[800000, 1200000, 1400000, 1300000],
[200000, 400000, 500000, 300000],
[100000, 200000, 400000, 600000]
]
},
{
stackBars: true,
stackMode: 'accumulate', // bars stack on top of each other
seriesBarDistance: 15,
axisY: {
labelInterpolationFnc: value => `${+value / 1000}k`
}
}
).on('draw', data => {
if (data.type === 'bar') {
// Customise each bar element via SVG attributes
data.element.attr({ style: 'stroke-width: 30px' });
}
});
```
--------------------------------
### Bar Chart with Peak Circles via Draw Events
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/examples/bar-chart.mdx
Shows how to add custom elements, such as peak circles, to bars by utilizing the 'draw' events provided by Chartist.js.
```javascript
import React from 'react';
import ContextProvider from '../ContextProvider';
export default function App() {
return (
{({ branch, theme }) => (
)}
);
}
```
--------------------------------
### Run Tests in Watch Mode
Source: https://github.com/chartist-js/chartist/blob/main/CONTRIBUTING.md
Execute Jest tests in watch mode for continuous testing during development. This allows for rapid feedback on code changes.
```bash
pnpm jest --watch
```
--------------------------------
### Line Chart with Cardinal Spline Interpolation
Source: https://context7.com/chartist-js/chartist/llms.txt
Renders a line chart using Cardinal (Catmull-Rom) splines, ensuring the curve passes through data points but may overshoot on sharp changes. Supports 'tension' (0-1, default 1) and 'fillHoles' options. Import 'chartist' and the Interpolation namespace.
```typescript
import { LineChart, Interpolation } from 'chartist';
new LineChart('#chart', { labels: [1,2,3,4,5], series: [[1,2,8,1,7]] }, {
lineSmooth: Interpolation.cardinal({ tension: 0.5, fillHoles: false })
});
```
--------------------------------
### Interpolation
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/api/basics.md
Details on the interpolation module for Chartist.js.
```APIDOC
## Interpolation Namespace
### Description
Provides functions for data interpolation in Chartist.js.
### API Reference
[Link to Interpolation API documentation](/api/namespaces/Interpolation)
```
--------------------------------
### SVG Wrappers
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/api/basics.md
This section covers the SVG utility classes provided by Chartist.js for generating SVG elements.
```APIDOC
## Svg
### Description
Represents an SVG element in Chartist.js.
### API Reference
[Link to Svg API documentation](/api/classes/Svg)
```
```APIDOC
## SvgPath
### Description
Represents an SVG path element in Chartist.js.
### API Reference
[Link to SvgPath API documentation](/api/classes/SvgPath)
```
```APIDOC
## SvgList
### Description
Represents a list of SVG elements in Chartist.js.
### API Reference
[Link to SvgList API documentation](/api/classes/SvgList)
```
--------------------------------
### Create Horizontal Bar Chart
Source: https://context7.com/chartist-js/chartist/llms.txt
Set `horizontalBars: true` to flip axes. Use `reverseData: true` to draw from top to bottom. Adjust `axisY.offset` for long labels.
```typescript
import 'chartist/dist/index.css';
import { BarChart } from 'chartist';
new BarChart(
'#chart',
{
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
series: [
[5, 4, 3, 7, 5],
[3, 2, 9, 5, 4]
]
},
{
horizontalBars: true,
reverseData: true, // draw top-to-bottom
seriesBarDistance: 10,
axisY: { offset: 80 }, // extra space for long labels
axisX: { onlyInteger: true }
}
);
```
--------------------------------
### Programmatic SVG Manipulation with Svg Wrapper
Source: https://context7.com/chartist-js/chartist/llms.txt
Utilize the Svg wrapper for fluent creation and manipulation of SVG elements. Supports attribute setting, class management, SMIL animations, tree navigation, and embedding HTML via foreignObject.
```typescript
import { Svg, easings } from 'chartist';
// Wrap an existing SVG node
const svgEl = document.querySelector('svg')!;
const svg = new Svg(svgEl);
// Create child elements fluently
const group = svg.elem('g', {}, 'my-group');
const rect = group.elem('rect', { x: 10, y: 10, width: 100, height: 50 }, 'my-rect');
// Get/set attributes
rect.attr({ fill: 'steelblue', rx: 4 });
const fillValue = rect.attr('fill'); // 'steelblue'
// Class management
rect.addClass('highlighted');
rect.removeClass('highlighted');
const classes = rect.classes(); // ['my-rect']
// Animate with SMIL (guided mode handles fill-freeze and beginElement internally)
rect.animate({
x: {
dur: 500,
from: 10,
to: 200,
easing: easings.easeOutQuart // or a [cx1, cy1, cx2, cy2] bezier array
},
opacity: {
dur: '500ms',
from: 0,
to: 1
}
}, true /* guided */);
// Navigate the tree
const parent = rect.parent();
const root = rect.root();
const found = svg.querySelector('.my-rect');
const list = svg.querySelectorAll('rect');
// Embed HTML via foreignObject
svg.foreignObject('Hello
', { x: 0, y: 0, width: 200, height: 50 });
// Remove element
rect.remove();
```
--------------------------------
### Line Chart with No Interpolation
Source: https://context7.com/chartist-js/chartist/llms.txt
Creates a line chart where data points are connected by straight lines, offering the fastest rendering. Handles data holes by not drawing lines across them. Import 'chartist' and the Interpolation namespace.
```typescript
import { LineChart, Interpolation } from 'chartist';
new LineChart('#chart', { labels: [1,2,3,4,5], series: [[1,null,8,1,7]] }, {
lineSmooth: Interpolation.none()
});
```
--------------------------------
### Line Chart with Monotone Cubic Interpolation
Source: https://context7.com/chartist-js/chartist/llms.txt
Generates a line chart with smooth curves that maintain monotonicity, preventing overshooting. This is the default smoothing for `lineSmooth: true`. Accepts a 'fillHoles' option (default false). Import 'chartist' and the Interpolation namespace.
```typescript
import { LineChart, Interpolation } from 'chartist';
new LineChart('#chart', { labels: [1,2,3,4,5], series: [[1,2,8,1,7]] }, {
lineSmooth: Interpolation.monotoneCubic({ fillHoles: true })
});
```
--------------------------------
### EventEmitter
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/api/basics.md
Documentation for the EventEmitter class used in Chartist.js for handling events.
```APIDOC
## EventEmitter
### Description
A class for managing and emitting events within Chartist.js.
### API Reference
[Link to EventEmitter API documentation](/api/classes/EventEmitter)
```
--------------------------------
### Line Chart with Time-Series and FixedScaleAxis
Source: https://context7.com/chartist-js/chartist/llms.txt
Plots time-series data with irregular intervals using `FixedScaleAxis` on the X-axis. Data points are objects with `x` (Date) and `y` (number) properties.
```typescript
import 'chartist/dist/index.css';
import { LineChart, FixedScaleAxis } from 'chartist';
new LineChart(
'#chart',
{
series: [
{
name: 'sensor-a',
data: [
{ x: new Date('2024-01-01'), y: 53 },
{ x: new Date('2024-01-03'), y: 40 },
{ x: new Date('2024-01-07'), y: 45 },
{ x: new Date('2024-01-10'), y: 30 }
]
}
]
},
{
axisX: {
type: FixedScaleAxis,
divisor: 5, // number of tick steps
labelInterpolationFnc: value =>
new Date(value).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
},
axisY: { onlyInteger: true }
}
);
```
--------------------------------
### Migrate from CommonJS to ESM in Chartist
Source: https://github.com/chartist-js/chartist/blob/main/website/docs/whats-new-in-v1.md
Shows the migration from CommonJS require statements to ES module imports for Chartist components. This is necessary for leveraging tree-shaking.
```javascript
const Chartist = require('chartist')
new Chartist.Bar(/* ... */);
new Chartist.Line(/* ... */);
new Chartist.Pie(/* ... */);
new Chartist.Svg(/* ... */);
Chartist.Svg.Easing
// ...
// ->
import { BarChart, LineChart, PieChart, Svg, easings } from 'chartist'
new BarChart(/* ... */)
new LineChart(/* ... */)
new PieChart(/* ... */)
new Svg(/* ... */)
easings
// ...
```
--------------------------------
### Chartist.js chart.update() Method
Source: https://context7.com/chartist-js/chartist/llms.txt
Dynamically update chart data and options after initialization. The `update()` method can be used to change data only, or both data and options. An optional third argument `override=true` merges new options on top of current ones.
```typescript
import { BarChart } from 'chartist';
const chart = new BarChart('#chart', {
labels: ['Jan', 'Feb', 'Mar'],
series: [[10, 20, 15]]
});
// Update data only (keeps current options)
chart.update({ labels: ['Apr', 'May', 'Jun'], series: [[5, 30, 25]] });
// Update both data and options
chart.update(
{ labels: ['Jul', 'Aug'], series: [[8, 12]] },
{ high: 40, low: 0 }
);
// Pass override=true to merge new options on top of current (not defaults)
chart.update(null, { axisY: { onlyInteger: true } }, true);
```
--------------------------------
### Simple Bezier Smoothing for Line Charts
Source: https://context7.com/chartist-js/chartist/llms.txt
Employ Interpolation.simple for basic Bezier curve smoothing on line charts. The 'divisor' option can be configured to adjust the smoothing effect.
```typescript
import { LineChart, Interpolation } from 'chartist';
new LineChart('#chart', { labels: [1,2,3,4,5], series: [[1,2,8,1,7]] }, {
lineSmooth: Interpolation.simple({ divisor: 2 })
});
```
--------------------------------
### Chart.js Default Axis Options
Source: https://github.com/chartist-js/chartist/wiki/Default-options-list
Defines the default configuration for both X and Y axes, including label offsets, visibility, grid drawing, interpolation, and axis types. Use these to customize how your axes are displayed and behave.
```javascript
axisX: {
// The offset of the labels to the chart area
offset: 30,
// Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
position: 'end',
// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset: {
x: 0,
y: 0
},
// If labels should be shown or not
showLabel: true,
// If the axis grid should be drawn or not
showGrid: true,
// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc: Chartist.noop,
// Set the axis type to be used to project values on this axis. If not defined, Chartist.StepAxis will be used for the X-Axis, where the ticks option will be set to the labels in the data and the stretch option will be set to the global fullWidth option. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
type: undefined
},
// Options for Y-Axis
axisY: {
// The offset of the labels to the chart area
offset: 40,
// Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
position: 'start',
// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset: {
x: 0,
y: 0
},
// If labels should be shown or not
showLabel: true,
// If the axis grid should be drawn or not
showGrid: true,
// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc: Chartist.noop,
// Set the axis type to be used to project values on this axis. If not defined, Chartist.AutoScaleAxis will be used for the Y-Axis, where the high and low options will be set to the global high and low options. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
type: undefined,
// This value specifies the minimum height in pixel of the scale steps
scaleMinSpace: 20,
// Use only integer values (whole numbers) for the scale steps
onlyInteger: false
}
```
--------------------------------
### Create Bipolar Bar Chart
Source: https://context7.com/chartist-js/chartist/llms.txt
Use positive and negative values in series for bipolar charts. Customize X-axis label display with `axisX.labelInterpolationFnc` to show labels only on even indices.
```typescript
import 'chartist/dist/index.css';
import { BarChart } from 'chartist';
new BarChart(
'#chart',
{
labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'],
series: [
[1, 2, 4, 8, 6, -2, -1, -4, -6, -2],
[-3, -1, 2, 5, 3, -1, -4, -6, -2, 1]
]
},
{
high: 10,
low: -10,
seriesBarDistance: 12,
axisX: {
labelInterpolationFnc: (value, index) => (index % 2 === 0 ? value : null)
}
}
);
```