Javascript D3 Reading From Csv
Solution 1:
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 hereconsole.log(data);
});
Solution 2:
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. */
});
Post a Comment for "Javascript D3 Reading From Csv"