Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing data from .csv using d3.js

I am trying to import some data from a .csv using d3.js. I am having trouble doing this, and was wondering if anyone could lend a hand. My .csv file is formatted like so:

max_i,min_i,max_f,min_f
-122.1430195,-122.1430195,-122.415278,37.778643
-122.1430195,-122.1430195,-122.40815,37.785034
-122.4194155,-122.4194155,-122.4330827,37.7851673
-122.4194155,-122.4194155,-122.4330827,37.7851673
-118.4911912,-118.4911912,-118.3672828,33.9164666
-121.8374777,-121.8374777,-121.8498415,39.7241178
-115.172816,-115.172816,-115.078011,36.1586877
-82.5618186,-82.5618186,-79.2274115,37.9308282
-79.9958864,-79.9958864,-80.260396,40.1787544
-74.1243063,-74.1243063,-74.040948,40.729688
-106.609991,-106.609991,-106.015897,35.640949

I am trying to load the data using the following code:

var dataset = []
d3.csv("data.csv", function(data) {
   dataset = data.map(function(d) { return [ +d["max_i"], +d["min_i"] ]; });
});
console.log(dataset)

However, I just get an empty [] in the console. Can anyone point out my mistake?

like image 849
araspion Avatar asked Apr 02 '13 00:04

araspion


People also ask

How do I import a CSV file into d3 JS?

D3 provides the following methods to load different types of data from external files. Sends http request to the specified url to load . csv file or data and executes callback function with parsed csv data objects. Sends http request to the specified url to load .

Is the syntax to read JSON data in d3?

json() function is used to fetch the JSON file. If this function got an init parameter, then this is called along with the fetch operation. Syntax: d3.

Is d3 CSV async?

d3. csv is asynchronous by design to prevent pages from freezing up, so that can't be changed without changing the d3 library itself. However, you could pre-load all your files via d3.

Is d3 js easy?

Conclusion. D3. js is a very powerful, yet simple, JavaScript library that allows you to play with and bring life to documents based on data using HTML, CSS, and SVG. There are a lot of good resources available online to learn D3.


1 Answers

Change it to:

var dataset = []
d3.csv("data.csv", function(data) {
   dataset = data.map(function(d) { return [ +d["max_i"], +d["min_i"] ]; });
   console.log(dataset)
});

You need to inspect dataset inside the callback, once your data is returned.

like image 163
Andy Thornton Avatar answered Sep 20 '22 18:09

Andy Thornton