D3.js provides usefull instructions to create axes in charts. Before creating an axis,
you need to understand how the scale()
function works since this is used
for scaling the axes. If you are not familiar with the scale()
function, read
Part 10 of this tutorial before the following.
To create a bottom axis, you first have to create a scale function. In this example, we'll create an axis from 0 to 10. Our SVG container is 200 pixels width, so let's add 20 pixels margin to the left and right. Our scaling function becomes:
var xScale = d3.scaleLinear()
.domain([0, 20])
.range([80, 180]);
The following syntax creates the axis:
svg.append('g').call(d3.axisBottom(xScale));
The call()
function is used to invokes the function d3.axisBottom()
exactly once,
passing in the selection along with any optional arguments. More detailled
explanation can be found here.
Here is the axes draw in the SVG container:
Of course, we usualy want to place the bottom axis at the bottom of the chart. So, let's translate the axis:
svg.append('g')
.attr('transform', 'translate(0, 80)')
.call(d3.axisBottom(xScale));
Our axis is now placed at the bottom of our chart:
The others axes are exactly based on the same principle:
Note here how the ticks()
function is used to specify the number of ticks in the left and right axes:
// Right axis
svg.append('g')
.attr('transform', 'translate(380, 0)')
.call(d3.axisRight(yScale).ticks(5))