...

/

Time Scales & Parsing

Time Scales & Parsing

D3 provides a set of functions for passing and scaling time. Time is considered continuous.

We'll cover the following...

In the script section, most of the code has been prepared. At the bottom, we are creating a scale for the y-axis, but not for the x-axis. It is because the x-axis will measure the date. We have not had the opportunity to discuss how to scale time. D3 introduces two scales for scaling time. We will be looking at both scales in this lesson.

Both scales are based on the linear scale. They can transform continuous data into continuous data. In general, time is considered continuous. Therefore we will need a scale that can work with continuous data. What makes the scales special is that they can work with dates instead of regular numbers.

The scaleTime() function

We are going to create the scale for the x-axis. We will be working in the script section. At the bottom of the draw() function, where we created the yScale function, define a variable called xScale. Its value will be the d3.scaleTime() function.

Press + to interact
// Scales
const yScale = d3.scaleLinear()
.domain(d3.extent(dataset, yAccessor))
.range([dimensions.ctrHeight, 0])
.nice()
const xScale = d3.scaleTime()
.domain(d3.extent(dataset, xAccessor))
.range([0, dimensions.ctrWidth])

The scaleTime() function will generate a scale that can transform dates into numbers. The domain must be the range of ...