How to show dates on x axis for nvd3 / d3.js?

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

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

Uncaught TypeError: Object 1326000000000 does not have a getMonth method

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' } ]; } 

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

+46
Dec 27
source share
2 answers

Try creating a new Date object before the checkmark for the x axis is passed to the formatter:

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

See the documentation for d3.time.format for how you can customize the format string.

+60
Dec 27 '12 at 20:11
source share

When adding an answer to seliopou to correctly align dates with the x axis, try the following:

 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 
+30
Mar 15 '14 at 2:08
source share



All Articles