gpt4 book ai didi

javascript - 如何向 CanvasJS 中的散点图添加一条最佳拟合线(趋势线)?

转载 作者:行者123 更新时间:2023-11-29 20:29:41 25 4
gpt4 key购买 nike

我有一个包含大量数据的散点图,太多无法显示给用户。我想在图表中添加一条最佳拟合线或“趋势线”以显示趋势并使散点图不可见。我的数据以以下格式存储在外部 JSON 文件中:

{
"X" : [1,2,3,4,5,6,7,8,9...],
"Y" : [1,2,3,4,5,6,7,8,9...]
}

我正在使用这段代码显示我的数据:

function addData(data){
console.log("Adding data");
var gradeMaxLength = 0;

for( var i = 0; i < data.length; i++ ){
if( gradeMaxLength < data[i].grade.length ){
gradeMaxLength = data[i].grade.length;
}
}

// addding datSeries
for( var j = 0; j < gradeMaxLength; j++ ){
chart.options.data.push({
type:"scatter",
dataPoints:[]
});
}

// adding dataPoints
for( var k = 0; k < data.length; k++ ){
for( var l = 0; l < gradeMaxLength; l++ ){
chart.options.data[l].dataPoints.push({
x: data[k].present[l],
y: data[k].grade[l]
}
);
}
}
chart.render();
}

有没有一种方法可以在我的图表中添加一条最适合的线,我在下面附上了一张照片?

Graph

最佳答案

对于 canvasJS,您可以使用这段代码。我自己用了一段时间,但效果很好!

在你的 chart.render() 之后添加这个;

    calculateTrendLine(chart);
function calculateTrendLine(chart){
var a, b, c, d, e, slope, yIntercept;
var xSum = 0, ySum = 0, xySum = 0, xSquare = 0, dpsLength = chart.data[0].dataPoints.length;
for(var i = 0; i < dpsLength; i++)
xySum += (chart.data[0].dataPoints[i].x * chart.data[0].dataPoints[i].y)
a = xySum * dpsLength;

for(var i = 0; i < dpsLength; i++){
xSum += chart.data[0].dataPoints[i].x;
ySum += chart.data[0].dataPoints[i].y;
}
b = xSum * ySum;

for(var i = 0; i < dpsLength; i++)
xSquare += Math.pow(chart.data[0].dataPoints[i].x, 2);
c = dpsLength * xSquare;

d = Math.pow(xSum, 2);
slope = (a-b)/(c-d);
e = slope * xSum;
yIntercept = (ySum - e) / dpsLength;

var startPoint = getTrendLinePoint(chart.data[0].dataPoints[0].x, slope, yIntercept);
var endPoint = getTrendLinePoint(chart.data[0].dataPoints[dpsLength-1].x, slope, yIntercept);

chart.addTo("data",{
type: "line", //Line series showing trend
markerSize: 0,
dataPoints: [startPoint, endPoint]
});
}

function getTrendLinePoint(x, slope, intercept){
return {x: x, y: ((slope * x) + intercept)};
}

关于javascript - 如何向 CanvasJS 中的散点图添加一条最佳拟合线(趋势线)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58643111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com