简体   繁体   中英

d3js time format

I'm new to d3 so apologies is the question has an obvious answer. I'm trying to create a simple path with inputs as a json file something like that

    var data = [{"date":"2012-10-22","debit":"150.00"},
                {"date":"2012-10-29","debit":"1650.00"}, .....

and then I'm trying make the a scale

    var x = d3.time.scale()
            .domain(d3.extent(data, function(d) { return (d.date); }))
            .range([0, w]);

d3.extend returns the correct values but when I input this into the line and the path I get NaN. Following is my code

    var margin = {top: 20, right: 50, bottom: 30, left: 50},
        w = 600 - margin.left - margin.right,
        h = 400 - margin.top - margin.bottom,
        barPadding = 3,

    var debitMax = d3.max(data, function (d) { return + d.debit;});
    var x = d3.time.scale()
            .domain(d3.extent(data, function(d) { return (d.date); }))
            .range([0, w]);
    var y = d3.scale.linear()
            .domain([0, debitMax])
            .range([h, 0]);

    var valueline = d3.svg.line()
            .x(function(d) { return x((d.date)); })
            .y(function(d) { return y(d.debit); })
            .interpolate("basis");

    var svgContainer = d3.select("div").append("svg")
            .attr("width", w + margin.left + margin.right)
            .attr("height", h + margin.top + margin.bottom)

    var debitPath = svgContainer
            .append("path")
            .attr("d", valueline(data));

and here is what I get on firebug

           Error: Problem parsing d="MNaN,318.181818 ..........

Thanks

The date in your JSON is not actually something that Javascript can deal with in a sensible way -- you need to parse it into date objects. d3 provides various functions for this (see the documentation ). In your case, you'll need something like

var parseDate = d3.time.format("%Y-%m-%d").parse;
...
.domain(d3.extent(data, function(d) { return parseDate(d.date); }))
...
.x(function(d) { return x(parseDate(d.date)); })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM