I am not able to understand how d3.call() works and when and where to use that. Here is the tutorial link that I'm trying to complete.
Can someone please explain specifically what this piece is doing
var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); svg.append("g").call(xAxis);
D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS.
call is useful where you want a reusable function that operates on a selection. For example, colorAll takes a selection and sets the fill of the selection's elements to orange: function colorAll(selection) { selection . style('fill', 'orange'); } d3. selectAll('circle') .
g element is used to group SVG shapes together, so no it's not d3 specific.
js (also known as D3, short for Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. It makes use of Scalable Vector Graphics (SVG), HTML5, and Cascading Style Sheets (CSS) standards.
I think the trick here is to understand that xAxis is a function that generates a bunch of SVG elements. In fact it is the function returned by d3.svg.axis()
. The scale and orient functions are just part of the chaining syntax (read more of that here: http://alignedleft.com/tutorials/d3/chaining-methods/).
So svg.append("g")
appends an SVG group element to the svg and returns a reference to itself in the form of a selection (same chain syntax at work here). When you use call
on a selection you are calling the function named xAxis
on the elements of the selection g
. In this case you are running the axis function, xAxis
, on the newly created and appended group, g
.
If that still doesn't make sense, the syntax above is equivalent to:
xAxis(svg.append("g"));
or:
d3.svg.axis() .scale(xScale) .orient("bottom")(svg.append("g"));
What the accepted answer left out IMO is that .call()
is a D3 API function and not to be confused with Function.prototype.call()
selection.call(function[, arguments…])
Invokes the specified function exactly once, passing in this selection along with any optional arguments. Returns this selection. This is equivalent to invoking the function by hand but facilitates method chaining. For example, to set several styles in a reusable function:
Now say:
d3.selectAll("div").call(name, "John", "Snow");
This is roughly equivalent to:
name(d3.selectAll("div"), "John", "Snow");
where name is a function, for example
function name(selection, first, last) { selection .attr("first-name", first) .attr("last-name", last); }
The only difference is that selection.call always returns the selection and not the return value of the called function, name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With