D3载入CSV文件,然后仅使用特定列 [英] D3 Loading in CSV file then using only specific columns

查看:37
本文介绍了D3载入CSV文件,然后仅使用特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难从CSV文件中获取两列,而我正计划用它们来构建基本的条形图.我正计划在一个数组中获取2个数组(每列一个),以此来构建条形图.如您所知,刚开始使用D3.

I've had a hard time getting two columns from a CSV file with which I am planning on building a basic bar chart. I was planning on getting 2 arrays (one for each column) within one array that I would use as such to build a bar chart. Just getting started with D3, as you can tell.

当前将数据加载到其中会得到一个对象数组,这很混乱,无法获得两列键-值对.我不确定我的想法是正确的...

Currently loading the data in gets me an array of objects, which is then a mess to get two columns of key-value pairs. I'm not sure my thinking is correct...

我看到了类似的问题:

d3-从csv文件中加载两个特定的列

但是我将如何使用选择和enter()来实现自己的目标?

But how would I use selections and enter() to accomplish my goal?

推荐答案

您不能仅加载较大CSV的2列,但可以加载整个内容并提取所需的列.

You can't load just 2 columns of a bigger CSV, but you can load the whole thing and extract the columns you want.

说您的csv是这样的:

Say your csv is like this:

col1,col2,col3,col4
aaa1,aaa2,aaa3,aaa4
bbb1,bbb2,bbb3,bbb4
ccc1,ccc2,ccc3,ccc4

然后您将其加载

csv('my.csv', function(err, data) {
  console.log(data)
  /*
    output:
    [
      { col1:'aaa1', col2:'aaa2', col3:'aaa3', col4:'aaa4' },
      { col1:'bbb1', col2:'bbb2', col3:'bbb3', col4:'bbb4' },
      { col1:'ccc1', col2:'ccc2', col3:'ccc3', col4:'ccc4' }
    ]
  */
})

如果您只想要 col2 col3 (并且您不想简单地将其他列的数据留在其中,那么无论如何都不应该成为问题),您可以这样做:

If you only want col2 and col3 (and you don't want to simply leave the other columns' data in there, which shouldn't be an issue anyway), you can do this:

var cols2and3 = data.map(function(d) {
  return {
    col2: d.col2,
    col3: d.col3
  }
});

console.log(cols2and3)
/*
  output:
  [
    { col2:'aaa2', col3:'aaa3' },
    { col2:'bbb2', col3:'bbb3' },
    { col2:'ccc2', col3:'ccc3' }
  ]
*/

即上面的代码生成了一个新的对象数组,每个对象只有两个道具.

I.e. the above code produced a new array of objects with only two props per object.

如果您只需要每列一个值的数组,而不是同时具有两列值的对象,则可以:

If you want just an array of values per column — not objects with both columns' values — you can:

var col2data = data.map(function(d) { return d.col2 }
var col3data = data.map(function(d) { return d.col3 }

console.log(col2) // outputs: ['aaa2', 'bbb2', 'ccc2']

这篇关于D3载入CSV文件,然后仅使用特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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