I am trying to learn the concepts of D3.js. I've realized that I might want to relate a current element to the previous element. Let's assume that I want to create a line graph and I am drawing from point to point. I might create something like this:
var data = [200, 300, 250];
var svg = d3.select('body').append('svg');
var lines = svg.selectAll('line').data(data);
lines.enter()
  .append('line')
  .attr( {
    'stroke-width': 2,
    stroke: '#000',
    x1: 0, y1: 0,
    x2: function(d, i) { return i * 50 + 50 },
    y2: function(d) { return d - 180; }
  });
(Codepen)
Notice, however, that my x1 and y1 values are zero.  I want these values to come from the previous datum.  How would I get access to the previous datum (assuming 0,0 if there is none)?
Note: I realize that the proper way to do draw a line graph is to create a single path and use the d3.svg.line generator function.  I'm not trying to solve a problem here.  I'm trying to understand the core concepts.
I came up with one approach. Decrement the index of the current datum:
var data = [200, 300, 250];
var svg = d3.select('body').append('svg');
var lines = svg.selectAll('line').data(data);
function x(d, i) { return i * 50 + 50; }
function y(d) { return d - 180; }
function previous(func, seed) {
  return function(d, i) {
    return i > 0 ? func(data[i-1], i-1) : (seed || 0);
  }
}
lines.enter()
  .append('line')
  .attr( {
    'stroke-width': 2,
    stroke: '#000',
    x1: previous(x), 
    y1: previous(y),
    x2: x,
    y2: y
  });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With