forked from arnicas/interactive-vis-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
d3_table.html
95 lines (70 loc) · 2.74 KB
/
d3_table.html
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Loading CSV Data with D3</title>
</head>
<body>
<h1>Loading CSV and making a table!</h1>
<p>This table shows regional access to improved water over 15 years. </p>
<p>Source: WHO/UNICEF (2015) Progress on Sanitation and Drinking Water: 2015 Update</p>
<div id="table"></div>
</body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script type="text/javascript">
//Load in contents of CSV file, and do things to the data.
d3.csv("data/water_improvement_data.csv", function(error, myData) {
if (error) {
console.log("Had an error loading file.");
}
// We'll be using simpler data as values, not objects.
var myArray = [];
myData.forEach(function(d, i){
// now we add another data object value, a calculated value.
d.difference = d.year2015 - d.year1990;
if (d.name === "Developing regions") {
d.name = "Developing Regions"; // fixing a label in js code - could fix in the file, of course
}
if (d.name === "Developed regions") {
d.name = "Deveoloped Regions";
}
// Add a new array with the values of each:
myArray.push([d.name, d.year1990, d.year2015, d.difference]);
});
console.log("original data is objects:", myData);
console.log("fixed data is an array of arrays:", myArray);
// sort by difference descending - the 4th item in each array:
myArray.sort(function(a,b) {
return d3.descending(a[3], b[3]);
});
// You could also have made the new array with a map function!
var table = d3.select("#table").append("table");
var header = table.append("thead").append("tr"); // after this, the header is the tr row.
// do a data join and create th items for each data element in the array
header
.selectAll("th")
.data(["Region", "1990", "2015", "Difference"]) // I can name them what I want
.enter()
.append("th")
.text(function(d) { return d; });
var tablebody = table.append("tbody");
rows = tablebody
.selectAll("tr")
.data(myArray) // this is the array of arrays we made above, in the same order as the column labels, sorted now.
.enter()
.append("tr");
// We built the rows using the nested array - now each row has its own array.
cells = rows.selectAll("td")
// each row has data associated; we get it and enter it for the cells.
.data(function(d) {
console.log(d);
return d;
})
.enter()
.append("td")
.text(function(d) {
return d;
});
});
</script>
</html>