Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3js: When to use .datum() and .data()?

Tags:

d3.js

nvd3.js

I often see .datum when an area chart is used. For example:

svg = d3.select("#viz").append("svg").datum(data) 

Are there any rules of thumb for when .datum is needed?

var area = d3.svg.area()       .x(function(d) { return x(d.x); })       .y0(height)       .y1(function(d) { return y(d.y); });    var svg = d3.select("body").append("svg")       .attr("width", width)       .attr("height", height);    svg.append("path")      .datum(data)     .attr("d", area);  
like image 469
Bobby Gifford Avatar asked Nov 01 '12 16:11

Bobby Gifford


1 Answers

I think the documentation gives a good answer to this question: https://github.com/mbostock/d3/wiki/Selections#wiki-datum.

Basically, the point is that in some cases you are not interested in the enter/exit sets when you do a selection. If this is the case, which often seems to be the case for the full chart, you use datum.

Update: It depends: when you expect no dynamic updates, which seems to be the case in your given example, datum is okay. Why? Because there is no path svg element yet, there is only one path element and once it is added it will not change.

If you where to have multiple path elements and dynamic changes (e.g. after each second the oldest data element gets removed and a new one gets added), than you will need data. This will give you three sets: the sets of graphic elements for which no data exists any longer, the set of elements for which the data is updated and the set of elements for which no data item existed before (respectively, the enter, update and exit sets). Once you need this I suggest you read up on the d3 documentation.

Obviously, calculating these three sets is not without a cost. In practice, this should only become a problem when you're working with "large" (I think d3 scales up to 10s of thousands of items) data sets.

like image 187
Bertjan Broeksema Avatar answered Sep 18 '22 06:09

Bertjan Broeksema