|
<!DOCTYPE html> |
|
<html lang="en"> |
|
<head> |
|
<meta charset="utf-8"> |
|
<title>Refugees by Origin</title> |
|
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script> |
|
</head> |
|
<body> |
|
|
|
<h1>Refugees by Origin</h1> |
|
|
|
<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; |
|
|
|
|
|
d3.csv("d3.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); |
|
|
|
// here we are making strings into numbers using type coercion: |
|
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.year2013 - data_item.year2010; |
|
|
|
data_item.sum = data_item.year1990 + data_item.year2000 + data_item.year2010 + data_item.year2013; |
|
|
|
total1990 = total1990 + data_item.year1990; |
|
total2000 = total2000 + data_item.year2000; |
|
total2010 = total2010 + data_item.year2010; |
|
total2013 = total2013 + data_item.year2013; |
|
|
|
console.log(index, data_item); |
|
|
|
}); |
|
|
|
console.log(data); |
|
console.log("total 1990", total1990); |
|
console.log("total 2000", total2000); |
|
console.log("total 2010", total2010); |
|
console.log("total 2013", total2013); |
|
|
|
// Sorting: |
|
|
|
data.sort(function (a, b) { |
|
return b.sum - a.sum; |
|
}); |
|
|
|
// Suppose you wanted it sorted the other way? How would you do that? |
|
|
|
console.log("sorted", data); |
|
|
|
//Other code to execute after successful file Load |
|
d3.select("body").append("h1").text("My Data"); |
|
d3.select("body").append("h3").text("Country 1990 2000 2010 2013 Total") |
|
|
|
d3.select("body").selectAll("p") |
|
.data(data) |
|
.enter() |
|
.append("p") |
|
.text(function(d){ |
|
return d.name + " " + d.year1990 + " " + d.year2000 + " " + d.year2010 + " " + d.year2013 + " " + d.sum; |
|
}); |
|
|
|
}); |
|
|
|
|
|
// 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? |
|
// console.log("totals", total1990, total2015); |
|
|
|
</script> |
|
|
|
</body> |
|
</html> |