Importing data from multiple csv files in D3
Solution 1:
In d3 version 5, you can use Promise.all
to load multiple csv files. Example:
Promise.all([
d3.csv("file1.csv"),
d3.csv("file2.csv"),
]).then(function(files) {
// files[0] will contain file1.csv
// files[1] will contain file2.csv
}).catch(function(err) {
// handle error here
})
More info about loading csv in d3 v5
More info about Promise.all()
Solution 2:
You simply call d3.csv
several times:
d3.csv("csv1.csv", function(error1, data1) {
d3.csv("csv2.csv", function(error2, data2) {
// do something with the data
});
});
As for your third question, no, D3 will parse everything. There's nothing forcing you to use all the data though, so if you're interested in only one column, just use the data from that.
Solution 3:
You could use a d3 queue to load the files simultaneously. An example;
d3.queue()
.defer(d3.csv, "file1.csv")
.defer(d3.csv, "file2.csv")
.await(function(error, file1, file2) {
if (error) {
console.error('Oh dear, something went wrong: ' + error);
}
else {
doStuff(file1, file2);
}
});
Solution 4:
To answer your part 3,
- Is there a way to choose a certain column from the
csv
files to import?
No, you cannot load in part of a CSV
. You can, however, load in the entire CSV
file and selectively use one column from it. You can refer to data.newVer
to utilize the newVer
column data.