Replicate Excel Power Trendline values in chart - Javascript highcharts

Javascript examples for highcharts:Line Chart

Description

Replicate Excel Power Trendline values in chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Highcharts Demo</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
      <script type="text/javascript">
    $(function(){//from   ww  w  .j a  va 2  s .c o m
var data = [
  [1, 1],
  [2, 5],
  [3, 11],
  [4, 20],
  [5, 38],
  [6, 60],
  [7, 121],
  [8, 161],
  [9, 221],
  [10, 278]
];
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;
}
var chart = new Highcharts.Chart('container', {
  tooltip: {
    shared: true
  },
  series: [{
    name: 'Experimental points',
    lineWidth: 0,
    data: data,
    states: {
      hover: {
        lineWidthPlus: 0
      }
    }
  }, {
    name: 'Theoretical (fitted) points',
    data: getFittedPoints(data)
  }]
});
    });

      </script> 
   </head> 
   <body> 
      <script src="https://code.highcharts.com/highcharts.js"></script> 
      <div id="container"> 
      </div>  
   </body>
</html>

Related Tutorials