3

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?

2
  • 1
    Why don't you simply map each property? Commented Feb 15, 2017 at 8:29
  • 2
    can you share some code of what you have tried so far? Keep in mind that you can manipulate the data structure before feeding it to d3, if that makes it easier to handle while drawing the visualisation Commented Feb 15, 2017 at 8:31

1 Answer 1

9

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.