Trendline in FLOT

前端 未结 1 1158
梦毁少年i
梦毁少年i 2021-01-16 00:43

I included jquery.flot.trendline.js. From Here

It is my code

$.plot($(\"#placeholder\"), seriesdata, {
        series: {
     trendlin         


        
1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-16 00:59

    That plugin is a no-go. It requires modifications to the flot source to work and in my opinion isn't very well done. The simpliest approach would be to just add the trendline yourself as an additional series. The math is not difficult...

      // 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;
      }
    

    You can then call this as:

      lineFitSeries = lineFit(someSeries);
    

    And add the lineFitSeries as another series to flot...

    Here's a working example.

    enter image description here

    0 讨论(0)
提交回复
热议问题