Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript d3 reading from csv

Ok, so I am a bit of a noob with javascript and I need to read data from a csv to make a barchart with d3. The barchart is no problem for me, the reading from the csv file is. This is my code:

var dataset;
    d3.csv("gender_ratio.csv", function(data) {
    dataset = data;
    return dataset;
});

var add = function(year, total, males, females){
    var year = {
        year: year,
        total: total,
        males: males,
        females: females
    };
    newdata.push(year);
    return newdata;
};

for (var i = 0; i < dataset.length; i += 4){
    add(dataset[i], dataset[i+1], dataset[i+2], dataset[i+3]);
    return newdata;
};

Can someone tell me what I is going wrong here? I am running this with modzilla firefox, so the browser security isn't the problem here.

like image 214
Yoeril Avatar asked Jun 08 '15 09:06

Yoeril


People also ask

How to read data from CSV in d3 JS?

Use d3. csv("data. csv", function(data){...}) to get CSV from url and parse, or use d3.

What does d3 CSV return?

d3. csv() returns the data as an object. This object is an array of objects loaded from your csv file where each object represents one row of your csv file.

Is d3 CSV asynchronous?

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. text() and call d3.

Is the syntax to read JSON data in d3?

Syntax: d3. json(input[, init]);


2 Answers

First, d3's .csv function works asynchronous, thus you need to call te actual bar chart drawing function within the .csv function. If the csv file has a first row featuring column names, you can use a callback function:

var dataset = [];
d3.csv("gender_ratio.csv", function(d) {
  return {
    year: d.year,
    total: d.total,
    males: d.males,
    females: d.females,
  };
}, function(error, rows) {
  dataset = rows;
  drawBarChart();  /* <<-- This would be the call to the drawing function. */
});
like image 35
Paul Avatar answered Sep 25 '22 16:09

Paul


The call to load the csv data completes asynchronously. That means your for loop is run before the data has been loaded.

If you move the for loop into the callback function of the call to d3.csv then the data will be available.

You should also check what the returned data looks like for d3.csv. Your code assumes it is returning a flat array, whereas it actually returns an array of objects where each element represents a row. If you add a console.log in the callback of the function you'll get a better sense of what the data looks like.

You also have a return statement in that for loop which means it'll only process the first element of data before exiting the loop.

d3.csv("gender_ratio.csv", function(data) {
    dataset = data;
    // process data here
    console.log(data);
});
like image 105
knolleary Avatar answered Sep 22 '22 16:09

knolleary