title: filtering data and working with scales - d3js
body: <p>I have a simple scatterplot in d3js. The aim of the visualization is to fade out points on a selection. This works. Congruent with this, a new trendline should appear only for those selected points as well as an updated slope equation and R2 value.  The fading of points and updating of slope equation/R2 values is working on selection.  However, the trendline appears to be truncated and not scaled correctly, but I can't figure out why.</p>
  
  <p><a href="http://blockbuilder.org/jalapic/18b997f9b1025b21470d058b918421b9" rel="nofollow noreferrer">Here is a working version.</a></p>
  
  <p>Following the <code>on.change</code> the following code is executed:</p>
  
  <pre><code>filteredData  = filterJSON(data, 'name', value); // gets filtered json data
  
    var x = d3.scaleLinear()
        .range([0,width]);
  
    var y = d3.scaleLinear()
        .range([height,0]);
  
  
    var xSeries1 = filteredData.map(function(e) { return e.x; }); // new x values
    var ySeries1 = filteredData.map(function(e) { return e.y; }); // new y values
    var rsq1 = leastSquares(xSeries1,ySeries1); // calculates r2/slope etc. - see function below
  
   // Add trendline
    ptAx1 =  d3.min(xSeries1);
    ptAy1 =  rsq1[0] *  d3.min(xSeries1) + rsq1[1];
    ptBy1 =  d3.min(ySeries1);
    ptBx1 =  (d3.min(ySeries1) - rsq1[1]) / rsq1[0];
  
  
  
    svg.append("line")
          .attr("class", "regression")
          .attr("x1", x(ptAx1))   
          .attr("y1", y(ptAy1))
          .attr("x2", x(ptBx1))
          .attr("y2", y(ptBy1));
  
  
  
  
  // calculate linear regression
  function leastSquares(xSeries,ySeries) {
  
    var reduceSumFunc = function(prev, cur) { return prev + cur; };
  
    var xBar = xSeries.reduce(reduceSumFunc) * 1.0 / xSeries.length;
    var yBar = ySeries.reduce(reduceSumFunc) * 1.0 / ySeries.length;
  
    var ssXX = xSeries.map(function(d) { return Math.pow(d - xBar, 2); })
      .reduce(reduceSumFunc);
  
    var ssYY = ySeries.map(function(d) { return Math.pow(d - yBar, 2); })
      .reduce(reduceSumFunc);
  
    var ssXY = xSeries.map(function(d, i) { return (d - xBar) * (ySeries[i] - yBar); })
      .reduce(reduceSumFunc);
  
    var slope = ssXY / ssXX;
    var intercept = yBar - (xBar * slope);
    var rSquare = Math.pow(ssXY, 2) / (ssXX * ssYY);
  
    return [slope, intercept, rSquare];
  }
  </code></pre>
  
  <p>This code works well when all data points (no filtering of data), but doesn't when filtering occurs.</p>
  
  <p>This is all points - trendline ok
  <a href="https://i.stack.imgur.com/IH1xa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IH1xa.png" alt="enter image description here"></a></p>
  
  <p>This is filtered points - trendline truncated
  <a href="https://i.stack.imgur.com/JRkvF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JRkvF.png" alt="enter image description here"></a></p>