问题
So, just recently I have been using D3.js to parse data from a CSV file. While reading the "Interactive Data Visualization" by Scott Murray (great book and very informative) it explains how to select all data from a table in a CSV.
The code to parse the CSV is shown below:
d3.text("three.csv", function(data) {
var parsedCSV = d3.csv.parseRows(data);
var container = d3.select("#thirdCSV")
.append("div")
.append("table")
.attr("id", "tableThree")
.selectAll("tr")
.data(parsedCSV).enter()
.append("tr")
.selectAll("td")
.data(function(d) { return d; }).enter()
.append("td")
.attr("id","three")
.text(function(d) { return d; });
});
For my project, I am taking 7 different CSV files and placing it on a HTML format.
Writing the code above 7x seems unnecessary, is there another way to parse multiple CSV file? If so, is there also a way to parse only specific columns such as columns D-F? Here is an image of how one of the files is set up (the rest of the CSV files are the same format.
回答1:
There is a specific function for reading in csv files in D3 d3.csv(). You should use it instead of d3.text() because it makes things much easier since you do not need to use d3.csv.parseRows() in addition. Look this block for example.
You can use d3.queue() function for asynchronous loading of several data files. It waits for all the files to be loaded before the next steps are taken. You should use it like this:
var q = d3.queue()
.defer(d3.csv, "first.csv")
.defer(d3.csv, "second.csv")
.defer(d3.csv, "third.csv")
....
.awaitAll(function(error, results) {
if (error) throw error;
console.log(results);
draw(results)
});
I also want to point out that the D3.queue() function is not included in D3 v3 default bundle, so you have to load it separately:
<script src="https://d3js.org/d3-queue.v3.min.js"></script>
来源:https://stackoverflow.com/questions/39009291/parsing-specific-columns-data-from-multiple-csv-file