Skip to content

Instantly share code, notes, and snippets.

@wklchris
Last active May 25, 2021 18:02
Show Gist options
  • Save wklchris/3dd9d8952f52dbcfbd72de763da2097c to your computer and use it in GitHub Desktop.
Save wklchris/3dd9d8952f52dbcfbd72de763da2097c to your computer and use it in GitHub Desktop.
D3 v4 load multiple files using d3.queue
license: gpl-3.0

A quick guide to show how to multi-load files by D3.js v4.

d3.queue()
.defer(d3.csv, "file1.csv")
.defer(d3.csv, "file2.csv")
.await(function(error, data1, data2) {
  if (error) throw error;
  ...
});

Really straightforward.

name number
peaches 2
apples 4
<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
d3.queue()
.defer(d3.csv, "people.csv")
.defer(d3.csv, "fruits.csv")
.await(function(error, people, fruits) {
if (error) throw error;
var div = d3.select("body").append("div")
.attr("width", 200)
.attr("height", 400);
var p = div.selectAll("p")
.data(people).enter()
.append("p")
.text(function(d, i) {
return d.name + " has " + fruits[i].number + " " + fruits[i].name;
});
});
</script>
name gender age
Chris male 3
Monica female 3
@zhuokaizhao
Copy link

Hi what if you had hundreds of csv files to load? If there a way to add a loop inside the defer call? Thanks.

@wklchris
Copy link
Author

Hi what if you had hundreds of csv files to load? If there a way to add a loop inside the defer call? Thanks.

Sorry, I have no idea about the answer to your question. I haven't done this kind of loop CSV loading before, and I haven't used D3 for so long a time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment