- Expert Data Visualization
- Jos Dirksen
- 266字
- 2025-04-04 19:31:10
Loading CSV data with D3
To load data asynchronously, D3 provides a number of helper functions. In this case, we've used the d3.csv function:
d3.csv('data/yob2015.txt',
function (d) { return { name: d.name, sex: d.sex, amount: +d.amount }; },
function (data) {
...
}
The d3.csv function we use takes three parameters. The first one, data/yob2015.txt, is a URL which points to the data we want to load. The second argument is a function that is applied to each row read by D3. The object that's passed into this function is based on the header row of the CSV file. In our case, this data looks like this:
{
name: 'Sophie',
sex: 'F',
amount: '1234'
}
This (optional) function allows you to modify the data in the row, before it is passed on as an array (data) to the last argument of the d3.csv function. In this example, we use this second argument to convert the string value d.amount to a numeric value. Once the data is loaded and in this case converted, the function provided as the third argument is called with an array of all the read and converted values, ready for us to visualize the data.
D3 provides a number of functions like d3.csv to load data and resources. These are listed in the following table:

You can also manually process CSV files if they happen to use a different format. You should load those using the d3.text function, and use any of the functions from the d3-dsv module to parse the data. You can find more information on the d3-dsv module here: https://github.com/d3/d3-dsv.