.csv()
Published Dec 11, 2023
Contribute to Docs
The .csv()
function in D3 is used to load and parse CSV (Comma-Separated-Values
) files or data asynchronously. It returns the data as an array of objects. The function is commonly used in data visualization.
Syntax
d3.csv(url[[, accessor], callback])
url
: The URL of the CSV file or a string containing the CSV data.accessor
: An optional conversion function to change the representation. It allows for custom data transformation and returns processed data for each row.callback
: An optional callback function that executes once the data is loaded and parsed.
Example
In the following example .csv()
is used to load and parse CSV data. In this case, the accessor is the anonymous function(d)
. It uses two callback functions: .then(function(data) {})
and .catch(function(error) {})
:
Consider the comma-separated data in example.csv:
Name,Age,CityAlice,25,New YorkBob,30,San FranciscoCharlie,28,Los AngelesDarwin,34,Miami
To load, parse, and print the data in example.csv
, the following code is executed:
d3.csv('example.csv', function (d) {// 'd' is an object representing a row in the CSVreturn {name: d.Name,age: +d.Age, // Convert age to a numbercity: d.City,};}).then(function (data) {// 'data' is an array of processed objectsconsole.log(data);}).catch(function (error) {// Handle any errors that occurred during loading or parsingconsole.error(error);});
- The accessor function applies to each row of CSV data, transforming it into an object with the properties
name
,age
, andcity
. - The callback function
.then(function(data) {})
handles the processed data whereas.catch(function(error) {})
handles potential errors during the loading process.
The example results in the following output:
[{ name: 'Alice', age: 25, city: 'New York' },{ name: 'Bob', age: 30, city: 'San Francisco' },{ name: 'Charlie', age: 28, city: 'Los Angeles' },{ name: 'Darwin', age: 34, city: 'Miami' }]
This is the processed data after applying the accessor function and the first callback function.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript:D3 on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Course
Learn D3
Learn how to create bar charts with D3, the popular interactive data visualization library.With CertificateIntermediate1 hour