Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
StormPooper Avatar asked Apr 01 '18 15:04

StormPooper


People also ask

How to load csv data in d3?

D3 provides the following methods to load different types of data from external files. Sends http request to the specified url to load . csv file or data and executes callback function with parsed csv data objects. Sends http request to the specified url to load .

Is the syntax to read JSON data in d3?

json() function is used to fetch the JSON file. If this function got an init parameter, then this is called along with the fetch operation. Syntax: d3.

Is d3 CSV async?

d3. csv is asynchronous by design to prevent pages from freezing up, so that can't be changed without changing the d3 library itself. However, you could pre-load all your files via d3.

What does d3 JSON return?

The function d3. json() is an asynchronous function that directly returns (with an undefined value I assume). Only when the data is received from the backend, the callback function you passed to it will be called.


1 Answers

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.

like image 112
pmkro Avatar answered Sep 18 '22 06:09

pmkro