Skip to content Skip to sidebar Skip to footer

Dealing With Dates On D3.js Axis

How do I make my line x-axis based on date in d3.js? I am attempting to teach myself how to use d3.js. I've been looking at the examples that come with it and have been attempting

Solution 1:

You're trying to use d3.scale.linear() for dates, and that won't work. You need to use d3.time.scale() instead (docs):

// helper functionfunctiongetDate(d) {
    returnnewDate(d.jsonDate);
}

// get max and min dates - this assumes data is sortedvar minDate = getDate(data[0]),
    maxDate = getDate(data[data.length-1]);

var x = d3.time.scale().domain([minDate, maxDate]).range([0, w]);

Then you don't need to deal with the time interval functions, you can just pass x a date:

.attr("d", d3.svg.line()
    .x(function(d) { returnx(getDate(d)) })
    .y(function(d) { returny(d.jsonHitCount) })
);

Working fiddle here: http://jsfiddle.net/nrabinowitz/JTrnC/

Post a Comment for "Dealing With Dates On D3.js Axis"