Axis

Learn how to draw the x-axis and y-axis.

We'll cover the following

Before we start drawing charts, let’s explore the fundamental building block of the chart, the axis. An axis provides human readability to visualization. An axis uses scales, and each axis will need its own scale to work with.

D3.js provides the following four functions to draw the scales.

  • d3.axisBottom() creates a bottom horizontal axis.
  • d3.axisTop() creates a top horizontal axis.
  • d3.axisLeft() creates a left vertical axis.
  • d3.axisRight() creates a right vertical axis.

Let’s explore and draw the x-axis and y-axis below.

Draw x-axis

We are going to demonstrate the x-axis through an example. As we have discussed above, we use the d3.axisBottom() to draw the bottom horizontal axis. Let’s use it to draw the x-axis in the following code.

Drawing x-axis

Explanation

Let’s discuss the above code to better understand how it works.

  • Line 1-6: We have defined an SVG of size (250x350).
  • Then, we have defined some data. With the help of this data, we will define the x-axis.
  • Line 13-15: We have defined a scale, xscale, which is required to draw the axis. The domain of this scale will range from the min to max value of X in the data. d3.extent() is called on X values of the data set, which will return the min and max values of X. Then we have mapped these values in the domain to range (0,300). The domain values will be mapped to 300 pixels in the SVG canvas as specified by the range.
  • In the last three lines of code, we have appended a non-graphical element, g, using the append() function. Then we have added the x-axis using the call() function. The SVG origin lies at the top left corners, so the translate() function is used to move the axis to the bottom.

Draw y-axis

After drawing the horizontal x-axis, it’s time to draw the vertical axis. As we have discussed above, D3.js provides d3.axisleft() to draw the vertical axis. Let’s use it to draw the vertical axis in the following example.

Drawing y-axis

Explanation

Let’s dive into the explanation of the above code to get a better understanding of it.

  • The explanation for the above code is the same as the previous code. The only code that needs to be explained is in line 15 and line 17.
  • In line 15, the range is defined from [150 ,0] rather than from [0,150]. Because the origin is in the top left corner, the y-axis will be shown in increasing order from top to bottom. By reversing the order in the range() function, the y-axis will be shown in increasing order from bottom to top.
  • In line 17, d3.axisLeft is used to initialize the vertical axis.