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

Ste*_*TNT 3 javascript charts json d3.js 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;
});
Run Code Online (Sandbox Code Playgroud)

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

chart.xAxis
        .tickFormat(function(d) { return d3.time.format("%Y-%m-%d")(new Date(d)) });
Run Code Online (Sandbox Code Playgroud)

范围从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)) });
Run Code Online (Sandbox Code Playgroud)

这是因为在tickFormat函数中,它d是作为intUNIX时间戳传递的,因此我需要在格式化之前再次解析日期.

Ame*_*aBR 5

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

您需要告诉图表函数如何从数据中获取有效的线性值.您可以通过在图表对象上设置x-accessor函数来执行此操作:

    var chart = nv.models.lineChart()
                  .x( function(d){ return Date(d.x);} );
Run Code Online (Sandbox Code Playgroud)

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

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

请注意,从日期时间刻度传递给刻度线格式的刻度值是日期值,因此您只需将其格式化以进行打印,您不需要任何转换.