51

私はnvd3を使用していますが、これはタイムスケールとフォーマットに関する一般的なd3.jsの質問だと思います。問題を説明する簡単な例を作成しました(以下のコードを参照)。

xAxisの.tickFormatを省略すると、日付のフォーマットがなくても正常に機能します。以下の例では、エラーが発生します。

Uncaught TypeError:オブジェクト1326000000000にはメソッド'getMonth'がありません

nv.addGraph(function() {

    var chart = nv.models.lineChart();

    chart.xAxis
         .axisLabel('Date')
         .rotateLabels(-45)
         .tickFormat(d3.time.format('%b %d')) ;

     chart.yAxis
         .axisLabel('Activity')
         .tickFormat(d3.format('d'));

     d3.select('#chart svg')
         .datum(fakeActivityByDate())
       .transition().duration(500)
         .call(chart);

     nv.utils.windowResize(function() { d3.select('#chart svg').call(chart) });

     return chart;
});

function days(num) {
    return num*60*60*1000*24
}

/**************************************
 * Simple test data generator
 */

function fakeActivityByDate() {
    var lineData = [];
    var y = 0;
    var start_date = new Date() - days(365); // One year ago

    for (var i = 0; i < 100; i++) {
        lineData.push({x: new Date(start_date + days(i)), y: y});
        y = y + Math.floor((Math.random()*10) - 3);
    }

    return [
        {
            values: lineData,
            key: 'Activity',
            color: '#ff7f0e'
        }
    ];
 }

例(現在は修正済み)は、日付軸を持つnvd3にあります

4

2 に答える 2

63

Try creating a new Date object before the tick for the x-axis gets passed to the formatter:

.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); })

See the documentation for d3.time.format to see how you can customize the formatting string.

于 2012-12-27T20:11:26.497 に答える
34

Adding on to seliopou's answer, to correctly align the dates with the x-axis, try this:

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
于 2014-03-15T02:08:49.033 に答える