Now that we learned the essentials of scale in our previous section, we are all set up to draw axes in our SVG container. So lets see how to create an axis in D3. But before that we need to install the d3-axis module.
Drawing an axis
Lets see some code to draw an axis and then I will explain each line of code:
Ok here is the breakdown of the above code:
- First we create a svg container as D3 axis can be drawn inside an svg container, give it some dimension and set the border:
- Then we create the scale which will be used to create our axis:
- Use the scale to create an axis:
Here you saw the first axes method d3.axisBottom(). Lets discuss this method a bit and other such methods:
- d3.axisTop(scale) : A horizontal axis with labels placed on top of the axis
- d3.axisBottom(scale) : A horizontal axis with labels placed at the bottom of the axis
- d3.axisLeft(scale) : A vertical axis with labels placed on the left hand side of the axis
- d3.axisRight(scale) : A vertical axis with labels placed on the right hand side of the axis
- Create a group element ‘g’ inside the svg container and call the xAxis:
After this code D3 creates all the necessary svg elements for an axis. The code generated is shown below:
We can see D3 creates lot of svg elements to draw an axis. The important point to note here is the <g> tag with class a tick. Each tick in the axis is composed of a <g> element with a <line> and <text> element inside it. If we want to style a tick, we need to style the <line> and <text> element.
Another point which needs attention is that the xAxis is created on the top but wouldn’t it be good if the x-axis is placed at the bottom of the svg container like we normally see. To do that we need to translate the <g> (containing our axis svg elements) vertically to height – padding (here height is the height of svg container). This code does that:
You can uncomment the code in the above JS Bin demo and see this in effect.
d3-axis provides several methods to customize ticks in an axis. Below are some important ones:
- ticks() : This tells D3 how many ticks we want to render in the axis. But this is just a suggestion to D3. D3 can create slightly more or less ticks based on the available real estate and its own calculation.
- tickPadding() : Sets the space between tick labels and the axis.
- tickFormat() : Gives custom format to the labels
This will produce an axis as shown below
Drawing grid lines
Lets first look at what we are building:
This example is taken from Data Visualization with D3.js Cookbook (Drawing Grid Lines – Chapter 5).
Lets try to understand how it works:
With that we have covered the essential concepts of drawing and customizing axes in D3. Next up – Transitions