使用d3.js v.4加载csv文件

时间:2018-07-12 17:49:52

标签: javascript d3.js

我是d3和javascript的新手,无法解决以下问题。

我正在尝试使用d3.csv加载csv文件,但是遇到了问题。

d3.csv("data2.csv")
    .row(function (d){
        return {
            ax: Number(d.ax.trim().slice(1)),
            ay: Number(d.ay.trim().slice(1))
        };
    })
    .get(function (error, data){
        console.log(data)
    });

我的csv文件是

ax,ay,az 
1,40,50 
2,41,49 
3,39,52 
4,35,49 
5,34,46 
6,33,45 
7,32,42 
8,30,40 
9,29,32 
10,27,26

console.log在给我以下内容:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, columns: Array(3)]
0    :    {ax: 0, ay: 0}
1    :    {ax: 0, ay: 1}
2    :    {ax: 0, ay: 9}
3    :    {ax: 0, ay: 5}
4    :    {ax: 0, ay: 4}
5    :    {ax: 0, ay: 3}
6    :    {ax: 0, ay: 2}
7    :    {ax: 0, ay: 0}
8    :    {ax: 0, ay: 9}
9    :    {ax: 0, ay: 7} 

ax的结果为0,这是不正确的,而ay的结果显然也是不正确的。 我如何才能正确地将数字存储在数组中,以便可以继续使用d3.js版本4绘制数据?

2 个答案:

答案 0 :(得分:0)

尝试

d3.csv("/data/employees.csv")
  .row(function(d) {
        return {
            age: d.age,
            name: d.name.toUpperCase() // converting name to upper case 
        }; 
   })
  .get(function(data) {
      console.log(data);
  }); 

enter link description here

答案 1 :(得分:0)

d3.csv('https://gist.githubusercontent.com/xrd/9a73ccf7ac1e41b728202f3c70cdb959/raw/9c3a1bde4dee9f0d5f80e705bb4f25353ea6b398/test.csv')
            .row(function (d){
                console.log( d );
                return {
                    ax: Number(d.ax),
                    ay: Number(d.ay)
                };
            })
            .get(function (error, data){
                console.log(data)
            });

您可以在这里看到它:http://jsfiddle.net/g3xfbL9m/9/,并且,如果您打开控制台,则可以看到它以正确的值输出到控制台。