I'm trying to build a line chart using nvd3 for d3js but I've got some problems using a date domain on the x axis.
Here's my code:
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;
});
What I get is a x axis in which every date is 1970-01-01 and this because the d
in
chart.xAxis
.tickFormat(function(d) { return d3.time.format("%Y-%m-%d")(new Date(d)) });
ranges from 1 to -1 instead of the expected x value.
What's wrong with it?
EDIT: Starting from @AmeliaBR's solution I've managed to make this work using this code:
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)) });
This because, in the tickFormat
function, d
was passed as an int
with the UNIX timestamp, and so I needed to parse the date again before formatting it.