Table of Contents

D3 - Csv Function (CSV from an URL)

About

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

Reference: Csv

Prerequisites

Properties

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).

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

Syntax

Csv

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

where:

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
    }
});

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 How to use Regular expression (Regexp) in Javascript?

Example

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


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.");
    }
});

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:

D3 Csv Console Log