Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 148 lines (130 sloc) 4.824 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
    <title>Linear Regression</title>
    <!--[if IE]>
<script type="text/javascript" src="../excanvas.js"></script>
<![endif]-->
    <!--
For production (minified) code, use:
<script type="text/javascript" src="dygraph-combined.js"></script>
-->
    <script type="text/javascript" src="../dygraph-dev.js"></script>

    <style type="text/css">
    body { max-width: 640 px; }
    </style>
  </head>
  <body>
    <h2>Linear Regression Demo</h2>
    <p>Click the buttons to generate linear regressions over either data
    series. If you zoom in and click the regression button, the regression will
    only be run over visible points. Zoom back out to see what the local
    regression looks like over the full data.</p>

    <div id="demodiv" style="width: 480px; height: 320px;"></div>

    <script type="text/javascript">
      var data = [];
      for (var i = 0; i < 120; i++) {
        data.push([i,
                   i / 5.0 + 10.0 * Math.sin(i / 3.0),
                   30.0 - i / 5.0 - 10.0 * Math.sin(i / 3.0 + 1.0)]);
      }
      var labels = ['X', 'Y1', 'Y2'];
      var orig_colors = [];

      g = new Dygraph(
              document.getElementById("demodiv"),
              data,
              {
                labels: labels,
                drawPoints: true,
                strokeWidth: 0.0,
                drawCallback: function(g, is_initial) {
                  if (!is_initial) return;
                  var c = g.getColors();
                  for (var i = 0; i < c.length; i++) orig_colors.push(c[i]);
                }
              }
          );

      // coefficients of regression for each series.
      // if coeffs = [ null, [1, 2], null ] then we draw a regression for series 1
      // only. The regression line is y = 1 + 2 * x.
      var coeffs = [ null, null, null ];
      function regression(series) {
        // Only run the regression over visible points.
        var range = g.xAxisRange();

        var sum_xy = 0.0, sum_x = 0.0, sum_y = 0.0, sum_x2 = 0.0, num = 0;
        for (var i = 0; i < data.length; i++) {
          var x = data[i][0];
          if (x < range[0] || x > range[1]) continue;

          var y = data[i][series];
          if (y == null) continue;
          if (y.length == 2) {
            // using fractions
            y = y[0] / y[1];
          }

          num++;
          sum_x += x;
          sum_y += y;
          sum_xy += x * y;
          sum_x2 += x * x;
        }

        var a = (sum_xy - sum_x * sum_y / num) / (sum_x2 - sum_x * sum_x / num);
        var b = (sum_y - a * sum_x) / num;

        coeffs[series] = [b, a];
        if (typeof(console) != 'undefined') {
          console.log("coeffs(" + series + "): [" + b + ", " + a + "]");
        }

        updateChart();
      }

      function updateChart() {
        // Generate a new data set with the regression lines.
        var new_labels = [];
        var new_colors = [];
        var new_opts = {};
        for (var i = 0; i < labels.length; i++) {
          new_labels.push(labels[i]);
          if (i) new_colors.push(orig_colors[i - 1]);
          if (coeffs[i]) {
            // Darken the series by 50% to generate its regression.
            var label = labels[i] + " Regression";
            new_labels.push(label);
            var c = new RGBColorParser(orig_colors[i - 1]);
            c.r = Math.floor(255 - 0.5 * (255 - c.r));
            c.g = Math.floor(255 - 0.5 * (255 - c.g));
            c.b = Math.floor(255 - 0.5 * (255 - c.b));
            new_colors.push(c.toHex());
            new_opts[label] = {
              drawPoints: false,
              strokeWidth: 1.0
            };
          }
        }

        var new_data = [];
        for (var i = 0; i < data.length; i++) {
          new_data.push([]);
          for (var j = 0; j < data[i].length; j++) {
            new_data[i].push(data[i][j]);
            if (coeffs[j]) {
              new_data[i].push(coeffs[j][0] + coeffs[j][1] * data[i][0]);
            }
          }
        }

        new_opts.file = new_data;
        new_opts.labels = new_labels;
        new_opts.colors = new_colors;
        g.updateOptions(new_opts);
      }

      function clearLines() {
        for (var i = 0; i < coeffs.length; i++) coeffs[i] = null;
        updateChart();
      }
      
    </script>
    
    <div style="position: absolute; left: 500px; top: 150px;">
    <input type=button style="color: green;" value="Regression (Y1)" onClick="regression(1)" />
    <br/><br/>
    <input type=button style="color: blue;" value="Regression (Y2)" onClick="regression(2)" />
    <br/><br/>
    <input type=button value="Clear Lines" onClick="clearLines()" />
    </div>
</body>
</html>
Something went wrong with that request. Please try again.