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.
Use d3. csv("data. csv", function(data){...}) to get CSV from url and parse, or use d3.
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.
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.
Syntax: d3. json(input[, init]);
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. */
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With