Solari
Solari

Reputation: 53

D3.js not recognizing floats from CSV

I'm trying to produce a two line graph with D3.js.

However, when trying to draw the svg line, my console complains the following:

Error: <path> attribute d: Expected number, "M0,NaNL120.01533182…".

This seems to be the second svg line, where all the y-coordinates are NaN. Why is this so?

I figured, that I might be converting my csv wrong, but console.log -says that my y-coordinates are indeed numbers.

// Get the data
d3.csv("debt.csv", function(error, data) {
  data.forEach(function(d) {
    d.year = parseDate(d.year);
    d.debt = +d.debt;
    d.debtgdp = parseFloat(d.debtgdp); // Trying to parse to a float
    console.log(typeof d.debtgdp); // Recognizes that it is a number
});

CSV looks like this:

year,debt,debtgdp 
1940,29,39.7
1950,228,24.8
1960,271,10.11
1970,707,9.2
1980,3022,9.0
1990,9593,10.5
1995,60121,61.0
2000,63435,46.6
2001,61760,42.8
2002,59253,40.0

All of the code can be found here: http://niklasstrengell.fi/temp/juha/

Thanks in advance for the help!

Upvotes: 1

Views: 439

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

The problem here is very difficult to find out if you just look at the code: a space just after debtgdp and before the newline, at the first row of your CSV file.

The hint was this: with or without both parseFloat() and the unary operator, d.debtgdp is always undefined.

The solution was simply removing that space. Check for spaces and non printable characters in your CSV from now on.

Here is your working code: http://bl.ocks.org/anonymous/a4763e5cc824039cff369f6679d4722b

Upvotes: 3

Related Questions