D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
lmelgar
Full window
Github gist
Data homework
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Loading CSV Data with D3</title> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script> </head> <body> <h1>Loading CSV and processing the data.</h1> <p>Not much to see here; try looking in the console!</p> <p>If you open the console after loading, you'll need to reload the page.</p> <script type="text/javascript"> //Load in contents of CSV file, and do things to the data. var total1990 = 0; var total2000 = 0; var total2010 = 0; var total2013 = 0; var total = 0; var body = d3.select("body"); d3.csv("UN_RefugeesByOrigin_1990-2013.csv", function(error, data) { if (error) { console.log("Had an error loading file."); } // let's do things to the data here. This is VERY COMMON in d3 code. console.log(data); // Your arguments for forEach are the item and it's number in the array: data.forEach(function(data_item, index){ // NB: it's much more common to see (d, i) as shorthand in D3 code. console.log(index, data_item); data_item.year1990 = +data_item.year1990; data_item.year2000 = +data_item.year2000; data_item.year2010 = +data_item.year2010; data_item.year2013 = +data_item.year2013; // now we add another data object value, a calculated value. /*data_item.difference = data_item.year2015 - data_item.year1990;*/ total1990 = total1990 + data_item.year1990; total2000 = total2000 + data_item.year2000; total2010 = total2010 + data_item.year2010; total2013 = total2013 + data_item.year2013; total = data_item.total1990 + data_item.total2000 + data_item.total2010 + data_item.total2013; difference = total2013 - total2010; console.log(index, data_item); }); console.log("total 1990", total1990); console.log("total 2000", total2000); console.log("total 2010", total2010); console.log("total 2013", total2013); console.log("total", total) /*console.log("difference", difference)*/ // Sorting: data.sort(function (a, b) { return a.year1990 - b.year1990; }); // Suppose you wanted it sorted the other way? How would you do that? console.log("sorted", data); /*data.forEach(function (data) { body.append("p").text(d.country + ", " + total); });*/ }); // Notice this below doesn't work. It's outside the scope of the function that loaded the data. You need to keep your operations on data inside the loading callback. //console.log("my data now", data); // what do you expect these values to be now? what's going on? </script> </body> </html>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js