Loading CSV Data


D3 is all about creating things based on data, which means we need ways to get our data to D3. Often data exists in separate files or webservices. D3 has functionality to help import data that is separate from your webpage provided you can access it with a URL and it is a common data format such as CSV, TSV, XML, or JSON. In this lab we'll talk about importing CSV data.

What is CSV data? CSV stands for comma separated values. It is a commonly used data exchange format for tabular data. Here is some sample CSV data representing a grocery receipt:

Item Number,Name,Price,Is It Food?
1,Greek Yogurt,$0.88,True

Tabular means that each entry has the same number of fields and the fields have no heirarchy. Notice how each column is separated by a comma. The comma in this case is called a delimiter. It lets us know where each field ends. Each record or row of data is delimited with a new line. The first line of the file contains the column headers or column names.

How does D3.js help?

D3.js makes it easy to put existing data into a visualization. Let's say that the CSV above was in a file called "receipt.csv". We would use the d3.csv function to load this CSV data. This function takes two parameters:

  1. location - is the location of the CSV data. For example, "receipt.csv" or "http://example.com/receipt.csv".
  2. callback - a function to call once the data has been loaded.

The callback function itself has two parameters:

  1. error - an indicator that is populated if an error occured when trying to load the file.
  2. data - The data from the CSV file. The data is an array of objects, with each object representing a row of the data. The properties of the data parameter object are named according to the CSV's header row.

Below is how the CSV file is represented after being loaded by D3. Notice how D3 retrieves and parses the CSV file into a convient object format to save us the trouble.

function callback(error, data) { 
    .text(function(d) { return JSON.stringify(d); }); // Turn object into JSON string

As a reminder to access Javascript object properties that have spaces in them you have to use square brackets instead of a period followed by the field name.

// No spaces, use period followed by property's name

// Spaces, use [] without a period
data[0][Item Number]


Things to do

  1. Change the sample below to output the "Is It Food?" column of the first row of the CSV data.
  2. Change the sample below to output an HTML table of the CSV data.

Extra Credit

Change the code on the left. Once you've made a change, the page will render on the right.