Search⌘ K
AI Features

Time Scales & Parsing

Explore how to implement time scales in D3.js for the x-axis and convert date strings into Date objects for accurate scaling. Understand the difference between local time and UTC scales and apply parsing techniques using d3.timeParse to prepare data for time-based visualizations.

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.

C++
// 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. ...