FriconiX
Free collection of beautiful vector icons for your web pages.

D3.js tutorial - Part 12 - Axes

Introduction

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:

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 explaination 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:

svg.append('g')
    .attr('transform', 'translate(0, 80)')
    .call(d3.axisBottom(xScale));

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   
svg.append('g')
    .attr('transform', 'translate(380, 0)')
    .call(d3.axisRight(yScale).ticks(5))

See also


Last update : 01/29/2020