-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05_click_transition.html
405 lines (315 loc) · 10 KB
/
05_click_transition.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Click to transition</title>
<script type="text/javascript" src="d3.js"></script>
<style type="text/css">
h1 {
font-family: Helvetica, sans-serif;
font-size: 14px;
font-weight: bold;
}
.area {
stroke: none;
}
.area:hover {
fill: yellow;
}
</style>
</head>
<body>
<h1>Monthly Number of Electric-Drive Vehicles Sold in the U.S. (by Type): January 2005–February 2017</h1>
<script type="text/javascript">
//Width and height
var w = 1400;
var h = 300;
var padding = 20;
var dataset, xScale, yScale, xAxis, yAxis, area; //Empty, for now
//For converting strings to Dates
var parseTime = d3.timeParse("%Y-%m");
//For converting Dates to strings
var formatTime = d3.timeFormat("%b %Y");
//Define key function, to be used when binding data
var key = function(d) {
return d.key;
};
//Set up stack methods
var vehicleStack = d3.stack();
var typeStack = d3.stack();
//Load in data
d3.request("vehicle_sales_data.csv")
.mimeType("text/csv")
.get(function(response) {
//
// DATA PARSING
//
//Parse each row of the CSV into an array of string values
var rows = d3.csvParseRows(response.responseText);
// console.log(rows);
//Make dataset an empty array, so we can start adding values
dataset = [];
//Loop once for each row of the CSV, starting at row 3,
//since rows 0-2 contain only vehicle info, not sales values.
for (var i = 3; i < rows.length; i++) {
//Create a new object
dataset[i - 3] = {
date: parseTime(rows[i][0]) //Make a new Date object for each year + month
};
//Loop once for each vehicle in this row (i.e., for this date)
for (var j = 1; j < rows[i].length; j++) {
var make = rows[0][j]; //'Make' from 1st row in CSV
var model = rows[1][j]; //'Model' from 2nd row in CSV
var makeModel = rows[0][j] + " " + rows[1][j]; //'Make' + 'Model' will serve as our key
var type = rows[2][j]; //'Type' from 3rd row in CSV
var sales = rows[i][j]; //Sales value for this vehicle and month
//If sales value exists…
if (sales) {
sales = parseInt(sales); //Convert from string to int
} else { //Otherwise…
sales = 0; //Set to zero
}
//Append a new object with data for this vehicle and month
dataset[i - 3][makeModel] = {
"make": make,
"model": model,
"type": type,
"sales": sales
};
}
}
//Log out the final state of dataset
// console.log(dataset);
//
// STACKING
//
//Now that we know the column names in the data,
//get all the keys (make + model), but toss out 'date'
var keys = Object.keys(dataset[0]).slice(1);
// console.log(keys);
//Tell stack function where to find the keys
vehicleStack.keys(keys)
.value(function value(d, key) {
return d[key].sales;
});
//Stack the data and log it out
var vehicleSeries = vehicleStack(dataset);
// console.log(vehicleSeries);
//
// TYPE DATA SERIES
//
//The goal here is to make a totally separate data set that
//includes just monthly totals for each `type` (HEV, PHEV, BEV, FCEV).
//Make typeDataset an empty array, so we can start adding values
typeDataset = [];
//Loop once for each row of the CSV, starting at row 3,
//since rows 0-2 contain only vehicle info, not sales values.
for (var i = 3; i < rows.length; i++) {
//Create a new object
typeDataset[i - 3] = {
date: parseTime(rows[i][0]), //Make a new Date object for each year + month
"HEV": 0,
"PHEV": 0,
"BEV": 0,
"FCEV": 0
};
//Loop once for each vehicle in this row (i.e., for this date)
for (var j = 1; j < rows[i].length; j++) {
var type = rows[2][j]; //'Type' from 3rd row in CSV
var sales = rows[i][j]; //Sales value for this vehicle and month
//If sales value exists…
if (sales) {
sales = parseInt(sales); //Convert from string to int
} else { //Otherwise…
sales = 0; //Set to zero
}
//Add sales value to existing sum
typeDataset[i - 3][type] += sales;
}
}
//Log out the final state of dataset
// console.log(typeDataset);
//
// STACKING
//
//Tell stack function where to find the keys
typeStack.keys([ "HEV", "PHEV", "BEV", "FCEV" ]);
//Stack the data and log it out
var typeSeries = typeStack(typeDataset);
// console.log(typeSeries);
//
// MAKE THE CHART
//
//Create scale functions
xScale = d3.scaleTime()
.domain([
d3.min(dataset, function(d) { return d.date; }),
d3.max(dataset, function(d) { return d.date; })
])
.range([padding, w - padding * 2]);
yScale = d3.scaleLinear()
.domain([
0,
d3.max(dataset, function(d) {
var sum = 0;
//Loops once for each row, to calculate
//the total (sum) of sales of all vehicles
for (var i = 0; i < keys.length; i++) {
sum += d[keys[i]].sales;
};
return sum;
})
])
.range([h - padding, padding / 2])
.nice();
//Define axes
xAxis = d3.axisBottom()
.scale(xScale)
.ticks(10)
.tickFormat(formatTime);
//Define Y axis
yAxis = d3.axisRight()
.scale(yScale)
.ticks(5);
//Define area generator
area = d3.area()
.x(function(d) { return xScale(d.data.date); })
.y0(function(d) { return yScale(d[0]); })
.y1(function(d) { return yScale(d[1]); });
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create areas for individual VEHICLES
svg.append("g")
.attr("id", "vehicles")
.selectAll("path")
.data(vehicleSeries, key)
.enter()
.append("path")
.attr("class", "area")
.attr("d", area)
.attr("fill", function(d) {
//Which vehicle is this?
var thisKey = d.key;
//What 'type' is this vehicle?
var thisType = d[0].data[thisKey].type;
// console.log(thisType);
//New color var
var color;
switch (thisType) {
case "HEV":
color = d3.schemeCategory20[0];
break;
case "PHEV":
color = d3.schemeCategory20[1];
break;
case "BEV":
color = d3.schemeCategory20[2];
break;
case "FCEV":
color = d3.schemeCategory20[3];
break;
}
return color;
})
.append("title") //Make tooltip
.text(function(d) {
return d.key;
});
//Create areas for TYPES
svg.append("g")
.attr("id", "types")
.selectAll("path")
.data(typeSeries, key)
.enter()
.append("path")
.attr("class", "area")
.attr("d", area)
.attr("fill", function(d) {
//Which type is this?
var thisType = d.key;
//New color var
var color;
switch (thisType) {
case "HEV":
color = "rgb(110, 64, 170)";
break;
case "PHEV":
color = "rgb(76, 110, 219)";
break;
case "BEV":
color = "rgb(35, 171, 216)";
break;
case "FCEV":
color = "rgb(29, 223, 163)";
break;
}
return color;
})
.on("click", function(d) {
//Which type was clicked?
var thisType = d.key;
//Generate a new data set with all-zero values,
//except for this type's data
var thisTypeDataset = [];
for (var i = 0; i < typeDataset.length; i++) {
thisTypeDataset[i] = {
date: typeDataset[i].date,
HEV: 0,
PHEV: 0,
BEV: 0,
FCEV: 0,
[thisType]: typeDataset[i][thisType] //Overwrites the appropriate zero value above
}
}
// console.log(thisTypeDataset);
//Stack the data (even though there's now just one "layer") and log it out
var thisTypeSeries = typeStack(thisTypeDataset);
// console.log(thisTypeSeries);
//Bind the new data set to paths, overwriting old bound data.
var paths = d3.selectAll("#types path")
.data(thisTypeSeries, key);
//Transition areas into new positions (i.e., thisType's area
//will go to a zero baseline; all others will flatten out).
//
//Store this transition in a new variable for later reference.
var areaTransitions = paths.transition()
.duration(1000)
.attr("d", area);
//Update scale
yScale.domain([
0,
d3.max(thisTypeDataset, function(d) {
var sum = 0;
//Calculate the total (sum) of sales of this type,
//ignoring the others (for now)
sum += d[thisType];
return sum;
})
]);
//Append this transition to the one already in progress
//(from above). Transition areas to newly updated scale.
areaTransitions.transition()
.delay(200)
.duration(1000)
.attr("d", area);
})
.append("title") //Make tooltip
.text(function(d) {
return d.key;
});
//Create axes
svg.append("g")
.attr("class", "axis x")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis y")
.attr("transform", "translate(" + (w - padding * 2) + ",0)")
.call(yAxis);
});
</script>
</body>
</html>