nvd3 formatting date returns always 1970-01-01

别来无恙 提交于 2019-12-05 20:44:47

You're never telling NVD3 that your x-values are dates. By default, for a line chart NVD3 uses a linear (numerical) x-axis. When it tries to convert each of your x-value date strings to numbers, it gets NaN (not a number). It therefore ends up without having any valid x values from which to create the x axis domain, and uses [-1,1] as the default.

You need to tell the chart function how to get a valid linear value from your data. You do this by setting an x-accessor function on your chart object:

    var chart = nv.models.lineChart()
                  .x( function(d){ return Date(d.x);} );

You can also specifically tell the chart to use a Date scale for the x-axis. It's not required (once you convert your strings to Dates, they can be automatically converted into valid numbers), but it will result in better tick values (based on even multiples in date and time units, instead of even multiples of milliseconds).

    chart.xScale = d3.time.scale();
    chart.xAxis
        .tickFormat(function(d) { return d3.time.format("%Y-%m-%d")(d) });

Note that tick value passed to the tick format from the date-time scale is a date value, so you only have to format it for printing, you don't need any conversion.

Why dont you just pass epoch time to x, using dateObj.getTime()

more info : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/getTime

Here is an example of my code which works :

chart.xAxis     //Chart x-axis settings
      .axisLabel('Date')
      .tickFormat(function(d) { return d3.time.format('%d-%m-%y')(new Date(d)); })
      .rotateLabels(-15); //This is optional but very useful sometimes

This is the kind of x I am passing to the values object :

var tmp = new Date(someDate);
tmp = tmp.getTime();
values : [{x:tmp, y:someData}, {x:tmp1, y:someData1}, etc]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!