我正在尝试使用 nvd3 为 d3js 构建折线图,但在 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/