Skip to content

How to load data from a CSV file in D3 v5

I’m trying to load data from a CSV file in D3; I have this code:

function update (error, data) {
    if (error !== null) {
        alert ("Couldn't load the dataset!");
    } else {
        //do something
    };

function changeData () {
    d3.csv ("data/dataset.csv", update);
}

If I use D3 v4 it works fine, but if I switch to v5 it doesn’t work anymore. Can someone explain to me how to modify the code to make it work with D3 v5?

Answer

d3 v5 uses the fetch API and returns a promise requiring the below code.

d3.csv('yourcsv.csv')
  .then(function(data) {
      // data is now whole data set
      // draw chart in here!
  })
  .catch(function(error){
     // handle error   
  })

In case in the future people want v4. d3 v4 on the other hand uses the XMLHttpRequest method, and does not return a promise requiring this code

d3.csv('yourcsv.csv', function(data) {
    //whole data set
    // draw chart here
})

csv loading is async so make sure to run your chart code within the csv function.