Loading CSV Data
Tutorial
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 2,Cucumbers,$0.99,True 3,Magazine,$6.99,False
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:
- location - is the location of the CSV data. For example, "receipt.csv" or "http://example.com/receipt.csv".
- callback - a function to call once the data has been loaded.
The callback function itself has two parameters:
- error - an indicator that is populated if an error occured when trying to load the file.
- 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) { d3.select("#example") .selectAll("p") .data(data) .enter() .append("p") .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 data[0].Name // Spaces, use [] without a period data[0][Item Number]
Quiz
Things to do
- Change the sample below to output the "Is It Food?" column of the first row of the CSV data.
- Change the sample below to output an HTML table of the CSV data.
Extra Credit
- Apply a custom style to the Price column, making it stand out from the other columns. Use a CSS class and d3.classed()
- Try applying the custom style to other columns
- Misspell "receipt.csv" and output the error message that D3.js provides