Accepted answer

To add a line to your plot, all that you need to do is to append some line SVGs to your main SVG (chart) or to the group that contains your SVG elements (main).

Your code would look something like the following:


This would draw a line from (10,5) to (20,10). You could similarly create a data set for your lines and append a whole bunch of them.

One thing you might be interested in is the SVG path element. This is more common for lines than drawing one straight segment at a time. The documentation is here.

On another note you may find it easier to work with data in d3 if you create it all as one object. For example, if your data was in the following form:

data = [{x: 5, y:3}, {x: 10, y:17}, {x: 15, y:4}, {x: 20, y:6}]

You could use:

  .data(ydata)  // using the values in the ydata array
  .enter().append("svg:circle")  // create a new circle for each value
      .attr("cy", function (d) { return y(d.y); } ) //set y
      .attr("cx", function (d,i) { return x(d.x); } ) //set x

This would eliminate potentially messy indexing if your data gets more complex.


UPDATE: Here is the relevant block:

I wrote this function to calculate a linear regression from data, formatted as JSON.

It takes 5 parameters: 1) Your data 2) The column name of the data plotted on your x-axis 3) The column name of the data plotted on your y-axis 4) The minimum value of your x-axis 5) The minimum value of your y-axis

I got the formula for calculating a linear regression from

function calcLinear(data, x, y, minX, minY){

  // Let n = the number of data points
  var n = data.length;

  var pts = [];
    var obj = {};
    obj.x = d[x];
    obj.y = d[y];
    obj.mult = obj.x*obj.y;

  // Let a equal n times the summation of all x-values multiplied by their corresponding y-values
  // Let b equal the sum of all x-values times the sum of all y-values
  // Let c equal n times the sum of all squared x-values
  // Let d equal the squared sum of all x-values
  var sum = 0;
  var xSum = 0;
  var ySum = 0;
  var sumSq = 0;
    sum = sum + pt.mult;
    xSum = xSum + pt.x;
    ySum = ySum + pt.y;
    sumSq = sumSq + (pt.x * pt.x);
  var a = sum * n;
  var b = xSum * ySum;
  var c = sumSq * n;
  var d = xSum * xSum;

  // Plug the values that you calculated for a, b, c, and d into the following equation to calculate the slope
  //  m = (a - b) / (c - d)
  var m = (a - b) / (c - d);


  // Let e equal the sum of all y-values
  var e = ySum;

  // Let f equal the slope times the sum of all x-values
  var f = m * xSum;

  // Plug the values you have calculated for e and f into the following equation for the y-intercept
  // y-intercept = b = (e - f) / n = (14.5 - 10.5) / 3 = 1.3
  var b = (e - f) / n;

  // return an object of two points
  // each point is an object with an x and y coordinate
  return {
    ptA : {
      x: minX,
      y: m * minX + b
    ptB : {
      y: minY,
      x: (minY - b) / m


Related Query

More Query from same tag