如何在x轴上显示nvd3/d3.js的日期?

Ult*_*rus 50 d3.js nvd3.js

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

如果我省略了针对xAxis的.tickFormat,它可以在没有日期格式的情况下正常工作.通过下面的示例我得到错误:

未捕获的TypeError:对象1326000000000没有方法'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'
        }
    ];
 }
Run Code Online (Sandbox Code Playgroud)

示例(现已修复)位于带日期轴的nvd3中.

sel*_*pou 63

尝试Date在x轴的刻度传递给格式化程序之前创建一个新对象:

.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); })
Run Code Online (Sandbox Code Playgroud)

请参阅d3.time.format的文档以了解如何自定义格式化字符串.

  • 快速评论帮助我:日期对象在Javascript中以毫秒为单位,所以我需要确保我的图表数据(由Python API生成)生成x值,以毫秒为单位(自纪元以来)JS/d3解析和格式化我的x轴值正确. (2认同)

小智 34

添加到seliopou的答案,要正确地将日期与x轴对齐,请尝试以下方法:

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
Run Code Online (Sandbox Code Playgroud)

  • 我也有时间尺度的错位问题.这个解决方案解决了我的问 非常感谢你!!! (4认同)