Labels

Learn how to give labels to the axis.

We'll cover the following

Introduction

In this lesson, we are going to see another fundamental building block of drawing the chart, labels. Labels provide information for the chart and help to understand the information provided by the axis correctly. D3.js doesn’t have any explicit label component, but text is used to add labels to the graph. Curious to see how it works? Let’s jump right into the example.

Example

In the following example, we have been given data first, and we will need to draw an axis from the data then we will add the labels to the respective axis. In our example, the x-axis represents the days and the y-axis represents stock value. Our task is to add the respective labels to the x-axis and y-axis.

Adding labels

Explanation

Let go into a detailed explanation of the above code.

  • The code from line 1 to line 24 draws the axis as already discussed in the Axis lesson.
  • Line 25-27: We are labeling the x-axis using the text() method. We have moved the text to the appropriate position using the translate() function.
  • Adding a label to the y-axis from line 28 to line 30 is the same as the x-axis, except that we have rotated the label by -90 degrees to align it with the y-axis.