如何显示nvd3 / d3.js在X轴上的date?

我正在使用nvd3,但我认为这是一个关于时间尺度和格式的普通d3.js问题。 我创build了一个简单的例子来说明这个问题(见下面的代码):

如果我为xAxis省略.tickFormat,那么在没有date格式的情况下工作正常。 用下面的例子,我得到的错误:

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

这个例子(现在是固定的)是在date轴的nvd3中

尝试创build一个新的Date对象,然后将x轴的勾号传递给格式器:

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

请参阅d3.time.format文档以了解如何自定义格式化string。

加上seliopou的答案,为了使date与x轴正确alignment,试试这个:

 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