Formatting a Date and Time Axis with Specified Values

Learn to change the date/time formats of your graph axes.

We’ve been very clever in rotating our text, but you will notice that D3 has used its own good judgment as to what format the days/date will be represented as.

Not that there’s anything wrong with it, but what if we want to put a specific format of date/time nomenclature as axis labels? No problem; D3 to the rescue again!

This is actually a pretty easy thing to do, but there are plenty of options for the formatting, so the only really tricky part is deciding what to put where.

But before we start doing anything, we are going to have to expand our bottom margin even more than we did with the “rotate the axis” labels feature.

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

That should see us right.

Changing the format

Now for the simple part; changing the format of the label is as simple as inserting the tickFormat command into the x-axis declaration and including a D3 time formatting function a little like this:

Get hands-on with 1400+ tech skills courses.