Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 selectAll: count results

How do I count how many nodes were matched by a selectAll? (without joined data)

Or if there's data, how to count the data from the selection? (suppose I've set it with "data(function...)" so I don't know the length in advance)

like image 682
Victor Basso Avatar asked Jul 03 '15 14:07

Victor Basso


People also ask

What is selectAll in D3?

selectAll() function in D3. js is used to select all the element that matches the specified selector string. Syntax: d3.selectAll("element") Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.

How does D3 select work?

select() function in D3. js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.

What is or are the main selection in D3?

D3 provides two top-level methods for selecting elements: select and selectAll. These methods accept selector strings; the former selects only the first matching element, while the latter selects all matching elements in document traversal order.


2 Answers

Just use d3.selectAll(data).size().Hope this example help you:

 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; });  var tdSize=tr.selectAll("td").size(); 

Complete jsfiddle here.

like image 168
Gabriel Avatar answered Sep 19 '22 20:09

Gabriel


One way I have done this previously is to pass that information into the data function by making a new object.

 .data(function(d) {               return d.Objects.map(function(obj) {          return {              Object: obj,              TotalObjects: d.Objects.length          }    }); 

Then in your update portions you use Object and still have the count available.

.attr("x", function(d) {      return d.Object.X;  })  .attr("y", function(d) {      return d.TotalObjects;  }) 
like image 35
Andy Lewis Avatar answered Sep 16 '22 20:09

Andy Lewis