How do I display dates on the x-axis for nvd3 / d3.js?

d3.jsnvd3.js

d3.js Problem Overview


I'm using nvd3, but I think this is a general d3.js question about time scale and formatting. I've created a simple example that illustrates the problem (see code below):

If I omit .tickFormat for the xAxis, it works fine without date formatting. With the example below I get the error:

> Uncaught TypeError: Object 1326000000000 has no method 'getMonth'

nv.addGraph(function() {

    var chart = nv.models.lineChart();

    chart.xAxis
         .axisLabel('Date')
         .rotateLabels(-45)
         .tickFormat(d3.time.format('%b %d')) ;

     chart.yAxis
         .axisLabel('Activity')
         .tickFormat(d3.format('d'));

     d3.select('#chart svg')
         .datum(fakeActivityByDate())
       .transition().duration(500)
         .call(chart);

     nv.utils.windowResize(function() { d3.select('#chart svg').call(chart) });

     return chart;
});

function days(num) {
    return num*60*60*1000*24
}

/**************************************
 * Simple test data generator
 */

function fakeActivityByDate() {
    var lineData = [];
    var y = 0;
    var start_date = new Date() - days(365); // One year ago

    for (var i = 0; i < 100; i++) {
        lineData.push({x: new Date(start_date + days(i)), y: y});
        y = y + Math.floor((Math.random()*10) - 3);
    }

    return [        {            values: lineData,            key: 'Activity',            color: '#ff7f0e'        }    ];
 }

The example (now fixed) is in nvd3 with date axis.

d3.js Solutions


Solution 1 - d3.js

Try creating a new Date object before the tick for the x-axis gets passed to the formatter:

.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); })

See the documentation for [d3.time.format][1] to see how you can customize the formatting string.

[1]: https://github.com/mbostock/d3/wiki/Time-Formatting "D3 time formatting docs"

Solution 2 - d3.js

Adding on to seliopou's answer, to correctly align the dates with the x-axis, try this:

chart.xAxis
      .tickFormat(function(d) {
          return d3.time.format('%d-%m-%y')(new Date(d))
      });

  chart.xScale(d3.time.scale()); //fixes misalignment of timescale with line graph

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUltrasaurusView Question on Stackoverflow
Solution 1 - d3.jsseliopouView Answer on Stackoverflow
Solution 2 - d3.jsrtexalView Answer on Stackoverflow