forked from sgratzl/d3tutorial
-
Notifications
You must be signed in to change notification settings - Fork 5
/
mcv06_final.html
338 lines (289 loc) · 9.85 KB
/
mcv06_final.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Student's First Multiple Coordinated View</title>
<meta name="description" content="Student's First Multiple Coordinated View" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
<script src="../web_modules/d3/dist/d3.js"></script>
<link href="./mvc.css" rel="stylesheet" />
<style>
rect {
fill: steelblue;
fill-opacity: 0.8;
}
rect:hover {
fill-opacity: 1;
}
path {
fill-opacity: 0.8;
}
.selected,
path:hover {
fill-opacity: 1;
}
.axis {
font-size: smaller;
}
main {
display: flex;
flex-wrap: wrap;
}
h3 {
text-align: center;
}
</style>
</head>
<body>
<h1>Student's First Multiple Coordinated View</h1>
<div>
<label for="passenger-class"><strong>Passenger Class:</strong></label>
<select id="passenger-class">
<option value="" selected>All Classes</option>
<option value="1">First Class</option>
<option value="2">2nd Class</option>
<option value="3">3rd Class</option>
</select>
<strong>Selected Gender: </strong>
<span id="selectedSex"></span>
<strong>Selected Survived: </strong>
<span id="selectedSurvived"></span>
</div>
<main>
<section>
<h3>Gender Distribution</h3>
<svg id="sex"></svg>
</section>
<section>
<h3>Age Histogram</h3>
<svg id="age"></svg>
</section>
<section>
<h3>Fare Histogram</h3>
<svg id="fare"></svg>
</section>
<section>
<h3>Survived Distribution</h3>
<svg id="survived"></svg>
</section>
</main>
<script>
const state = {
data: [],
passengerClass: "",
selectedSex: null,
selectedSurvived: null,
};
function createHistogram(svgSelector) {
const margin = {
top: 40,
bottom: 10,
left: 120,
right: 20,
};
const width = 600 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;
// Creates sources <svg> element
const svg = d3
.select(svgSelector)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
// Group used to enforce margin
const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);
// Scales setup
const xscale = d3.scaleLinear().range([0, width]);
const yscale = d3.scaleLinear().range([0, height]);
// Axis setup
const xaxis = d3.axisTop().scale(xscale);
const g_xaxis = g.append("g").attr("class", "x axis");
const yaxis = d3.axisLeft().scale(yscale);
const g_yaxis = g.append("g").attr("class", "y axis");
function update(new_data) {
//: (IPerson[] & {x0: number, x1: number})[]
//update the scales
xscale.domain([0, d3.max(new_data, (d) => d.length)]);
yscale.domain([new_data[0].x0, new_data[new_data.length - 1].x1]);
//render the axis
g_xaxis.transition().call(xaxis);
g_yaxis.transition().call(yaxis);
// Render the chart with new data
// DATA JOIN
const rect = g
.selectAll("rect")
.data(new_data)
.join(
(enter) => {
// ENTER
// new elements
const rect_enter = enter
.append("rect")
.attr("x", 0) //set intelligent default values for animation
.attr("y", 0)
.attr("width", 0)
.attr("height", 0);
rect_enter.append("title");
return rect_enter;
},
// UPDATE
// update existing elements
(update) => update,
// EXIT
// elements that aren't associated with data
(exit) => exit.remove()
);
// ENTER + UPDATE
// both old and new elements
rect
.transition()
.attr("height", (d) => yscale(d.x1) - yscale(d.x0) - 2)
.attr("width", (d) => xscale(d.length))
.attr("y", (d) => yscale(d.x0) + 1);
rect.select("title").text((d) => `${d.x0}: ${d.length}`);
}
return update;
}
function createPieChart(svgSelector, stateAttr, colorScheme) {
const margin = 10;
const radius = 100;
// Creates sources <svg> element
const svg = d3
.select(svgSelector)
.attr("width", radius * 2 + margin * 2)
.attr("height", radius * 2 + margin * 2);
// Group used to enforce margin
const g = svg.append("g").attr("transform", `translate(${radius + margin},${radius + margin})`);
const pie = d3
.pie()
.value((d) => d.values.length)
.sortValues(null)
.sort(null);
const arc = d3.arc().outerRadius(radius).innerRadius(0);
const noSlice = [
{ startAngle: 0, endAngle: Math.PI * 2, padAngle: 0 },
{ startAngle: 0, endAngle: 0, padAngle: 0 },
];
const cscale = d3.scaleOrdinal(colorScheme);
function update(new_data) {
//{key: string, values: IPerson[]}[]
const pied = pie(new_data);
// Render the chart with new data
cscale.domain(new_data.map((d) => d.key));
// DATA JOIN
const old = g.selectAll("path").data();
function tweenArc(d, i) {
const interpolate = d3.interpolateObject(old[i], d);
return (t) => arc(interpolate(t));
}
// DATA JOIN
const path = g
.selectAll("path")
.data(pied, (d) => d.data.key)
.join(
// ENTER
// new elements
(enter) => {
const path_enter = enter
.append("path")
.attr("d", (d, i) => arc(noSlice[i]))
.on("click", (e, d) => {
if (state[stateAttr] === d.data.key) {
state[stateAttr] = null;
} else {
state[stateAttr] = d.data.key;
}
updateApp();
});
path_enter.append("title");
return path_enter;
},
(update) => update,
(exit) => exit.transition().attrTween("d", tweenArc).remove()
);
// ENTER + UPDATE
// both old and new elements
path
.classed("selected", (d) => d.data.key === state.selectedSex)
.transition()
.attrTween("d", tweenArc)
.style("fill", (d) => cscale(d.data.key));
path.select("title").text((d) => `${d.data.key}: ${d.data.values.length}`);
}
return update;
}
/////////////////////////
const ageHistogram = createHistogram("#age");
const sexPieChart = createPieChart("#sex", "selectedSex", d3.schemeSet3);
const fareHistogram = createHistogram("#fare");
const survivedPieChart = createPieChart("#survived", "selectedSurvived", d3.schemeSet3.slice(2));
function filterData() {
return state.data.filter((d) => {
if (state.passengerClass && d.pclass !== state.passengerClass) {
return false;
}
if (state.selectedSex && d.sex !== state.selectedSex) {
return false;
}
if (state.selectedSurvived && d.survived !== state.selectedSurvived) {
return false;
}
return true;
});
}
function wrangleData(filtered) {
const ageHistogram = d3
.bin()
.domain([0, 100])
.thresholds(10)
.value((d) => d.age);
const ageHistogramData = ageHistogram(filtered);
// always the two categories
const sexPieData = ["female", "male"].map((key) => ({
key,
values: filtered.filter((d) => d.sex === key),
}));
const fareHistogram = d3
.bin()
.domain([0, d3.max(filtered, (d) => d.fare)])
.value((d) => d.fare);
const fareHistogramData = fareHistogram(filtered);
// always the two categories
const survivedPieData = ["0", "1"].map((key) => ({
key,
values: filtered.filter((d) => d.survived === key),
}));
return {
ageHistogramData,
sexPieData,
fareHistogramData,
survivedPieData,
};
}
function updateApp() {
const filtered = filterData();
const { ageHistogramData, sexPieData, fareHistogramData, survivedPieData } = wrangleData(filtered);
ageHistogram(ageHistogramData);
sexPieChart(sexPieData);
fareHistogram(fareHistogramData);
survivedPieChart(survivedPieData);
d3.select("#selectedSex").text(state.selectedSex || "None");
d3.select("#selectedSurvived").text(state.selectedSurvived || "None");
}
d3.csv("titanic3.csv").then((parsed) => {
state.data = parsed.map((row) => {
row.age = parseInt(row.age, 10);
row.fare = parseFloat(row.fare);
return row;
});
updateApp();
});
//interactivity
d3.select("#passenger-class").on("change", function () {
const selected = d3.select(this).property("value");
state.passengerClass = selected;
updateApp();
});
</script>
</body>
</html>