Nov Nov - 5 months ago 22
Javascript Question

d3 retrieval of a csv file returns Nan in the javascript console

I'm just learning how to use d3. I'm having an issue when trying to retrieve a .cvs/excel file. At line 13 I get a console reading of "4 Nan", or "4 undefined, undefined". I might have the location of books.csv in the wrong location. It is located "xampp\htdocs\books.csv" along with my html file and d3.js.. The row and columns are 5 * 2. Any questions or help is much appreciated!

<!DOCTYPE html>
<html>
<head>
<meta charset"utf-8">
<title> D3 example</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>

<script>
d3.csv("books.csv", function(myArrayOfObjects){
myArrayOfObjects.forEach(function(d){
console.log( d.x + ", " + d.y);
});
});
</script>
</body>
<body>
Is it Working?
</body>
</html>

books.csv file contains:
4, 2
5, 10
3, 2
1, 7
0, 11

Answer

The problem is just the structure of your CSV:

The first line of your CSV is the header. d3.csv uses that line to create the objects. So, in a given CSV:

foo, bar
42, 12

d3.csv will create this data:

[{"foo": 42, "bar": 12}]

Right now, your CSV has numbers as headers, and this will simply not work. Javascript allows you to name an object key as numbers (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types), but in this case you have to reference it using a bracket notation:

console.log( d["4"] + ", " + d["2"]);

Once 4 and 2 are the headers.

That being said, here is an alternative CSV:

x,y
4, 2
5, 10
3, 2
1, 7
0, 11

Now, x and y are the headers.

I created a plunker to show you the difference: https://plnkr.co/edit/OipJg11P3aEvwgQ35xbh?p=preview

Your CSV is "wrongData.csv", and mine is "rightData.csv". Check the console.