Time scales
Rounding out our look at continuous scales, today we're going to learn about time scales.
If you've used JavaScript for more than about 10 minutes, you know working with dates and times can be… challenging, to put it mildly. D3 as a whole includes some really nice time utilities and formatters, but when it comes to plotting data based on a temporal attribute, time scales are the important piece.
The syntax for a time scale will of course look familiar.
const timeScale = d3 ;Here we create a time scale whose input domain goes from January 1, 2017 (remember months are 0-based, days are not 😡) to January 1, 2018. The output range will just be 0 to 100 to keep things simple.
This gives us a scale function that will accept a date in 2017 and tell us the numeric value representing that date.
// April 1 === 24.646 // July 1 === 49.577 // October 1 === 74.783Since our scale is continuous and our range is numeric, we can also use the invert method, which tends to come in handy more often with time scales than it does with other types. Given our scale above, we can find the exact time that marks the middle of 2017.
timeScale// Sun Jul 02 2017 13:00:00 GMT-0400 (EDT)Cleaning up real data
All continuous scales have a nice() method that will attempt to round your domain bounds so that they are nice round values. A lot of the time that is unnecessary since you just want to plot whatever is in the data. With a time scale, however, you probably want to start and end your scale at the beginning and end of some recognizable unit, like a year, month, day, etc.
For example, imagine you're plotting sales on a timeline. The first sale of the year probably didn't come in right as the clock ticked midnight, but you do want the edge of your axis and scale to be right there with the Times Square ball drop.
Let's say you've pulled your data and used d3.extent to find the first and last sales in the database.
const first last = d3;// first === "Mon Jan 02 2017 06:41:36 GMT-0500 (EST)"// last === "Wed Sep 27 2017 01:17:05 GMT-0400 (EDT)"By using the nice method we can coerce these values to something nice and round. This will allow for much nicer axes, with better spaced and labeled tick marks, and just a generally more pleasing chart.
const scaleTime = d3 ; scaleTime0// "Sun Jan 01 2017 00:00:00 GMT-0500 (EST)"scaleTime1// "Sun Oct 01 2017 00:00:00 GMT-0400 (EDT)"So you can see that just by calling nice() after constructing our scale, D3 has set our bounds to January 1 and October 1.
This topic is deep and wide
We'll stop here for now, but I'm sure we'll cover plenty of related topics in the future. If you get bored in the meantime the d3-time module is a treasure trove of useful utility functions.
Happy hacking!