javascript - nvd3 格式化日期始终返回 1970-01-01

标签 javascript json d3.js charts nvd3.js

我正在尝试使用 nvd3d3js 构建折线图,但在 x 轴上使用日期域时遇到了一些问题。

这是我的代码:

data_lineChart = [
{
    "key" : "key1",
    "values" : [
        { "x" : "2014-04-20",
          "y" : -6
        },
        { "x" : "2014-04-13",
          "y" : -5
        },
        { "x" : "2014-04-06",
          "y" : -1
        },
      ]
},
{
    "key" : "key2",
    "values" : [
        { "x" : "2014-04-20",
          "y" : 6
        },
        { "x" : "2014-04-13",
          "y" : 5
        },
        { "x" : "2014-04-06",
          "y" : 1
        },
      ]
}
]

nv.addGraph(function() {
        var chart = nv.models.lineChart();
        chart.xAxis
            .tickFormat(function(d) { return d3.time.format("%Y-%m-%d")(new Date(d)) });
        chart.yAxis
            .tickFormat(d3.format(',.2f'));
        chart.tooltipContent(function(key, y, e, graph) {
            var x = d3.time.format("%Y-%m-%d")(new Date(parseInt(graph.point.x)));
            var y = String(graph.point.y);
            var y = 'There is ' +  String(graph.point.y)  + ' calls';
            tooltip_str = '<center><b>'+key+'</b></center>' + y + ' on ' + x;
            return tooltip_str;
        });
        d3.select('#chart1 svg')
            .datum(data_lineChart)
            .transition()
            .duration(500)
            .call(chart);
    return chart;
});

我得到的是一个 x 轴,其中每个日期都是 1970-01-01,这是因为

中的 d
chart.xAxis
        .tickFormat(function(d) { return d3.time.format("%Y-%m-%d")(new Date(d)) });

范围从 1 到 -1 而不是预期的 x 值。

这是怎么回事?

编辑: 从@AmeliaBR 的解决方案开始,我设法使用以下代码完成了这项工作:

var chart = nv.models.lineChart().x( function(d){ return new Date(d.x);} );
chart.xScale = d3.time.scale();
chart.xAxis.tickFormat(function(d) { return d3.time.format("%d-%m-%Y")(new Date(d)) });

这是因为,在 tickFormat 函数中,d 作为带有 UNIX 时间戳的 int 传递,所以我需要解析在格式化之前再次确定日期。

最佳答案

您永远不会告诉 NVD3 您的 x 值是日期。默认情况下,对于折线图,NVD3 使用线性(数字)x 轴。当它尝试将每个 x 值日期字符串转换为数字时,它会得到 NaN(不是数字)。因此,它最终没有任何有效的 x 值来创建 x 轴域,并使用 [-1,1] 作为默认值。

您需要告诉图表函数如何从数据中获取有效的线性值。您可以通过在图表对象上设置一个 x-accessor 函数来做到这一点:

    var chart = nv.models.lineChart()
                  .x( function(d){ return Date(d.x);} );

您还可以专门告诉图表使用 Date scale对于 x 轴。这不是必需的(一旦您将字符串转换为日期,它们可以自动转换为有效数字),但它会产生更好的刻度值(基于日期和时间单位的偶数倍,而不是毫秒的偶数倍)。

    chart.xScale = d3.time.scale();
    chart.xAxis
        .tickFormat(function(d) { return d3.time.format("%Y-%m-%d")(d) });

请注意,从日期时间刻度传递给刻度格式的刻度值是一个日期值,因此您只需将其格式化为打印,不需要任何转换。

关于javascript - nvd3 格式化日期始终返回 1970-01-01,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23891420/

相关文章:

Javascript On 模糊事件

javascript - 无法加载 geojson 文件

ruby-on-rails - rails : How to inspect a response created with 'render json:' ?

javascript - 使用 Javascript 输出 Json 数组

d3.js - 如何在D3中更新堆栈条形图中的数据

javascript - 如何检测是否为 div 启用了显示更多?

c# - 如何在 Visual Studio 2008 或 Visual Studio 2010 中设置 JavaScript 断点

java - 在java中获取JSON值

D3.js:显示有限数量的滴答声

javascript - D3 如何替换 SVG 元素