Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x-axis dates don't align with y-axis data in nvd3

Tags:

d3.js

nvd3.js

I am using NVD3 with Flask and I have dates on the x-axis. enter image description here

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;
                });
like image 735
Lyman Zerga Avatar asked Dec 08 '22 11:12

Lyman Zerga


1 Answers

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
like image 162
rtexal Avatar answered May 16 '23 09:05

rtexal