I am trying to adapt a simple scatterplot program in D3 to accept a CSV file. When I use the data in the file it works just fine, but when I try to load the CSV file it simp
IMPORTANT:
While the answer here works, there's a builtin method d3.csv.parseRows()
, which achieves the same result. For that, see @ryanmt's answer (also on this page). However, keep in mind that regardless of the method you use, if your CSV has numbers in it then you'll need to convert them from strings to javascript Numbers. You can do it by prefixing the parsed values with a +
. For example, in the solution I provided here — which doesn't use parseRows()
— that conversion is achieved via +d["x-coordinate"]
.
THE ANSWER:
The CSV parser produces an array of objects, rather than the array of arrays that you need. It looks like this:
[
{"x-coordinate":"5"," y-coordinate":"20"},
{"x-coordinate":"480"," y-coordinate":"90"},
{"x-coordinate":"250"," y-coordinate":"50"},
{"x-coordinate":"100"," y-coordinate":"33"},
...
]
To transform it, you need to use a map()
function:
d3.csv("datatest.csv", function(data) {
dataset = data.map(function(d) { return [ +d["x-coordinate"], +d["y-coordinate"] ]; });
});
(Note, map()
is not available in older IE. If that matters, then there are plenty of workarounds with d3, jQuery, etc)
Using d3.csvParseRows (assuming D3 v5)
d3.text('/data/output.csv')
.then( text => d3.csvParseRows(text) )
.then( d => console.log(d) );
D3 provides a builtin for this very thing.
Instead of calling .parse()
on your data, call .parseRows
. This provides just the data as an Array, rather than an Object (based upon the header line).
see the Documentation.