echarts散点图自动生成公式

看到此文章, 我想你大概率是和我此时一样, 想弄一个散点图但公式没有头绪

直接上代码,

以下是利用散点图自动生成线性回归公式

  const data = [
    [1000,1100],
    [1100,1200],
    [1200,1300],
    [1300,1400],
    [1400,1500]
  ]
  // 计算平均值
  const calculateMean = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length

  // 计算斜率
  const calculateSlope = (xValues, yValues, xMean, yMean) =>
    // 0 + (1000 - 平均值(1200)) *(1100 - y轴平均值(1300)) / 0 + 1000 - x平均值(1200) * 2 = ...
    // 累加:(x当前值 - x当前平均值) * (y当前值 - y当前平均值) / (x当前值 - x平均值) * (x当前值 - x平均值)
    // 0 + 1000 - 1200 * 1100 - 1300 = 40000
    // 40000 + 1100 - 1200 * 1200 - 1300 = 50000
    // 50000 + 1200 - 1200 * 1300 - 1300 = 50000
    // 50000 + 1300 - 1200 * 1400 - 1300 = 60000
    xValues.reduce((acc, _, i) => acc + (xValues[i] - xMean) * (yValues[i] - yMean), 0) /
    xValues.reduce((acc, _, i) => acc + Math.pow(xValues[i] - xMean, 2), 0)

  // 计算截距 (y平均值 - (斜率 * x平均值))
  const calculateIntercept = (xMean, yMean, slope) => yMean - slope * xMean // 1300 - 1 * 1200 = 100

  // 计算拟合公式字符串
  const generateFitEquation = (slope, intercept) => `y = ${slope.toFixed(0)}x + ${intercept.toFixed(0)}`

  // 计算拟合参数
  const xValues = data.map(point => point[0])
  const yValues = data.map(point => point[1])
  // X平均值
  const xMean = calculateMean(xValues)
  // Y平均值
  const yMean = calculateMean(yValues)
  // 斜率值
  const slope = calculateSlope(xValues, yValues, xMean, yMean)
  // 截距
  const intercept = calculateIntercept(xMean, yMean, slope)
  // 存储公式
  const fitEquation = generateFitEquation(slope, intercept)
  // console.log('xMean', xMean)
  // console.log('yMean', yMean)
  // console.log('slope', slope)
  // console.log('intercept', intercept)
  // console.log('拟合公式:', fitEquation)
  const formula = fitEquation

效果图如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值