如何在 nvd3/d3.js 的 x 轴上显示日期? [英] How do I display dates on the x-axis for nvd3 / d3.js?

查看:28
本文介绍了如何在 nvd3/d3.js 的 x 轴上显示日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 nvd3,但我认为这是关于时间刻度和格式的一般 d3.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):

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

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

未捕获的类型错误:对象 1326000000000 没有方法 'getMonth'

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

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

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

推荐答案

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

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)); })

请参阅有关 d3.time.format<的文档/a> 以了解如何自定义格式字符串.

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

这篇关于如何在 nvd3/d3.js 的 x 轴上显示日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆