Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the previous datum in a join

Tags:

d3.js

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.

like image 868
Brian Genisio Avatar asked Nov 03 '22 21:11

Brian Genisio


1 Answers

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
  });
like image 100
Brian Genisio Avatar answered Dec 06 '22 03:12

Brian Genisio