forked from arnicas/interactive-vis-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
d3_process_data_dates.html
64 lines (45 loc) · 1.78 KB
/
d3_process_data_dates.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
<!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>
<p id="dates"></p>
<script type="text/javascript">
//Load in contents of CSV file, and do things to the data.
d3.csv("data/Angola_water_access.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.
// We're telling the parser what the input string format is:
var dateParser = d3.time.format("%Y"); // this is 2007 etc, as in the file.
var outputDate = d3.time.format(" '%y "); // this is '07 format - with spaces around it
// Your arguments for forEach are the item and its number in the array:
data.forEach(function(d, i){
d.water_access = +d.water_access; // convert the water_access to a number
// you apply the function with parse, to read it in:
d.parsed_year = dateParser.parse(d.year);
console.log(i, d); // now look at d.year and d.parsed_year.
// if you wanted to print it in a short format, instead:
console.log("output string", i, outputDate(d.parsed_year));
});
// here's a sample of using d3 to print the output dates:
var mydates = d3.select("p#dates");
mydates
.selectAll("p")
.data(data)
.enter()
.append("p")
.text(function(d) {
return "My output year format is:" + outputDate(d.parsed_year);
});
});
</script>
</body>
</html>