forked from jpalusky/4460-Project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcs4460Project.html
More file actions
666 lines (565 loc) · 23 KB
/
cs4460Project.html
File metadata and controls
666 lines (565 loc) · 23 KB
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Team World Life</title>
<style>
/*CSS STYLES*/
@font-face {
font-family: "Telegrafico";
src: url("Telegrafico.ttf");
}
body {
background-color: #ffffff;
margin:0;
padding: 0px;
}
.top-banner {
position: fixed;
background: #2c3e50;
text-align: center;
display: block;
color: #ffffff;
font-size: 25px;
height:30px;
width: 100%;
padding:2px;
z-index: 5;
}
.top-banner a {
font-family: "Telegrafico", sans-serif;
color:#ffffff;
cursor: pointer;
text-decoration:none;
letter-spacing: 4px;
font-weight: bold;
}
/* Path and line styling to make the axis look nicer */
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges; /* This is an SVG property that makes sure there is no blur on lines */
}
.axis text {
font-family: Century Gothic, sans-serif;
font-size: 11px;
}
text {
font-family: Century Gothic, sans-serif;
}
p {
font-family: Century Gothic, sans-serif;
}
#dropDown {
margin-left: 5px;
margin-top: 14px;
float: left;
}
.tooltip {
padding: 5px;
font-family: Century Gothic, sans-serif;
text-align: center;
color: rgba(0,0,0,0.6);
}
</style>
<!-- Slider stuff -->
<link rel="stylesheet" id="themeCSS" href="iThing.css">
<link rel="stylesheet" href="style.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<script src="jquery.mousewheel.min.js"></script>
<script src="../jQAllRangeSliders-min.js"></script>
</head>
<body>
<!-- D3, topojson, and datamaps -->
<script type="text/javascript" src="d3.v3.js"></script>
<script type="text/javascript" src="topojson.js"></script>
<script src="datamaps.world.min.js"></script>
<script src="zoompan.js"></script>
<div class="top-banner">
<a href="index.html">World Map Data</a>
</div>
<!-- Div for cholopleth map -->
<div id="basic_choropleth" style="position: relative; width: 1400px; height:600px; margin: 0 auto;"></div>
<!-- Slider -->
<div id="slider" style="width: 1400px; margin: 0 auto;"></div>
<button type="button" id="button">
Animate
</button>
<br>
<p style="float: left; margin-left: 20px;">Country name:</p>
<!-- Country dropdown bar --->
<select name="countryList" id="dropDown">
<option value="All" id="defaultSelect">Select a country</option>
</select>
<!-- D3 and Javascript portion -->
<script>
var lifeDataDataset = {
initialMinDatasetYear: 1960,
initialMaxDatasetYear: 2012,
colorMin: -1.0,
colorMax: 1.0
}
var allDatasets = [];
allDatasets.push(lifeDataDataset);
//Input the csv, calling it "dataset"
d3.csv("LifeData.csv", function(error, dataset) {
/*
dataset.forEach(function(row) {
console.log(Object.keys(row));
});
*/
//To do: calculate first and last year fields with javascript or d3
var initialMinDatasetYear = allDatasets[0].initialMinDatasetYear;
var initialMaxDatasetYear = allDatasets[0].initialMaxDatasetYear;
var minDatasetYear = 1960;
var maxDatasetYear = 2012;
//Create width, height, and padding for the line charts
var w = 1400;
var h = 300;
var padding = 50;
var currentCountry;
var countryName = [];
var xScale = d3.scale.linear();
var yScale = d3.scale.linear();
var xAxis = d3.svg.axis();
var yAxis = d3.svg.axis();
var yAxis2 = d3.svg.axis();
var line = d3.svg.line()
.defined(function(d,i) { return d['value'] > 0; })
.x(function(d, i) { return xScale(+d.key); })
.y(function(d, i) { return yScale(+d['value']); });
var line2 = d3.svg.line()
.defined(function(d,i) { return d['value'] > 0; })
.x(function(d, i) { return xScale(+d.key); })
.y(function(d, i) { return yScale(+d['value']); });
//Create the slider
$("#slider").rangeSlider({
bounds:{min: minDatasetYear, max: maxDatasetYear},
range: {min: 5, max: maxDatasetYear - minDatasetYear},
defaultValues:{min: minDatasetYear, max: maxDatasetYear}
});
//Change variables on slider change
$("#slider").on("valuesChanging", function(e, data){
minDatasetYear = Math.round(data.values.min);
maxDatasetYear = Math.round(data.values.max);
// main.select('.main.axis.month').call(x1MonthAxis);
xScale.domain([minDatasetYear, maxDatasetYear]);
createChoropleth(minDatasetYear, maxDatasetYear);
//This adds annotations about the world
checkForPopups();
//This refreshes the line graph
countryClick(currentCountry, true);
});
//Change variables on slider change
$("#slider").on("valuesChanged", function(e, data){
minDatasetYear = Math.round(data.values.min);
maxDatasetYear = Math.round(data.values.max);
// main.select('.main.axis.month').call(x1MonthAxis);
xScale.domain([minDatasetYear, maxDatasetYear]);
createChoropleth(minDatasetYear, maxDatasetYear);
//This adds annotations about the world
checkForPopups();
//This refreshes the line graph
countryClick(currentCountry, true);
});
//Create a new object from the Datamap plugin, called basic_choropleth (the variable and id have the same name)
var basic_choropleth = new Datamap({
element: document.getElementById("basic_choropleth"),
geographyConfig: {
highlightOnHover: true,
highlightFillColor: "#E0E0FF",
highlightBorderColor: '#000000',
borderColor: '#606060',
popupTemplate: function(geography) {
//Details on demand settings
var tooltipOutput;
dataset.forEach(function(d, i){
if(geography.id.replace(" ", "") == d["Country Code"].replace(" ", "")) {
var lifeExpectMin = (d[minDatasetYear + ""]).toFixed(2);
var lifeExpectMax = (d[maxDatasetYear + ""]).toFixed(2);
var slope = ((d[maxDatasetYear + ""] - d[minDatasetYear + ""])/(maxDatasetYear-minDatasetYear)).toFixed(2);
if(isNaN(lifeExpectMin) || lifeExpectMin <= 0){
lifeExpectMin = "N/A";
}
if(isNaN(lifeExpectMax) || lifeExpectMax <= 0){
lifeExpectMax = "N/A";
}
if(isNaN(lifeExpectMin) || isNaN(lifeExpectMax)){
slope = "N/A";
}
tooltipOutput = '<div class="hoverinfo">'
+ geography.properties.name + '<br>'
+ minDatasetYear + ' data value: ' + lifeExpectMin + '<br>'
+ maxDatasetYear + ' data value: ' + lifeExpectMax + '<br>'
+ 'Slope: ' + slope;
}
});
return tooltipOutput;
},
highlightBorderWidth: 1
},
done: function(datamap) { //On country click
datamap.svg.selectAll('.datamaps-subunit').on('click', function(geography) {
currentCountry = geography.id;
countryClick(currentCountry, true); //Boolean input "true" removes old graph
});
},
});
calcSlope = function(x1, x2, y1, y2){
return (x2 - x1)/(y2 - y1);
}
//Zoom and pan
var beforePan;
beforePan = function(oldPan, newPan){
var stopHorizontal = false
, stopVertical = false
, gutterWidth = 1300
, gutterHeight = 500
// Computed variables
, sizes = this.getSizes()
, leftLimit = -((sizes.viewBox.x + sizes.viewBox.width) * sizes.realZoom) + gutterWidth
, rightLimit = sizes.width - gutterWidth - (sizes.viewBox.x * sizes.realZoom)
, topLimit = -((sizes.viewBox.y + sizes.viewBox.height) * sizes.realZoom) + gutterHeight
, bottomLimit = sizes.height - gutterHeight - (sizes.viewBox.y * sizes.realZoom)
customPan = {}
customPan.x = Math.max(leftLimit, Math.min(rightLimit, newPan.x))
customPan.y = Math.max(topLimit, Math.min(bottomLimit, newPan.y))
return customPan;
}
var mapsvg = document.querySelector(".datamap");
var panZoom = svgPanZoom(mapsvg, {
mouseWheelZoomEnabled: false,
zoomEnabled: true,
controlIconsEnabled: true,
fit: true,
center: true,
zoomScaleSensitivity: 0.5,
minZoom: 1,
maxZoom: 3,
beforePan: beforePan
});
dataset.forEach(function(d) {
for(var j = initialMinDatasetYear; j <= initialMaxDatasetYear; j++)
{
//Plus sign turns data values at years into numbers.
d[j + ""] = +d[j + ""]; //Turn year to string so that d3 understands it
}
countryName.push([d["Country Name"], d["Country Code"]]);
});
//Country drop down
var dropDown = d3.select("#dropDown");
var countrySort = countryName.sort();
var options = dropDown.selectAll("option")
.data(countrySort)
.enter()
.append("option")
.text(function (d, i) { return d[0] + ": " + d[1]; })
.attr("value", function (d, i) { return d[1]});
dropDown.on("change", menuChanged);
function menuChanged() {
var selectedValue = d3.event.target.value;
currentCountry = selectedValue;
countryClick(selectedValue, true);
}
//Button stuff
var interval;
var myButton = d3.select("#button");
myButton.on("click", function(){
interval = setInterval(animateSlider, 400)
// var finished = false;
// while(!finished)
// {
// }
/*
d3.select("#zeroMedals").attr("style", "color: black");
createPies("All");
var defaultSelect = d3.select("#defaultSelect");
defaultSelect.attr("selected", "selected");
*/
});
var animateSlider = function(){
if(maxDatasetYear < initialMaxDatasetYear){
minDatasetYear++;
maxDatasetYear++;
$("#slider").rangeSlider("values", minDatasetYear, maxDatasetYear);
}
else{
clearInterval(interval);
}
}
//Create the scale for the choropleth
var colorScale2 = d3.scale.linear()
//NOTE: Un-comment the .domain below to have the colorscale that takes the actual year differences.
//.domain([choroplethDifMin, 0, choroplethDifMax]) //This would have to be inside of create gradient.
.domain([allDatasets[0].colorMin, 0, allDatasets[0].colorMax])
.clamp(true)
.range(["#FF4D4D", "white", "rgb(64, 150, 44)"]);//"#40BD28"]);
var createGradient = function(minChange, maxChange){
//Create linear gradient below map (this is a bit of a process)
var gradient = d3.select("#basic_choropleth").selectAll("svg")
.append("svg:g") //Put the gradient in a g element inside of the svg
.attr("width", "400")
.attr("height", "50")
.attr("transform", "translate(40, 500)"); //Put the gradient at the bottom of the map
//Define the gradient with a defs element
var defs = gradient.append("defs");
var linearGrad = defs.append("linearGradient")
.attr({
id: "grad1",
x1: "0%",
y1: "0%",
x2: "100%",
y2: "0%",
});
linearGrad.append("stop") //Tell where to start the gardient (min)
.attr({
offset: "0%",
style: "stop-color:" + colorScale2(minChange) + "; stop-opacity:1",
});
linearGrad.append("stop") //Tell where to start the gardient (min)
.attr({
offset: "15%",
style: "stop-color:" + colorScale2(0) + "; stop-opacity:1",
});
linearGrad.append("stop") //Tell where to end the gradient (max)
.attr({
offset: "100%",
style: "stop-color:" + colorScale2(maxChange)+ ";stop-opacity:1",
});
var svgGrad = gradient.append("rect") //Create the rectangle holding the gradient
.attr({
width: 300,
height: 30,
rx: 2,
ry: 2,
style: "fill:url(#grad1); stroke-width:1; stroke:rgb(60,60,60)" //Fill rectangle with the gradient created
});
gradient.append("text") //Append the text telling the min life
.attr({
y: 20,
x: 5,
fill: "black",
})
.text("Min: " + (minChange).toFixed(2));
gradient.append("text") //Append the text telling the max life
.attr({
y: 20,
x: 205,
fill: "black",
})
.text("Max: " + (maxChange).toFixed(2));
}//Create gradient
var createChoropleth = function(greatestYear, leastYear) {
//Find the min and max differences.
var choroplethDifMax = dataset[0][greatestYear + ""];
var choroplethDifMin = dataset[0][greatestYear + ""];
dataset.forEach(function(d){
if(!isNaN(d[greatestYear + ""]) && !isNaN(d[leastYear + ""]) && d[greatestYear + ""] > 0 && d[leastYear + ""] > 0)
{
var currentDif = (d[greatestYear + ""] - d[leastYear + ""])/(greatestYear - leastYear);
if(currentDif > choroplethDifMax){
choroplethDifMax = currentDif;
}
else if(currentDif < choroplethDifMin){
choroplethDifMin = currentDif;
}
}
});
createGradient(choroplethDifMin, choroplethDifMax);
//Color the choropleth
dataset.forEach(function(d){
var newColor = {};
if(!isNaN(d[greatestYear + ""]) && !isNaN(d[leastYear + ""]) && d[greatestYear + ""] > 0 && d[leastYear + ""] > 0){
var yearDif = (d[greatestYear + ""] - d[leastYear + ""])/(greatestYear - leastYear);
//Not quite sure why this works. Is this an object?
newColor[d["Country Code"]] = colorScale2(yearDif); //Puts a single item array into the newColor variable?
}
else{
newColor[d["Country Code"]] = "rgb(130, 130, 130)";
}
basic_choropleth.updateChoropleth(newColor); //update choropleth with the object?
});
}
createChoropleth(minDatasetYear, maxDatasetYear);
//Line chart year scaling
xScale = d3.scale.linear()
.domain([minDatasetYear, maxDatasetYear])
.range([padding, w - padding]);
//Create blank space
var canvas = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("class", "countryGraph1")
.attr("style", "margin: 0 auto;"); //Shift the line chart
//Function that runs when you click a country
var countryClick = function(countryIn, newCountryBoolean) {
var dataIndex;
if(newCountryBoolean == true) {
d3.selectAll(".countryGraph1").remove(); //If true is passed in, remove the graph (class countryGraph1)
}
//Set the country drop down
$('#dropDown').val(countryIn);
//Create a new canvas svg element, with class of countryGraph1
var canvas = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("class", "countryGraph1")
.attr("style", "margin: 0 auto;"); //Shift the line chart
//Kind of mudane way of finding which data index is currently selected (based on the country name)
dataset.forEach(function(d, i) {
if(d["Country Code"] == countryIn){
dataIndex = i;
}
if(dataIndex === -1) { //
canvas.append("text")
.attr("y", h/2)
.attr("x", w/2 - 130)
.text("Data Not Available")
.attr("fill", "black");
return;
}
});
//Find min value from the dataset
//NOTE: change initiammindatasetyear to mindataset year if you want y axis to dynamically scale
var minValue = 100;
for(var j = initialMinDatasetYear; j < initialMaxDatasetYear; j++) {
if(dataset[dataIndex][j + ""] > 0 && dataset[dataIndex][j + ""] < minValue)
{
minValue = dataset[dataIndex][j + ""]; //If smaller value than current, select the data item at the clicked index
}
}
//Set the yScale based on the datapoints
if( minValue < 100 && !isNaN(d3.max(d3.values(dataset[dataIndex]))) ) {
yScale = d3.scale.linear()
.domain([minValue - 1, d3.max(d3.values(dataset[dataIndex]))])
.range([h - padding, padding]); //Range is the size of the chart
}
else {
yScale = d3.scale.linear() //Default y scale if no datapoints, or ugly data
.domain([0, 100])
.range([h - padding, padding]);
}
//xAxis using year xScale
xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
//.ticks(5) //Creat less ticks if needed
.tickFormat(d3.format("d")); //decimal ticks (rounded)
//Append a g element containing xAxis
canvas.append("g")
.attr("class", "axis") //Assignign an axis class to the xAxis.
.attr("id", "xAxis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis); //Took our "g" group elements and put the xAxis on them. Note that we could put the xAxis code in.
//yAxis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left"); //IMPORTANT: left orientation for the left axis
//Append yAxis
canvas.append("g")
.attr("class", "axis")
.attr("id", "yAxis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
//Calculate the slope from the first and last years with data
var startYear; //Start and end if no value at 1960
var endYear;
var slope;
for(var j = minDatasetYear; j < maxDatasetYear; j++) { //Find a start year if no value in 1960
if(dataset[dataIndex][j + ""] > 0) {
startYear = j;
break;
}
}
for(var j = maxDatasetYear; j >= minDatasetYear; j--) { //Find end year if no value in 2011
if(dataset[dataIndex][j + ""] > 0) {
endYear = j;
break;
}
}
slope = calcSlope( dataset[dataIndex][startYear + ""], dataset[dataIndex][endYear + ""] ,startYear, endYear);
//This changes slope text (or color, if you want) if the slope is real or not
if (!isNaN(slope) && slope !== 0) {
canvas.append("text")
.attr("y", 20)
.attr("x", 20)
.text("Slope = " + slope.toFixed(2))
//.text(dataset[dataIndex]["Country Name"] + ", Slope = " + slope.toFixed(2))
.attr("fill", "black")
.attr("class", "slopeText");
}
else {
canvas.append("text")
.attr("fill", "black")
.attr("y", 20)
.attr("x", 20)
.text("Slope = N/A")
//.text(dataset[dataIndex]["Country Name"] + ", Slope = N/A")
.attr("fill", "black");
}
var entries = d3.entries(dataset[dataIndex]);
entries = entries.filter(function(element){
return(!isNaN(+element.key) && minDatasetYear <= +element.key && +element.key <= maxDatasetYear);
});
canvas.append("path")
.datum(entries)
.attr("class","line")
.attr("id","chartLine")
.attr("d", line);
} //countryClick()
var createPopup = function(textInput, tooltipClass, width, xLocation, yLocation) {
var mapSvg = d3.select(".svg-pan-zoom_viewport");
var fo = mapSvg.append("foreignObject")
.attr({
'x': xLocation,
'y': yLocation-15,
'width': width,
'class': "svg-tooltip " + tooltipClass,
});
var div = fo.append('xhtml:div')
.append('div')
.attr({
'class': 'tooltip',
});
div.append('p')
.html(textInput);
var foHeight = div[0][0].getBoundingClientRect().height;
fo.attr({
'height': foHeight
});
foHeight-=25;
mapSvg.insert('polygon', '.svg-tooltip')
.attr({
'points': "0,0 0," + foHeight + " " + width + "," + foHeight + " " + width + ",0 " + (width/2+10) + ",0 " + width/2 + "," + -25 + " " + (width/2-10) + ",0",
'height': foHeight + 20,
'width': width,
'fill': '#D8D8D8',
'opacity': 0.9,
'transform': 'translate(' + xLocation + ',' + yLocation + ')',
'class': tooltipClass
});
}
var removePopup = function(tooltipClass){
d3.selectAll(tooltipClass).remove();
}
var checkForPopups = function() {
// console.log(minDatasetYear + ", " + maxDatasetYear);
if(minDatasetYear > 1985 && maxDatasetYear < 1996) {
removePopup(".tooltip1");
createPopup("War in Rwanda", "tooltip1", 70, 782, 365);
}
else {
removePopup(".tooltip1");
}
}
}); //.csv
</script>
</body>