I am using NVD3 with Flask and I have dates on the x-axis.
As you can see the lines on x-axis don't coincide with the points. I printing out the day, month, year and hours on the x-axis. I don't understand why the dates are not equally spaced i.e the 'hours' are not the same even though my x-axis data is, so that the lines are more than "24 hrs" apart. I think this is causing the problem.
(Edited) My code is:
nv.addGraph(function() {
var chart = nv.models.lineChart();
chart.xAxis
.tickFormat(function(d) { return d3.time.format('%d %b %Y')(new Date(parseInt(d))) }
);
chart.yAxis
.tickFormat(d3.format(',.02f'));
chart.tooltipContent(function(key, y, e, graph) {
var x = d3.time.format('%d %b %Y')(new Date(parseInt(graph.point.x)));
var y = String(graph.point.y);
var y = String(graph.point.y);
tooltip_str = '<center><b>'+key+'</b></center>' + y + ' on ' + x;
return tooltip_str;
});
chart.showLegend(true);
d3.select('#lineChart svg')
.datum(data_lineChart)
.transition().duration(500)
.attr('width', 1200)
.attr('height', 450)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
A better suggestion here as d3 does not scale the x-axis represented by dates well if it is not declared a timescale.
chart.xAxis
.tickFormat(function(d) {
return d3.time.format('%d-%m-%y')(new Date(d))
});
chart.xScale(d3.time.scale()); //fixes misalignment of timescale with line graph
Ok, got it! What I do is I create a sorted list of timestamps which are to be used as data on the x-axis and round them to the nearest day. Then I force NVD3 to use this data as intervals instead of the auto-generated intervals by doing:
chart.xAxis
.tickValues({{x_data}})
where x_data is the list. And voila ! ...
You can explicitly control how the ticks are generated. To have ticks 24 hours apart, the code would be something like
chart.xAxis.ticks(d3.time.day, 1);
Edit
It looks like NVD3 doesn't actually use the D3 axis component to generate the labels, hence all of this has no effect. You would have to modify the source of NVD3 to achieve what you want.
来源:https://stackoverflow.com/questions/19690432/x-axis-dates-dont-align-with-y-axis-data-in-nvd3