-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathd3_process_data.html
More file actions
79 lines (52 loc) · 2.18 KB
/
d3_process_data.html
File metadata and controls
79 lines (52 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!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 total2015 = 0;
d3.csv("data/water_improvement_data.csv", function(error, data) {
console.log("data I input", 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 and a shortcut you will use a lot:
data_item.year1990 = +data_item.year1990;
data_item.year2015 = +data_item.year2015;
// now we add another data object value, a calculated value.
data_item.difference = data_item.year2015 - data_item.year1990;
total1990 = total1990 + data_item.year1990;
total2015 = total2015 + data_item.year2015;
console.log(index, data_item);
});
console.log(data);
console.log("total 1990", total1990);
console.log("total 2015", total2015);
// Sorting:
data.sort(function (a, b) {
return b.difference-a.difference;
});
// Suppose you wanted it sorted the other way? How would you do that?
console.log("sorted", data);
});
// 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>