简体   繁体   中英

d3 js line graph takes two different data formats. how do I differentiate those two?

While studying animated line chart of d3.

I ran into two different ways of making line charts and still can't differentiate the difference between the two.

Two cases are as below.

1) case one - drawing line by .attr(d, line(data)) 2) case two - drawing line by .attr (d, function(d){return line(d)})

Why some cases line is drawn by just calling the line function, while the other case asks me to make a anonymous function and put the line function within that?

Here are the sample cases I ran into.

1) case one example
https://bl.ocks.org/pjsier/28d1d410b64dcd74d9dab348514ed256

2) case two example
https://bl.ocks.org/phvaillant/53b90038b9c5ac5f6b817a4f63fbc2af

Whenever you see function(d) {...} as a parameter of .attr() , .style() , .data() , .datum() , .each() and a few others, d refers to the bound datum of each element in the selection.

But if you see a line drawn as in the first approach:

.attr("d", line(data))`

Every element in the selection will be given the same line: line(data) will return the same value for every element in the selection. This approach might be taken if you haven't bound any data to the selection. To draw multiple different lines we'd need to use a loop of some sort and change the value of data . If binding data to the selection (which is a key purpose of D3), you should use that bound data as in the second approach - it'll be easier if you decide to have more than one line.

In the second approach:

.attr("d", function(d) { return line(d); })

The bound datum each element in the selection is passed to line() , as the bound datum for each line can be different, you can have different lines without an explicit loop. For multiple lines, this would certainly be the idiomatic method, though for single lines, the difference is, honestly, fairly negligible.


I didn't actually see .attr("d", line(data)) in the first example's link, the first example's link seems to have instead .attr("d", line) , which is equivalent to the second example:

In the second example, this:

.attr("d", function(d) { return line(d); })

Is equivalent to:

.attr("d", line);

In the simpler line the bound datum is passed to line and line is executed for each item in the selection. Here's the same block updated to demonstrate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM