Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create elements depending on data in D3?

looking at sample:

d3.select("body").selectAll("div")     .data([4, 8, 15, 16, 23, 42])   .enter().append("div")     .text(function(d) { return d; }); 

cant help but wonder how to make append sensitive to provided data - say do append and fill text with some predicate say if d == 8 othervise do not append?

like image 523
DuckQueen Avatar asked Jul 18 '13 12:07

DuckQueen


People also ask

What does .data do in D3?

data() D3 is data driven. The data() function is used to join the specified array of data to the selected DOM elements and return the updated selection. D3 works with different types of data like Array, CSV, TSV, JSON, XML etc.

What is attr in D3?

attr() function is used to set the attribute of the element that is selected. The name of the attribute and value of the attributes are to be set using this function.

What does the every () method do in D3?

each() function in D3. js is used to call the particular function for each selected HTML elements. In function datum(d) and index(i) are given as the parameters.

What do the select () and selectAll () functions in D3 do?

d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.


1 Answers

The simplest way is to filter your array before calling .data( ... ):

d3.select("body").selectAll("p")     .data([4, 8, 15, 16, 23, 42].filter(function(d){ return d < 10; }))   .enter().append("div")     .text(function(d) { return d; }); 

will create a div only for 4 and 8.

Alternatively, you can filter your selection after binding your array to elements on the page to conditionally create children elements:

d3.select("body").selectAll("div")     .data([4, 8, 15, 16, 23, 42])   .enter().append("div")     .text(function(d) { return d; })  .filter(function(d){ return d == 8; }).append("span")     .text("Equal to 8") 
like image 99
Adam Pearce Avatar answered Oct 03 '22 04:10

Adam Pearce