FLOT中的趋势线

Gow*_*wri 1 flot

我列入jquery.flot.trendline.js. 从这里

这是我的代码

$.plot($("#placeholder"), seriesdata, {
        series: {
     trendline: {
        show:true,
        lineWidth:2,
        fill:true,
        fillColor:false,
        steps:true
    },
    ...
});
Run Code Online (Sandbox Code Playgroud)

我没有在图表中获得趋势线.

Mar*_*ark 10

那个插件是不行的.它需要修改flot源才能工作,在我看来并不是很好.最简单的方法是自己添加趋势线作为附加系列.数学并不困难......

  // calc slope and intercept
  // then use resulting y = mx + b to create trendline
  lineFit = function(points){
    sI = slopeAndIntercept(points);
    if (sI){
      // we have slope/intercept, get points on fit line
      var N = points.length;
      var rV = [];
      rV.push([points[0][0], sI.slope * points[0][0] + sI.intercept]);
      rV.push([points[N-1][0], sI.slope * points[N-1][0] + sI.intercept]);
      return rV;
    }
    return [];
  }

  // simple linear regression
  slopeAndIntercept = function(points){
    var rV = {},
        N = points.length,
        sumX = 0, 
        sumY = 0,
        sumXx = 0,
        sumYy = 0,
        sumXy = 0;

    // can't fit with 0 or 1 point
    if (N < 2){
      return rV;
    }    

    for (var i = 0; i < N; i++){
      var x = points[i][0],
          y = points[i][1];
      sumX += x;
      sumY += y;
      sumXx += (x*x);
      sumYy += (y*y);
      sumXy += (x*y);
    }

    // calc slope and intercept
    rV['slope'] = ((N * sumXy) - (sumX * sumY)) / (N * sumXx - (sumX*sumX));
    rV['intercept'] = (sumY - rV['slope'] * sumX) / N;
    rV['rSquared'] = Math.abs((rV['slope'] * (sumXy - (sumX * sumY) / N)) / (sumYy - ((sumY * sumY) / N)));

    return rV;
  }
Run Code Online (Sandbox Code Playgroud)

然后你可以这称为:

  lineFitSeries = lineFit(someSeries);
Run Code Online (Sandbox Code Playgroud)

并添加lineFitSeries作为另一个系列来flot ...

这是一个有效的例子.

在此输入图像描述