Contents

How to Load External Data in D3.js?

Contents

In this article we will see how to import csv, tsv an json file into a D3 project. The good news is that D3 allows us to do it very easily. If you have a csv file in your directory project you can use this function to load it:

1
2
3
d3.csv("mycsv.csv").then( data=> {
	console.log(data)
})

This snippet of code display the data in the browser’s console.

In the same way, you can do it with a tsv file:

1
2
3
d3.tsv("mytsv.tsv").then(data => {
	console.log(data)
})

And it works with json too:

1
2
3
d3.json("myjson.json").then(data => {
	console.log(data)
})

Now, let’s assume that we have a csv file containing heights for different buildings.

We would like to display one circle for each building. First, we need to load the data.

1
2
3
4
5
6
d3.csv("tour.csv").then( data=> {
	data.forEach(d => {
		d.height = Number(d.height)
	})
	console.log(data);
})

We can see in the console that data are well loaded.

We use the forEach method to convert each height in an integer (before they were characters).

Now we will use the same technique as in this article to draw circles using the data. We first define an svg canvas:

const svg = d3.select("#canvas").append("svg").attr("width", 100).attr("height", 850);

Then we append circles to the svg;

const circles = svg.selectAll("circle").data(data);

Finally we define the radius and the cx position of the circles using the data.

1
2
3
4
5
circles.enter().append("circle")
	.attr("cx", (d, i) => (i*10)+10)
	.attr("cy", 50)
	.attr("r", (d) => d )
	.attr("fill", "green");

The three last snippet should be just below the “console.log(data);”

Now your code should display one circle for each building where the radius is the height of the buildings.

That’s it for today, I hope this post helped you. Do not hesitate to ask me your questions in DM.

See you!