Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js - how selections work - Need clarification on Mike's article

In http://bost.ocks.org/mike/selection/, Mike talks about applying functions on selections.

When you use a function to define a selection.attr or selection.style, the function is called for each element; the main difference with grouping is that the second argument to your function (i) is the within-group index rather than the within-selection index.

This might be simple, but for some reason, I can't completely understand this point. Would anyone be kind enough to explain this with an example.

like image 749
Arun J Avatar asked Aug 14 '15 15:08

Arun J


1 Answers

the main difference with grouping is that the second argument to your function (i) is the within-group index rather than the within-selection index.

Remember the index passed in to any attr, style, etc. functions in d3?

...
.attr('something', function(d, index) {
     // major gymnastics with d and index
}

So when you do a selectAll, the index starts from 0 for each group.

So, if you do two chained selectAlls where the first (group) levels are rows (tr) and the second (child) levels are cells (td), you'd have the following passed in as indices for a 2 rows x 3 cells table

0, 1, 2, 0, 1, 2

instead of

0, 1, 3, 4, 5, 6

which is what you'd expect when you select just 6 nodes with a single selectAll.


The following snippet of code illustrates this

    d3.selectAll("#a tr").selectAll("td").text(function(d, index) {
      return index;
    })

     d3.selectAll("#b td").text(function(d, index) {
      return index;
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Grouped cells (i.e. 2 selectAll)
<table id="a">
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

Ungrouped cells (i.e. 1 selectAll)
<table id="b">
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

The first animation on the page you linked to (http://bost.ocks.org/mike/selection/) illustrates this pretty well - here's a marked up version of the same

enter image description here

like image 168
potatopeelings Avatar answered Sep 29 '22 11:09

potatopeelings