dealing with dates on d3.js axis

后端 未结 1 858
轮回少年
轮回少年 2021-01-30 03:38

How do I make my line x-axis based on date in d3.js?

I am attempting to teach myself how to use d3.js. I\'ve been looking at the examples that come with it and have bee

1条回答
  •  借酒劲吻你
    2021-01-30 03:44

    You're trying to use d3.scale.linear() for dates, and that won't work. You need to use d3.time.scale() instead (docs):

    // helper function
    function getDate(d) {
        return new Date(d.jsonDate);
    }
    
    // get max and min dates - this assumes data is sorted
    var minDate = getDate(data[0]),
        maxDate = getDate(data[data.length-1]);
    
    var x = d3.time.scale().domain([minDate, maxDate]).range([0, w]);
    

    Then you don't need to deal with the time interval functions, you can just pass x a date:

    .attr("d", d3.svg.line()
        .x(function(d) { return x(getDate(d)) })
        .y(function(d) { return y(d.jsonHitCount) })
    );
    

    Working fiddle here: http://jsfiddle.net/nrabinowitz/JTrnC/

    0 讨论(0)
提交回复
热议问题