Hi,
I want to create in regresiion line in scatter chart. As i have search it is available for python but not for javascript. Is there any alternative or did I missed the docs?
@Osama I think you are right, it looks as if the regression line exists built in in plotly.express
only.
I asked llama3
it came up with the following:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.plotly.com/plotly-2.16.1.min.js"></script>
</head>
<body>
<div id="graph"></div>
<script>
// Sample data
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const y = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];
// Calculate regression line
const math = Math;
const sum = (arr) => arr.reduce((a, b) => a + b, 0);
const mean = (arr) => sum(arr) / arr.length;
const variance = (arr) => sum(arr.map((x) => math.pow(x - mean(arr), 2))) / arr.length;
const covariance = (x, y) => sum(x.map((x, i) => (x - mean(x)) * (y[i] - mean(y)))) / x.length;
const slope = covariance(x, y) / variance(x);
const intercept = mean(y) - slope * mean(x);
const regressionLine = x.map((x) => slope * x + intercept);
// Create Plotly graph
const layout = {
title: 'Scatter Plot with Regression Line',
xaxis: { title: 'X' },
yaxis: { title: 'Y' },
};
const data = [
{
x: x,
y: y,
mode: 'markers',
type: 'scatter',
name: 'Data',
},
{
x: x,
y: regressionLine,
mode: 'lines',
type: 'scatter',
name: 'Regression Line',
},
];
Plotly.newPlot('graph', data, layout);
</script>
</body>
</html>
Hi @AIMPED , thanks for the solution😇. But the solution u have is giving and error: .reduce is not a function, coz the mean funtion is changing the array to 1. To correct that i have calculated the mean at first instead of calculating it inside other function. And finally came up whit this. Let me know if this is the same you are getting.
// Sample data
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const y = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];
// Calculate regression line
const math = Math;
const sum = (arr) => arr.reduce((a, b) => a + b, 0);
// Calculate means once and reuse
const meanX = sum(x) / x.length;
const meanY = sum(y) / y.length;
const variance = (arr, mean) => sum(arr.map((value) => math.pow(value - mean, 2))) / arr.length;
const covariance = (x, y, meanX, meanY) => sum(x.map((xVal, i) => (xVal - meanX) * (y[i] - meanY))) / x.length;
const slope = covariance(x, y, meanX, meanY) / variance(x, meanX);
const intercept = meanY - slope * meanX;
const regressionLine = x.map((xVal) => slope * xVal + intercept);
// Create Plotly graph
const layout = {
title: 'Scatter Plot with Regression Line',
xaxis: { title: 'X' },
yaxis: { title: 'Y' },
};
const data = [
{
x: x,
y: y,
mode: 'markers',
type: 'scatter',
name: 'Data',
},
{
x: x,
y: regressionLine,
mode: 'lines',
type: 'scatter',
name: 'Regression Line',
},
];
Plotly.newPlot('myDiv', data, layout);
Which resulting in something like this: