Question

Im trying to set up a line chart nvd3 graphic, but im getting time value on x axis not vertically aligned, heres the code:

function fillData() {

var test1 = [],
    test2 = [],
    test3 = [];

var now =  new Date(),
   day = 1000*60*60*24;

var cont = 0;

for (var i = now - 9*day; i < now; i+=day)
{

    var arr = [400,431,401,430,429,450,448,498,421,421];
    var arr1 = [420,415,421,410,439,430,468,448,441,421];
    var arr2 = [410,425,431,420,459,420,458,438,451,421];

    test1.push({x: i, y: arr[cont]});
    test2.push({x: i, y: arr1[cont]});
    test3.push({x: i, y: arr2[cont]});
    cont+=1;

} // fin for

return [
    {
      values: test1,
      area: true,
      key: 'test1',
      color: '#81BA63'
    },
    {
      values: test2,
      area: true,
      key: 'test2',
      color: '#EAEAEA'
    },
    {
      values: test3,
      area: true,
      key: 'test3',
      color: '#6389BA'
    }
  ];
}

nv.addGraph(function() {
var chart = nv.models.lineChart()

    .margin({top: 0, bottom: 25, left: 45, right: 0})
    .showLegend(true)
    .forceY([300,500])

chart.yAxis
    .showMaxMin(true)
    .tickFormat(d3.format('.02'))

chart.xAxis
    .showMaxMin(false)
    .tickFormat(function(d) { return d3.time.format('%d - %b')(new Date(d)) });
     chart.xScale(d3.time.scale());


d3.select('#sources-chart-line svg')
    .datum(fillData())
    .transition().duration(500)
    .call(chart);

nv.utils.windowResize(chart.update);

return chart;
});

problem screenshot: http://oi57.tinypic.com/i6gq2t.jpg

Thanks in Advance!!

Was it helpful?

Solution

The problem is that the number of data points (9) and axis ticks (8) is different. D3 picks "representative" ticks for the scale, which aren't necessarily aligned with the data points. Therefore, you get ticks between data points for which the date is still correct, but not at exactly midnight like the data points.

One way of fixing this is to explicitly specify the tick values:

var data = fillData();
chart.xAxis
  .tickValues(data[0].values.map(function(d) { return d.x; }));

This is a bit ugly, but it shows the principle and you can refactor the code to make these values better accessible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top