d3.js解析csv文件的日期错误 [英] d3.js parsing date error with csv file

查看:172
本文介绍了d3.js解析csv文件的日期错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在解析csv文件中的日期时遇到问题。
一直在寻找小时在线,书籍和测试,没有找到解决方案。

I have a problem with parsing dates in a csv file. Have been looking for hours online and in books and testing, without finding the solution.

也许有人可以帮助。

代码在读取文件时只需解析数字即可。但是当解析一个文件与日期我得到以下错误信息,指示日期格式无法识别:

The code works fine for reading a file with parsing just numbers. But when parsing a file with dates I get the following error message indicating the date format is not recognised:

Problem parsing d="MNaN,268.5466377440347LNaN,117.78741865509761LNaN ...

文件如下所示:

 date,value
 11-11-13,582
 12-11-13,860
 13-11-13,940

代码:(js)

Code: (js)

function myFunction() {
      d3.csv('data/Date.csv', draw);
}

function draw(data) {
    "use strict";
    var margin = 50,
        width = 800 - margin,
        height = 350 - margin;

    var parseDate = d3.time.format("%d-%m-%y").parse;

    var x_scale = d3.time.scale()
        .domain(d3.extent(data,function(d){return d.date}))
        .range([margin, width]);

    var y_scale = d3.scale.linear()
       .domain(d3.extent(data,function(d){return d.value}))
       .range([height, margin]);

    var x_axis = d3.svg.axis()
        .scale(x_scale)
        .orient("bottom");

    var y_axis = d3.svg.axis()
        .scale(y_scale)
        .orient("left");

    var line = d3.svg.line()
        .x(function(d){return x_scale(d.date);})
        .y(function(d){return y_scale(d.value);});

    data.forEach(function(d) {
        d.date = parseDate(d.date);
        d.value = +d.value;
    });

    d3.select("body") 
      .append("svg")
        .attr("width", width+margin)
        .attr("height", height+margin)
      .append('g')
        .attr("transform","translate(" + margin + "," + margin + ")");

    d3.select('svg')
      .append('path')
        .datum(data)
        .attr ("class","line")
        .attr('d', line);

    d3.select("svg")
      .append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(x_axis);

    d3.select("svg")
      .append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + margin + ",0)")
      .call(y_axis);
}

<body>
<button onclick="myFunction()">Show Graph</button>
</body>


推荐答案

您应该移动以下代码

data.forEach(function(d) {
    console.log(d.date);
    console.log(format.parse(d.date));
    d.date = format.parse(d.date);
    d.value = +d.value;
});

var format = d3.time.format("%d-%m-%y");

您的原始代码使用解析日期之前的解析日期:)

Your original code used the parsed date before the date is parsed:)

这篇关于d3.js解析csv文件的日期错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆