In the previous chapters, we learnt about scales. In this chapter, we will learn to create axes using scales in D3. The axes renders human-readable reference marks for scales. Graphs have two axes: the horizontal axis or the x-axis and the vertical axis or the y-axis. D3 provides functions to draw axes. An axis is made of lines, ticks and labels. An axis uses scale, so each axis will need to be given a scale to work with. D3 provides the following functions to draw axes.
So far in our visualizations we haven't added any axes. Let's learn how to add x axis to a graph.
The above example will display the following result. X Axes in D3Let's walk through the above code:
Next, we create our SVG element and set its width and height.
We create a linear scale and specify our domain and range. Observe how we have used d3.min and d3.max functions to get the minimum and maximum values from our dataset. Min would be 10 and max would be 30.
We use d3.axisBottom to create our x-axis and provide it with the scale we defined earlier.
And finally, we append a group element and insert x-axis. Similarly, we can create a vertical axis using
This will draw y-axis in the browser as shown below. Y-Axis in D3Let's understand the above example code.
We created a linear scale and specified our domain and range using the data. We used d3.min and d3.max functions to get the minimum and maximum values from our dataset.
We use d3.axisLeft to create our y-axis and provide it with the scale we defined above.
Finally, we append a group element and call the y-axis function. So, all the components of the y-axis will be grouped under the group element. We then apply a translate transformation to align the y-axis to 50px right of the origin and 10px to the bottom of the origin. This ensures a better visual representation on the screen. The d3.axisBottom() and d3.axisLeft() functions have been introduced in the latest version of D3 i.e. version 4. Earlier versions used d3.svg.axis() with orient("left") and orient("bottom") for y-axis and x-axis respectively. Let's get both the axes together now!
And the grand output: X & Y AxesGreat. That looks neat. Doesn't it? Further Reading: Axis in D3 Now that we have learned about scales and axes, let's create a bar chart with scales and axes in the next chapter. |