Search code examples
c#highchartstrendline

Replicate Excel Power Trendline values with c#


I need to replicate this Excel graph in code

enter image description here

Given a list of [x, y] values, how can I obtain a new list of values to graph the power trendline?

I've found people referring to this http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html formula. But don't know how to generate a new list of values from this.


Solution

  • Follow the formula from the link:

    function getFittedPoints(data) {
      var log = Math.log,
        pow = Math.pow,
    
        sums = [
            0, // sum of the logarithms of x ( sum(log(x)) )
            0, // sum of the logarithms of y ( sum(log(y)) )
            0, // sum of the logarithms of the products of x and y ( sum(log(x) * log(y)) )
            0 // sum of the powers of the logarithms of x ( sum((log(x))^2 )
        ],
        fittedPoints = [], // return fitted points
        a, // a coefficient
        b, // b coefficient
    
        dataLen = data.length,
        i,
        logX,
        logY;
    
      for (i = 0; i < dataLen; i++) {
        sums[0] += logX = log(data[i][0]);
        sums[1] += logY = log(data[i][1]);
        sums[2] += logX * logY;
        sums[3] += pow(logX, 2);
      }
    
      b = (i * sums[2] - sums[0] * sums[1]) / (i * sums[3] - pow(sums[0], 2));
      a = pow(Math.E, (sums[1] - b * sums[0]) / i);
    
      for (i = 0; i < dataLen; i++) {
        fittedPoints.push([
            data[i][0],
            a * pow(data[i][0], b)
        ]);
      }
    
      return fittedPoints;
    }
    

    And then apply the function to the data.

    example: http://jsfiddle.net/fa3m4Lvf/

    Of course if your data are not clean then you can improve the function with handling null values,etc.