Trendline for Chart.js
bash
npm i chart.js chartjs-plugin-trendline
`
Import and register with Chart.js:
`js
import { Chart } from 'chart.js';
import ChartJSTrendline from 'chartjs-plugin-trendline';
Chart.register(ChartJSTrendline);
`
$3
`js
const { Chart } = require('chart.js');
const ChartJSTrendline = require('chartjs-plugin-trendline');
Chart.register(ChartJSTrendline);
`
$3
Load Chart.js first, then the plugin which will automatically register itself:
`html
`
The plugin is now available globally as ChartJSTrendline and auto-registers with Chart.js.
Configuration
To configure the trendline plugin you simply add a new config options to your dataset in your chart config.
$3
For linear trendlines (straight lines), use the trendlineLinear configuration:
`javascript
{
trendlineLinear: {
colorMin: Color,
colorMax: Color,
lineStyle: string, // "dotted" | "solid" | "dashed" | "dashdot"
width: number,
xAxisKey: string, // optional
yAxisKey: string, // optional
projection: boolean, // optional
trendoffset: number, // optional, if > 0 skips first n elements, if < 0 uses last n elements
// optional
label: {
color: Color,
text: string,
display: boolean,
displayValue: boolean, // shows slope value
offset: number,
percentage: boolean,
font: {
family: string,
size: number,
}
},
// optional
legend: {
text: string,
strokeStyle: Color,
fillStyle: Color,
lineCap: string,
lineDash: number[],
lineWidth: number,
}
}
}
`
$3
For exponential trendlines (curves of the form y = a × e^(b×x)), use the trendlineExponential configuration:
`javascript
{
trendlineExponential: {
colorMin: Color,
colorMax: Color,
lineStyle: string, // "dotted" | "solid" | "dashed" | "dashdot"
width: number,
xAxisKey: string, // optional
yAxisKey: string, // optional
projection: boolean, // optional
trendoffset: number, // optional, if > 0 skips first n elements, if < 0 uses last n elements
// optional
label: {
color: Color,
text: string,
display: boolean,
displayValue: boolean, // shows exponential parameters (a, b)
offset: number,
font: {
family: string,
size: number,
}
},
// optional
legend: {
text: string,
strokeStyle: Color,
fillStyle: Color,
lineCap: string,
lineDash: number[],
lineWidth: number,
}
}
}
`
Note: Exponential trendlines work best with positive y-values. The equation fitted is y = a × e^(b×x), where:
- a is the coefficient (scaling factor)
- b` is the growth rate (positive for growth, negative for decay)