Drawing the axes
We learn how to create axes and transform them into position.
Let's start with the y axis. d3's d3-axis module has axis generator methods which will draw an axis for the given scale.
Unlike the methods we've used before, d3 axis generators will append multiple elements to the page.
There is one method for each orientation, which will specify the placement of labels and tick marks:
Following common convention, we want the labels of our y axis to be to the left of the axis line, so we'll use
d3.axisLeft() and pass it our y scale.
When we call our axis generator, it will create a lot of elements — let's create a
g element to hold all of those elements and keep our DOM organized. Then we'll pass that new element to our
yAxisGenerator function to tell it where to draw our axis.
This method works but it will break up our chained methods. To fix this, d3 selections have a
.call() method that will execute the provided function with the selection as the first parameter.
We can use
prevent saving our selection as a variable, and
preserve the selection for additional chaining.
Note that this code does exactly the same thing as the snippet above - we are passing the function
.call(), which then runs the function for us.