Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does .data(function(d) { return d; }) return in d3?

var matrix = [
  [11975,  5871, 8916, 2868],
  [ 1951, 10048, 2060, 6171],
  [ 8010, 16145, 8090, 8045],
  [ 1013,   990,  940, 6907]
];

var tr = d3.select("body").append("table").selectAll("tr")
    .data(matrix)
  .enter().append("tr");

var td = tr.selectAll("td")
    .data(function(d) { return d; })
  .enter().append("td")
    .text(function(d) { return d; });

I don't understand what d is representing here. Could someone so kindly walk me through the code?

Reference: https://github.com/mbostock/d3/wiki/Selections#wiki-remove

like image 788
user3311274 Avatar asked Oct 02 '22 14:10

user3311274


1 Answers

What you have here is a nested selection, i.e. you're making a selection and then a selection based on that. This is also the explanation for the function in the .data() argument -- it is nested below the first, so it can refer to it.

In particular, you're passing in an array of arrays in .data(matrix). D3 will do something for every element of that matrix, i.e. for every array. Here, it is bound to the appended tr elements. So then when you call .data() again, you can refer to the data bound to those elements (the trs). function(d) { return d; } is simply saying that D3 should use the data already bound to it. As that is an array, D3 will do something for every element of it, i.e. append the table cell elements.

like image 190
Lars Kotthoff Avatar answered Oct 05 '22 13:10

Lars Kotthoff