D3 Loading in CSV file then using only specific columns

不打扰是莪最后的温柔 提交于 2021-02-08 03:55:17

问题


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...

I see this similar question:

d3 - load two specific columns from csv file

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


回答1:


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

Say your csv is like this:

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

And you load it with

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' }
    ]
  */
})

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']


来源:https://stackoverflow.com/questions/42243458/d3-loading-in-csv-file-then-using-only-specific-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!