Adding the X-Axis Label

Learn to add a label to the x-axis.

What’s the first thing you get told at school when drawing a graph?

Always label your axes!

So, time to add a couple of labels!

Preparation

Because we’re going to be adding labels to the bottom and left of the graph, we need to increase the bottom and left margins. Changes like the following should suffice:

var margin = {top: 20, right: 20, bottom: 50, left: 70},

First things first (because they’re done slightly differently), we will start with the x-axis. If we begin by describing what we want to achieve, it may make the process of implementing a solution a little more logical.

What we want to do is add a simple piece of text under the x-axis and in the center of the total span. Wow, that does sound easy.

And it is, but there are different ways of accomplishing it, and I think I should take an opportunity to demonstrate them. Especially since one of those ways is a BAD idea.

Let’s start with a bad idea first.

Adding a label the bad way

This is the code we’re going to add to the simple line graph script:

Get hands-on with 1400+ tech skills courses.