Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

d3.js

nvd3.js

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.

like image 520
Ultrasaurus Avatar asked Dec 27 '12 17:12

Ultrasaurus


2 Answers

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 to see how you can customize the formatting string.

like image 171
seliopou Avatar answered Oct 24 '22 11:10

seliopou


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
like image 38
rtexal Avatar answered Oct 24 '22 12:10

rtexal