-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwondertest.html
417 lines (375 loc) · 16.2 KB
/
wondertest.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
406
407
408
409
410
411
412
413
414
415
416
417
<html>
<head>
<title>Filterable Emissions Exploration</title>
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v6.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.4/themes/flick/jquery-ui.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>
<style>
body {
background-color: beige;
}
div.tooltip {
position: absolute;
text-align: center;
width: auto;
height: auto;
padding: 2px;
font: 12px sans-serif;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
#legend {
list-style: none;
margin-top: 30px;
width: 500px;
}
#legend span {
border: 1px solid #ccc;
float: left;
width: 12px;
height: 12px;
margin: 2px;
}
#leftPlot {
margin-right: 20px;
width: 45%;
display: inline-block;
vertical-align: top;
}
.bootstrap-select:not([class*="col-"]):not([class*="form-control"]):not(.input-group-btn) {
width: 100%;
}
#rightPlot {
display: inline-block;
width: 45%;
vertical-align: top;
}
.lastLabel {
float: right;
}
body {
width: 1300px;
margin: auto;
padding-bottom: 30px;
}
</style>
</head>
<body>
<h1>Filterable Emissions Exploration</h1>
<p>Climate change is an increasingly important challenge facing modern society. Emissions are a significant
contributing factor to this threat, and understanding the elements surrounding emissions is critical to determining
a path forward.</p>
<p><b>Purpose:</b> Please use this visualization to explore how emissions associate with various factors by country,
as well as the
breakdown of emissions types for given countries.</p>
<p><b>Instructions:</b> Hover over the points to see the represented country and click to update the pie chart. Use
the filters below to
adjust the scatterplot as desired.</p>
<div id="plots">
<div id="leftPlot">
<i>Orange points represent major G7 countries.</i><br />
<div id="scatterPlot"></div>
<button onclick="toggleFilters()" id="toggleButton">Show Filters</button>
<div id="filters">
<h4>Select year</h4>
<p id="yearSelect"><b>Selected year:</b> <span id="yearSelected">2010</span></p>
<div id="year"></div>
1970<span class="lastLabel">2012</span>
<p><i>Note: data for some years may be unavailable.</i></p>
<h4>Filter by population</h4>
<p><b>Selected range:</b> <span id="popSelected">10,000 – 1,000,000,000</span></p>
<div id="population" height=20px></div>
10,000<span class="lastLabel">1,000,000,000</span>
<h4>Select Y Axis variable</h4>
<select name="yVar" id="yVar" data-live-search="true" data-live-search-style="contains"
class="selectpicker"></select>
</div>
</div>
<div id="rightPlot">
<h2 id="pieChartTitle">Emissions Breakdown for World</h2>
<div id="pieChart"></div>
<ul id="legend"></ul>
</div>
</div>
<script>
const Y_VARS = {
"Access to electricity (% of population)": false,
"Agricultural land (% of land area)": false,
"Agricultural land (sq. km)": true,
"Agriculture, forestry, and fishing, value added (% of GDP)": false,
"Arable land (% of land area)": false,
"Foreign direct investment, net inflows (% of GDP)": true,
"Forest area (% of land area)": false,
"Forest area (sq. km)": true,
"Population growth (annual %)": false,
"Population living in areas where elevation is below 5 meters (% of total population)": false,
"Prevalence of underweight, weight for age (% of children under 5)": false,
"Primary completion rate, total (% of relevant age group)": false,
"Renewable electricity output (% of total electricity output)": false,
"Renewable energy consumption (% of total final energy consumption)": false,
"Rural land area where elevation is below 5 meters (% of total land area)": false,
"Rural land area where elevation is below 5 meters (sq. km)": true,
"School enrollment, primary and secondary (gross), gender parity index (GPI)": false,
"Urban land area where elevation is below 5 meters (% of total land area)": false,
"Urban land area where elevation is below 5 meters (sq. km)": true,
"Urban population": true,
"Urban population (% of total)": false,
"Urban population growth (annual %)": false,
}
function createDropdown() {
const select = document.getElementById("yVar");
Object.keys(Y_VARS).forEach((yVar) => {
const option = document.createElement("option");
option.text = option.value = yVar;
select.add(option);
})
}
createDropdown();
function toggleFilters() {
let filters = document.getElementById("filters");
let button = document.getElementById("toggleButton");
if (filters.style.display === "none") {
filters.style.display = "block";
button.innerText = "Hide Filters";
} else {
filters.style.display = "none";
button.innerText = "Show Filters";
}
}
document.getElementById("filters").style.display = "none";
function allToFloat(data) {
data.map(d => {
for (const key in d) d[key] = !isNaN(parseFloat(d[key])) ? parseFloat(d[key]) : d[key];
if ([1970, 1980, 1990].includes(d["Year"])) {
for (const key in d) {
if (key === "Year") continue;
if (typeof d[key] === 'number') {
d[key] = d[key] / 2;
}
}
}
return d;
});
return data;
}
d3.csv("https://raw.githubusercontent.com/ZeningQu/World-Bank-Data-by-Indicators/master/climate-change/climate-change.csv").then((climateData) => {
climateData = allToFloat(climateData);
const g7Countries = ['Canada', 'France', 'Germany', 'Italy', 'Japan', 'United Kingdom', 'United States']
// Setting parameters
let year = 2010;
let popMin = 10000, popMax = 1000000000;
let xVar = "Total greenhouse gas emissions (kt of CO2 equivalent)";
let yVar = Y_VARS[0];
let country = "World";
// Setting up variables that describe chart space
const height = 500;
const width = 600;
const margin = ({ top: 10, right: 20, bottom: 50, left: 50 });
// Create scatterplot SVG
const svg = d3.create('svg')
.attr('width', width)
.attr('height', height); const colorScale = (countryName) => d3.schemeTableau10[g7Countries.includes(countryName) ? 1 : 0]
const tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
// Add year background label
const yearLabel = svg.append('text');
// Initialize points
const symbol = d3.symbol();
const g = svg.append('g');
// Initialize x-axis
let xScale = d3.scaleLog()
.domain([1, d3.max(climateData, d => d[xVar])])
.range([margin.left, width - margin.right])
.nice();
const xAxisG = svg.append('g')
.attr('transform', `translate(0, ${height - margin.bottom})`);
const xAxisText = xAxisG.call(d3.axisBottom(xScale))
.append('text');
// Initialize y-axis
let yScale = d3.scaleLog()
.domain([1, d3.max(climateData, d => d[yVar])])
.range([height - margin.bottom, margin.top])
.nice();
const yAxisG = svg.append('g')
.attr('transform', `translate(${margin.left}, 0)`);
const yAxisText = yAxisG.call(d3.axisLeft(yScale))
.append('text');
function updateScatter() {
yVar = document.getElementById("yVar").value;
const data = climateData.filter(d => d["Year"] === year && d[xVar] >= 1 && d[yVar] >= 1 && d["Population, total"] >= popMin && d["Population, total"] <= popMax);
// Draw x-axis
xScale = d3.scaleLog()
.domain([1, d3.max(climateData, d => d[xVar])])
.range([margin.left, width - margin.right])
.nice();
xAxisG.call(d3.axisBottom(xScale));
xAxisText
.attr('transform', `translate(0, 40)`)
.attr('text-anchor', 'end')
.attr('fill', 'black')
.attr('font-size', '12px')
.attr('font-weight', 'bold')
.attr('x', width - margin.right)
.attr('y', -10)
.text(xVar);
// Draw y-axis
if (Y_VARS[yVar])
yScale = d3.scaleLog()
.domain([1, d3.max(climateData, d => d[yVar])])
.range([height - margin.bottom, margin.top])
.nice();
else
yScale = d3.scaleLinear()
.domain([1, d3.max(climateData, d => d[yVar])])
.range([height - margin.bottom, margin.top])
.nice();
yAxisG.call(d3.axisLeft(yScale));
yAxisText
.attr('transform', `translate(-40, ${margin.top}) rotate(-90)`)
.attr('text-anchor', 'end')
.attr('fill', 'black')
.attr('font-size', '12px')
.attr('font-weight', 'bold')
.text(yVar);
// Draw points
g
.selectAll('nnn')
.data(data)
.join('path')
.attr('class',"nnn")
.attr('transform', d => `translate(${xScale(d[xVar])}, ${yScale(d[yVar])})`)
.attr('fill', d => colorScale(d["Country Name"]))
.attr('d', d => symbol())
.on("mouseover", function (event, d) {
tooltip.transition()
.duration(200)
.style("opacity", .9);
tooltip.html(`${d["Country Name"]}`)
.style("left", (event.pageX) + "px")
.style("background", colorScale(d["Country Name"]))
.style("top", (event.pageY - 28) + "px");
d3.select(this)
.attr("fill", "black")
.attr("d", symbol.size(64 * 4));
})
.on("mouseout", function (event, d) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
d3.select(this)
.attr("fill", colorScale(d["Country Name"]))
.attr("d", symbol.size(64));
})
.on("click", function (event, d) {
country = d["Country Name"];
updatePie();
});
// Draw year label
yearLabel
.attr('x', 80)
.attr('y', height - margin.bottom - 20)
.attr('fill', '#ccc')
.attr('font-family', 'Helvetica Neue, Arial')
.attr('font-weight', 500)
.attr('font-size', 60)
.text(year);
}
document.getElementById("yVar").addEventListener("change", updateScatter);
$(function () {
$("#population").slider({
range: true,
min: 0,
max: 1000,
values: [0, 1000],
slide: function (event, ui) {
const minp = 0;
const maxp = 1000;
const minv = Math.log(10000);
const maxv = Math.log(1000000000);
const scale = (maxv - minv) / (maxp - minp);
popMin = Math.round(Math.exp(minv + scale * (ui.values[0] - minp)));
popMax = Math.round(Math.exp(minv + scale * (ui.values[1] - minp)));
document.getElementById("popSelected").innerText = `${Number(popMin).toLocaleString()} – ${Number(popMax).toLocaleString()}`
updateScatter();
}
});
});
$(function () {
$("#year").slider({
range: false,
min: 1970,
max: 2012,
value: 2010,
slide: function (event, ui) {
year = ui.value;
document.getElementById("yearSelected").innerText = `${year}`
updateScatter();
}
});
});
updateScatter();
// *********************************************************************
// Setting up variables that describe pie space
const pieHeight = 350;
const pieWidth = 350;
const pieRadius = Math.min(pieWidth, pieHeight) / 2;
const emissions = [
'CO2 emissions (kt)',
'Methane emissions (kt of CO2 equivalent)',
'Nitrous oxide emissions (thousand metric tons of CO2 equivalent)',
'Other greenhouse gas emissions, HFC, PFC and SF6 (thousand metric tons of CO2 equivalent)'
]
// Initialize pie graphics
const pieSvg = d3.create('svg')
.attr('width', pieWidth)
.attr('height', pieHeight)
.attr("viewBox", [-pieWidth / 2, -pieHeight / 2, pieWidth, pieHeight]);
const pieG = pieSvg.append('g')
.attr("stroke", "white");
const arc = d3.arc()
.innerRadius(0)
.outerRadius(pieRadius);
const pie = d3.pie()
.sort(null)
.value(d => d.value);
const pieColorScale = d3.scaleOrdinal()
.domain(emissions)
.range(d3.schemeDark2);
function updatePie() {
const selectedData = climateData.filter(d => d["Year"] === year && d["Country Name"] === country)[0];
const data = emissions.map(e => ({ key: e, value: selectedData[e] }));
// Draw slices
pieG.selectAll('path')
.data(pie(data))
.join("path")
.attr("fill", (d, i) => pieColorScale(emissions[i]))
.attr("d", arc);
document.getElementById("pieChartTitle").innerText = `Emissions Breakdown for ${country}`
}
updatePie();
// *********************************************************************
// Create legend
emissions.forEach((e, i) => {
const li = document.createElement("li");
const span = document.createElement("span");
span.style.backgroundColor = pieColorScale(e);
li.appendChild(span);
li.appendChild(document.createTextNode(e));
document.getElementById("legend").appendChild(li);
});
document.getElementById("scatterPlot").appendChild(svg.node());
document.getElementById("pieChart").appendChild(pieSvg.node());
});
</script>
</body>
</html>