D3 - Csv Function (CSV from an URL)

> Data Visualization (vis|viz|graphic|image) > D3 (Data-Driven Documents)

1 - About

This section talks about the function d3.csv that parse a CSV file. To parse a CSV string, see D3 - DSV.

Reference: Csv

3 - Prerequisites

4 - Properties

  • The mime type of the request is “text/csv”.
  • The request is processed asynchronously, such that the method returns immediately after opening the request.

A common mistake is to include references to the external data outside of the callback function. This may cause problem because the function is asynchronous. To prevent problems, make sure to reference your data only from within the callback function (or from within other functions that you call within the callback function).

  • D3 employed the first row of the CSV for property names, and subsequent rows for values.

Each value from the CSV is stored as a string, even the numbers

Advertising

5 - Syntax

5.1 - Csv

d3.csv(url[[, accessor], callback])

where:

  • URL: Default to relative.
  • An optional accessor function may be specified, which is then passed to d3.csv.parse
  • callback is a function invoked with as the argument the parsed rows or null if an error occurs.
var dataset;  //Global var
 
d3.csv(url, function(error, data) {
    // If error is not null, something went wrong.
    if (error) {  
          console.log(error);  //Log the error.
    } else {      
          console.log(data);   //Log the data.
          dataset = data; // Give the data a global scope
          //Call some other functions that generate the visualization
    }
});

5.2 - Text

Csv is an alias to the text function.

d3.text(url, 'text/csv', function(rawData) {
 
    // Remove comment rows with regex (Starting with the # characters)
    rawData = rawData.replace(  /^[#][^\r\n]+[\r\n]+/mg , '');
 
    // Parse the text as csv
    csvData = d3.csv.parse(rawData);
 
    // Continue
 
   }
);

with Javascript - Regular expression (Regexp)

6 - Example

Name,Age
Nicolas,42
Rixt,39
Madelief,10
Melissa,6
  • Script

d3.csv("https://gerardnico.com/datafile/basic_d3.csv", function(data) {
    // Process the data, for instance
    for (var i=0;i<data.length;i++) {
           console.log(data[i].Name+" is "+data[i].Age+" years.");
    }
});
  • Output:

Advertising

7 - Debugging

You can see the data array by sending it to the console log

d3.csv("basic_d3.csv", function(data) {
        console.log(data);
    });

Example from the devtools of chrome:

viz/d3/csv_function.txt · Last modified: 2019/04/14 14:25 by gerardnico