D3.js tutorial - Part 12 - Axes


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.

Bottom axis

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:


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:

Translating the axis

Of course, we usualy want to place the bottom axis at the bottom of the chart. So, let's translate the axis:

    .attr('transform', 'translate(0, 80)')

Our axis is now placed at the bottom of our chart:

Axes to the right, left and top

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   
    .attr('transform', 'translate(380, 0)')

See also

Last update : 05/14/2021