【问题标题】:How do I display dates on the x-axis for nvd3 / d3.js?如何在 nvd3 / d3.js 的 x 轴上显示日期?
【发布时间】:2012-12-13 02:11:15
【问题描述】:

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

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

未捕获的类型错误:对象 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'
        }
    ];
 }

示例(现已修复)在 nvd3 with date axis 中。

【问题讨论】:

  • 在提出此类问题时,您应该为您的示例创建一个jsFiddle。它使回答问题的人更容易看到您的代码示例正在运行并且易于编辑。
  • 这是个好主意。我尝试制作一个,但 css 看起来没有应用:jsfiddle.net/ultrasaurus/x7epG/3 -- 有人知道我做错了什么吗?
  • 看起来小提琴不再工作了。它现在引用的库是 404。

标签: d3.js nvd3.js


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!这行得通,在这里更新了示例:ultrasaurus.github.com/nvd3-simpleline/date_axis.html -- 但你能解释一下为什么它有效吗?为什么刻度线每隔一周? (对我来说很好,但想理解)
  • @Ultrasaurus 很高兴我能帮上忙。如果我已经回答了您的问题,您应该接受我的回答,将问题标记为已回答,以供其他人查看。
  • 帮助我的快速评论:日期对象在 Javascript 中以毫秒为单位,因此我需要确保我的图表数据(由 Python API 生成)以毫秒为单位生成 x 值(自纪元以来) JS/d3 来正确解析和格式化我的 x 轴值。
  • 如果您遇到刻度线或图表网格未与整个日期值对齐的问题,请在此处查看解决方法:groups.google.com/d/msg/d3-js/OGsyiNDfywo/EpmvLg5ydY4J
  • 我只想使用整数,所以我想分享我相对简单的补充:chart.tickFormat(function(d) { if (d % 1 == 0) { return(d) ; } })
【解决方案2】:

添加到 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

【讨论】:

  • 我不得不按照this answer使用d3.time.scale.utc()
  • 我也遇到了时间刻度错位问题。这个解决方案解决了我的问题。非常感谢!!!
猜你喜欢
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-03
相关资源
最近更新 更多