Contents

How to Manage Time Scales in D3.js?

Contents
In this article, I will show you the syntax in order to use time scales in D3. Time scales are very easy to understand if you already used linear scales. You can have a look at my post on linear scales here: https://www.datackling.com/post/how-to-manage-linear-scales-in-d3-js .

Time scales allow you to display scale from a departure date to a final data. They are very useful when you have time series.

Let’s first define a time scale with the scaleTime() method:

const timescale = d3.scaleTime()

Then we precise the input domain with the first and the last date in our data:

timescale.domain([ new Date(2019, 0, 1), new Date(2020, 0, 1)])

Now, let’s add the output range regarding of the size of the SVG canvas (suppose 500 here):

timescale.range([0, 500])

Let’s use the chaining method to write it in a way more concise:

1
2
3
4
5
const timescale = d3.scaleTime()
	.domain([ 
		new Date(2019, 0, 1), 
		new Date(2020, 0, 1)]
	.range([0, 500])

Perfect! The time scale is created. So now when we pass a new Date to “timescale” we will get a continious value between 0 and 500 that we can use in a chart.

That’s it for this article. I hope you enjoyed it and do not hesitate to ask your questions in DM.

See you!