Highcharts provides a wide range of chart types and options for customization. In this article, we will explore the scatter plot with trend line demo.
Dataset
Let's start by defining our dataset:
const dataset = [
[1.4, 0.4],
[2.4, 5.3],
[2.9, 4.9],
[5, 2.3],
[3.6, 1.9],
[5.1, 6.1],
[2, 4],
[2, 5.6],
[-0.2, 6.3],
[1.2, 6.3]
];
This dataset consists of 10 data points with x and y values.
Trend Line
To create a trend line, we will use the getTrendLine
function:
function getTrendLine(data) {
const n = data.length;
let sumX = 0,
sumY = 0,
sumXY = 0,
sumX2 = 0;
for (let i = 0; i < n; i++) {
const [x, y] = data[i];
sumX += x;
sumY += y;
sumXY += x * y;
sumX2 += x ** 2;
}
const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX ** 2);
const intercept = (sumY - slope * sumX) / n;
const trendline = [];
const minX = Math.min(...data.map(([x]) => x));
const maxX = Math.max(...data.map(([x]) => x));
trendline.push([minX, minX * slope + intercept]);
trendline.push([maxX, maxX * slope + intercept]);
return trendline;
}
This function calculates the slope and intercept of a linear regression line using the dataset.
Highcharts Chart
Now, let's create our Highcharts chart:
Highcharts.chart('container', {
title: {
text: 'Scatter plot with trend line'
},
xAxis: {
min: -0.5,
max: 5.5
},
yAxis: {
min: 0
},
series: [{
type: 'line',
name: 'Trend Line',
data: getTrendLine(dataset),
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
enableMouseTracking: false
}, {
type: 'scatter',
name: 'Observations',
data: dataset,
marker: {
radius: 4
}
}]
});
In this chart, we have two series:
- A line series for the trend line
- A scatter series for our observations
##In this article, we demonstrated how to create a scatter plot with a trend line using Highcharts. We defined our dataset and implemented a function to calculate the slope and intercept of the trend line. Finally, we created our Highcharts chart and displayed it in the browser.
References
- Highcharts: https://www.highcharts.com/
- NPM package:
npm install highcharts --save
- Downloadable library: https://www.highcharts.com/download
- License pricing: https://www.highcharts.com/pricing