d3.js Using D3 with JSON and CSV Loading data from CSV files


There are several ways of getting the data that you will bind to the DOM elements. The simpler one is having your data in your script as an array...

var data = [ ... ];

But D3.js allows us to load data from an external file. In this example, we will see how to properly load and deal with data from an CSV file.

CSV files are comma-separated values. In this kind of file, each line is a data record, each record consisting of one or more fields, separated by commas. Its important to know that the function we are about to use, d3.csv, uses the first line of the CSV as the header, that is, the line that contains the names of the fields.

So, consider this CSV, named "data.csv":

New York,3400,210

To load "data.csv", we use the function d3.csv. To make it easier, suppose that "data.csv" is in the same directory of our script, and its relative path is simply "data.csv". So, we write:

d3.csv("data.csv", function(data){
    //code dealing with data here

Notice that, in the callback, we used data as an argument. That's a common practice in D3, but you can use any other name.

What d3.csv does with our CSV? It converts the CSV in an array of objects. If, for instance, we console.log our data:

d3.csv("data.csv", function(data){

This is what we are going to see:

        "city": "New York",
        "population": "3400",
        "area": "210"
        "city": "Melbourne",
        "population": "1200",
        "area": "350"
        "city": "Tokyo",
        "population": "5200",
        "area": "125"
        "city": "Paris",
        "population": "800",
        "area": "70"

Now we can bind that data to our DOM elements.

Notice that, in this example, population and area are strings. But, probably, you want to deal with them as numbers. You can change them in a function inside the callback (as a forEach), but in d3.csv you can use an "accessor" function:

d3.csv("data.csv", conversor, function(data){
    //code here

function conversor(d){
    d.population = +d.population;
    d.area = +d.area;
    return d;

You can also use accessors in d3.tsv, but not in d3.json.

Note: d3.csv is an asynchronous function, meaning that the code after it will execute immediately, even before the CSV file is loaded. So, special attention for using your data inside the callback.