Jared
Jared

Reputation: 3892

Creating X-Axis with Array of Date() Objects - D3.js

I have an array of dates in javascript:

dates = [Fri Jan 02 2015 00:00:00 GMT-0600 (CST), 
Mon Jan 05 2015 00:00:00 GMT-0600 (CST), 
Tue Jan 06 2015 00:00:00 GMT-0600 (CST), 
Wed Jan 07 2015 00:00:00 GMT-0600 (CST), 
Thu Jan 08 2015 00:00:00 GMT-0600 (CST), 
Fri Jan 09 2015 00:00:00 GMT-0600 (CST), …]

With many more dates present. I can parse them however needed - in D3.js or keeping them in this Date() format. I want my timescale x axis to only have ticks for these dates (noticing that they skip weekends and holidays). Is this possible in D3? I currently tried

 timeScale = d3.time.scale()
  .domain(dates)
  .range([0, width])
  .clamp(true);

but this doesn't work. Using .domain([minDate, maxDate]) works, but includes weekends and holidays.

Upvotes: 1

Views: 405

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

The short answer seems to be "no", it's not possible, because d3.time.scale() was not designed having this in mind.

According to Bostock (creator of d3):

A d3.time.scale should be used when you want to display time as a continuous, quantitative variable, such as when you want to take into account the fact that days can range from 23-25 hours due to daylight savings changes, and years can vary from 365-366 days due to leap years. If you don’t want to plot continuous time, and all of the irregularities in our normal calendar units, then you probably don’t want to use d3.time.scale, and want a d3.scale.linear instead.

Thus, in your case, a better approach would be creating a linear scale, and mapping your days like this:

Fri Jan 02 --> 1
Mon Jan 05 --> 2
Tue Jan 06 --> 3
Wed Jan 07 --> 4
Etc...

Also, you may want to have a look at this implementation from Bostock, that converts between weekdays numbers and dates (I never tried it):

https://gist.github.com/mbostock/5827353

Upvotes: 1

Related Questions