score:1

Accepted answer

The problem is that you're trying to use the d3.time.format().parse() to convert days of the week into dates. That's not really possible, because "Monday" could be any date that falls on a "Monday".

So, instead of calling format.parse(d.Day), you need another means of turning a day of the week into a Date.

You can start by establishing a Sunday Date that would serve as the first day of the week and would appear left-most in your graph. It can be any Sunday at any point in the past or future, but let's use yesterday's Sunday. That means:

var aSunday = Number( new Date(2014, 0, 5) ) // Sunday, Jan 5th, 2014

Now, for every day of the week, you need to calculate an offset between that day and the Sunday before it. First, you need an array of all the days of the week, starting with Sunday:

var days=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 
          'Thursday', 'Friday', 'Saturday']

This way, days.indexOf(d.Day) would return the index of that day relative to Sunday. For example, "Tuesday" would have an index of 2, which is 2 days after Sunday. If you multiply that by the number of milliseconds per 24 hour day, you get the amount of milliseconds you need to add to aSunday in order to get a Date object representing that following Tuesday:

var msPerDay = 86400000 // 24 hours in milliseconds
var dateFn = function(d) { return aSunday + msPerDay * days.indexOf(d.Day); };

Here's how it works with you jsFiddle.

That being said, it's probably most appropriate to ditch d3.time.scale() and use d3.scale.ordinal() instead. Check this modified fiddle, which uses ordinal scale and doesn't know anything about Dates or time.

Also, come to think of it, the date-based approach may not play well with daylight savings. I strongly recommend the ordinal scale -based approach.


Related Query

More Query from same tag