【发布时间】:2014-05-27 13:55:13
【问题描述】:
我正在尝试使用 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 传递的,因此我需要在格式化之前再次解析日期。
【问题讨论】:
-
我想你需要
d3.time.format("%Y-%m-%d")(d.x)。 -
TypeError: d is undefined -
@LarsKotthoff,没有
d传递给刻度格式函数的值将是刻度值本身。问题在链条的上层。
标签: javascript json d3.js charts nvd3.js