Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

nvd3.js - How do I display dates on the x-axis for nvd3 / d3.js?

I'm using nvd3, but I think this is a general d3.js question about time scale and formatting. I've created a simple example that illustrates the problem (see code below):

If I omit .tickFormat for the xAxis, it works fine without date formatting. With the example below I get the error:

Uncaught TypeError: Object 1326000000000 has no method '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'
        }
    ];
 }

The example (now fixed) is in nvd3 with date axis.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...