-
Notifications
You must be signed in to change notification settings - Fork 0
/
overview.js
565 lines (482 loc) · 18.8 KB
/
overview.js
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
/*
Base globe code from http://bl.ocks.org/mbostock/4183330
Legend code from https://github.com/jgoodall/d3-colorlegend
Globe manipulation from http://rveciana.github.io/geoexamples/?page=d3js/d3js_svgcanvas/rotatingSVG.html
Note: Anything beyond the clipAngle is assigned d="", which I believe should be a valid null value, but flags as an error. (http://stackoverflow.com/questions/17396650/d3-js-parsing-error-rotation-of-orthogonal-map-projection)
Tabs code from http://code-tricks.com/create-a-simple-html5-tabs-using-jquery/
Scrollpane from https://github.com/vitch/jScrollPane/blob/master/script/jquery.jscrollpane.min.js
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// COMMON
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var color, min, mean, max; //<-- common required at top
var mediaData = {}, world_data,//<-- map required at top
tip = d3.tip()
.attr('class', 'd3-tip none')
.offset([-10, 0])
.html(function(d) {
var v;
var myColor = 'white';
if (!d || !mediaData[d.properties.name] || isNaN(mediaData[d.properties.name].articles)) v = "(no data)";
else {
myColor = color(mediaData[d.properties.name].articles);
v = numberWithCommas(mediaData[d.properties.name].articles);
}
return "<strong>Country: </strong><span style='color:"+myColor+";'><em>"+d.properties.name+"</em></span><span style='color:white;'>, </span><strong>Indicator Value: </strong><span style='color:"+myColor+";'><em>"+v+"</em></span>";
});
var mediaBarData = [], isCountrySortDescending = true, isResultSortDescending = false;//<-- bar required at top
var maxWidth = 940,
maxHeight = 650,
width = maxWidth,
height = maxHeight-150;
var margin = {
top: 0,
right: 0,
bottom: 0,//legend is at the bottom outside svg.
left: 0
};
var myColors = colorbrewer.Greens[6].slice(1),
emptyColor = 'white',
colorScale = myColors;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MAP ONLY
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var lastColorClicked,
country_map;
var svgMap = d3.select("#overviewMap").append("svg").attr({
width: width+margin.left+margin.right,
height: height+margin.top+margin.bottom,
transform: "translate(" + margin.left + "," + margin.top + ")"
}),
// add water
water = svgMap.append("rect")
.attr("class", "water")
.attr({
width: '940px',
height: '500px'
}),
countries_map = svgMap.append("g").attr({
id: "countries_map",
width: width,
height: height
}),
pathMap = d3.geo.path().projection(d3.geo.mercator().translate([width / 2, height / 2]));
/**
* Multifunctional color method, will handle regular fill and fancy based on clicked color.
* @param dimOthers {boolean} if false, regular fill.
* @param colorToPass {String} if dimOthers is true, this color drives selector.
*/
function colorCountry(dimOthers,colorToPass){
if (dimOthers && colorToPass){
country_map
.attr("opacity", function(d) {
if (lastColorClicked && lastColorClicked === colorToPass) return 1;
else {
var co = color(0);
if (d && _.has(mediaData, d.properties.name)) {
var c = mediaData[d.properties.name].articles;
if (c && !isNaN(c) && c > 0) co = color(c);
}
// console.log("co: "+co+", colorToPass: "+colorToPass+", equal? "+(co === colorToPass));
if (co === colorToPass) return 1;
else return .3;
}
});
lastColorClicked = colorToPass;
} else lastColorClicked = undefined;
country_map.transition()
.duration(250)
.style("fill", function(d) {
if (d && _.has(mediaData, d.properties.name)) {
var c = mediaData[d.properties.name].articles;
if (c && !isNaN(c) && c > 0) return color(c);
} else return emptyColor;
});
}
/**
* RENDER MAP (AFTER ALL ELSE IS LOADED)
*/
function renderMap() {
colorCountry(false,null);
//Populate legend
$('#legend_map').empty();
colorlegend("#legend_map", color, "quantile", {title: "results by country", boxHeight: 15, boxWidth: 30, fill: false, linearBoxes: 5});
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// COUNTRY BAR CHART
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var defaultBarTextColor = '#636363',
lightBarTextColor = '#bdbdbd',
hoverColor = 'orangered';
var marginBar = {
top: 50,
bottom: 0,
left: 0,
right: 50
},
widthBar = maxWidth - marginBar.left - marginBar.right,
heightBar = maxHeight - marginBar.top - marginBar.bottom,
countryWidth = 250;
var xScale = d3.scale.pow().exponent(0.1).range([0, widthBar - countryWidth]),
yScale = d3.scale.ordinal().rangeRoundBands([0, heightBar], .8, 0);
/* Bar rendering vars */
var bar_height = 15,
bar_padding = 1,
x_pad = 5,
y_em = ".95em";
/* Sorting vars */
var groups = null,
bars = null;
var svgBar, gBar;
/**
* RENDER BAR CHART (AFTER ALL ELSE IS LOADED)
*/
function renderBarChart() {
isCountrySortDescending = true;
isResultSortDescending = false;
var nameData = _.pluck(mediaBarData, 'name');
xScale.domain([min, max]);
yScale.domain(nameData);
$('#country_bar_chart').empty();
svgBar = d3.select("#country_bar_chart").append("svg")
.attr("width", widthBar + marginBar.left + marginBar.right)
.attr("height", 3000);
gBar = svgBar.append("g")
.attr("transform", "translate("+marginBar.left+","+marginBar.top+")");
groups = gBar.append("g")
.selectAll("g")
.data(mediaBarData)
.enter()
.append("g")
.attr("id", function (d) {
return "bar_group_" + d.code;
})
.attr("transform", function (d) {
// console.log(d);
return "translate(" + countryWidth + ", " + yScale(d.name) + ")";
});
bars = groups.append("rect")
.attr("class", "bar_rect")
.attr("id", function (d) {
return "bar_rect_" + d.code;
})
.attr("width", function (d) {
return xScale(d.articles);
})
.attr("height", bar_height - bar_padding)
.style("fill", function (d) {
return color(d.articles);
})
.on('mouseover', function (d) {
fill(d, true);
})
.on('mouseout', function (d) {
fill(d, false);
});
/* ADD TEXT LABELS */
//Countries
groups.append("text")
.attr("class", "bar_text")
.attr("id", function (d) {
return "bar_text_country_" + d.code;
})
.attr("x", "-" + x_pad)
.attr("dy", y_em)
.style("fill", defaultBarTextColor)
.text(function (d) {
return d.name;
});
//Result Counts
groups.append("g").append("text")
.attr("class", "bar_text")
.attr("id", function (d) {
return "bar_text_result_" + d.code;
})
.attr("x", function (d) {
var n = xScale(d.articles) - x_pad;
if (n < 0) return 5;
else return n;
})
.attr("dy", y_em)
.style("fill", function (d) {
var c = color(d.articles);
if (c === myColors[4]) return lightBarTextColor;//need to contrast dark green.
else
return defaultBarTextColor;
})
.text(function (d) {
var n = xScale(d.articles) - x_pad;
if (n < 0) return "0";
else return numberWithCommas(d.articles);
});
reorder("result");
}
/**
* Fill
* @param {Object} d
* @param {boolean} isHover
*/
function fill(d,isHover){
var group = d3.select("#bar_group_"+ d.code);
if (group != null) {
if (isHover){
group.select('rect').style('fill', hoverColor);
group.select('text').style('fill', hoverColor);
}
else {
group.select('rect').style('fill', color(d.articles));
group.select('text').style('fill', defaultBarTextColor);
}
}
}
/**
* Trigger a sort based on Country or Rank
* @param {String} radioVal value of the radio
*/
function reorder(radioVal){
groups.sort(function(a, b) {
if (radioVal === "country"){
if (isCountrySortDescending){
return d3.ascending(a.name,b.name);
} else {
return d3.descending(a.name,b.name);
}
} else {
return internalNumberSort(
a,parseInt(a.articles),b,parseInt(b.articles),isResultSortDescending);
}
});
/* Toggle state on sorted input.value; reset sort status on non-sorted to trigger ascending next sort. */
if (radioVal === "country"){
console.log("... reorder for 'country', descending? "+isCountrySortDescending);
isCountrySortDescending = isCountrySortDescending ? false : true;
isResultSortDescending = false;//<-- Note: want to trigger descending sort by default.
} else {
console.log("... reordered for 'result', descending? "+isResultSortDescending);
isResultSortDescending = isResultSortDescending ? false : true;
isCountrySortDescending = true;
}
groups
.transition()
.duration(750)
.delay(function(d, i) { return i * 10; })
.attr("transform", function(d, i) {
//translate x,y does not change the x,y but move the element.
return "translate(" + countryWidth +", " + i*bar_height +")";
});
return;
}
/**
* Special sort considerations for numbers to sort alphabetically by "Country" when number values
* to compare are equal. This will ALWAYS sort ascending by Country when values for number are equal.
* @param {Array} a data for a
* @param {Number} _a compare with _b
* @param {Array} b data for b
* @param {Number} _b compared to _a
* @param {boolean} sortAscending if true, sort ascending; otherwise sort descending
* @return {int} -1 | 0 | 1
*/
function internalNumberSort(a,_a,b,_b,sortAscending){
// console.log("... comparing number '"+_a+"' to '"+_b+"'");
if (sortAscending){
if (!isNaN(_a) && !isNaN(_b) && _a == _b){
return d3.ascending(a.name,b.name);
} else {
return d3.ascending(_a,_b);
}
} else {
if (!isNaN(_a) && !isNaN(_b) && _a == _b){
return d3.ascending(a.name,b.name);
} else {
return d3.descending(_a,_b);
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CRISES COMPARED
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function renderCrisesCompared(){
var margin = {top: 1, right: 1, bottom: 6, left: 1},
width = 940 - margin.left - margin.right,
height = 550 - margin.top - margin.bottom;
var format = function(d) {
var f;
if (d === 0) f = "Rank > 10";
else f = "Rank: " + d;
return f;
},
color = d3.scale.category20();
var svg = d3.select("#countrySankeyVis").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.size([width, height]);
var path = sankey.link();
d3.json("/productiondata/compared_overview.json", function(data) {
sankey
.nodes(data.nodes)
.links(data.links)
.layout(32);
var link = svg.append("g").selectAll(".link")
.data(data.links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function(d) { return Math.max(0, d.dy); })
.sort(function(a, b) { return b.dy - a.dy; });
link.append("title")
.text(function(d) { return d.source.name + " → " + d.target.name + "\n" + format(d.rank); });
var node = svg.append("g").selectAll(".node")
.data(data.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() { this.parentNode.appendChild(this); })
.on("drag", dragmove));
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function(d) { return d.color = color(d.name); })
.style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
.append("title")
.text(function(d) { return d.name + "\n" + format(d.rank); });
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) { return d.name; })
.filter(function(d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
function dragmove(d) {
d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
sankey.relayout();
link.attr("d", path);
}
});
}
function loadedDataCallBack(error, world, media, crisisSummary) {
console.log("--- START ::: loadedDataCallback ---");
/* Crisis summary */
// make summary global for use in tab changes
summary = crisisSummary;
// update crisis info section
resetSummary(summary);
mediaData = {};
mediaBarData = [];
world_data = topojson.feature(world, world.objects.countries).features;
/* convert media data to json object */
media.forEach(function (d) {
// set country name as property value
var name = d.query_distinct.slice(d.query_distinct.indexOf("(") + 1, d.query_distinct.lastIndexOf(")")),
code = d.query_distinct.slice(0, d.query_distinct.indexOf("(") - 1),
articles = code === "CS" ? 1 : +d.raw_result_count; //serbian results are consistently odd in API
//Globe Data needs name to map directly to the world_data countries names !!!
mediaData[name] = {
// set country name, code, and number of articles written
name: name,
code: code,
articles: articles
};
//Bar Data needs an Array and needs " removed !!!
mediaBarData.push({
// set country name, code, and number of articles written
name: name.replaceAll('"', ''),
code: code,
articles: articles
});
});
console.log('mediaData: ', mediaData);
// quantile scale
var resultCountData = _.pluck(mediaData, 'articles');
min = d3.min(resultCountData),
mean = d3.sum(resultCountData) / resultCountData.length,
max = d3.max(resultCountData);
color = d3.scale.quantile()
.domain([min, mean, max])
.range(colorScale);
//Populate country for map
$('#countries_map').empty();
country_map = countries_map
.selectAll(".country")
.data(world_data);
country_map.enter()
.append('path')
.attr('class', 'country')
.attr('d', pathMap)
.on('mouseover', tip.show)
.on("mousemove", function () {
return tip
.style("top", (d3.event.pageY + 16) + "px")
.style("left", (d3.event.pageX + 16) + "px");
})
.on('mouseout', tip.hide)
.on('click',function(d){
console.log(d);
var rc = mediaData[d.properties.name].articles;
if (!isNaN(rc)){
var co = color(rc);
colorCountry(true,co);
}
});
country_map.call(tip);
// renderGlobe();
renderMap();
renderBarChart();
console.log("--- END ::: loadedDataCallback ---");
}
addClassNameListener("crisis_select", function(){
var crisis = window.crisis_select.value;
console.log("### QUEUE NEW CRISIS ("+crisis+") AFTER CLASS CHANGE ###");
queue()
.defer(d3.json, "productiondata/globe.json")//world
.defer(d3.csv, "/productiondata/"+crisis+"/google-country_stats.csv")//media
.defer(d3.csv, "/productiondata/"+crisis+"/summary.csv")//storypoints
.await(loadedDataCallBack);
});
/* add chart reorder */
d3.selectAll("input")
.on("click", function () {
reorder(this.value);
return;
});
$(document).ready(function() {
document.getElementById("tab_1_compared").className = "content-tab active";
addClassNameListener("tab_1_compared", function () {
var className = document.getElementById("tab_1_compared").className;
if (className === "content-tab active") {
console.log("... tab change to tab_1_compared.");
// change summary data
resetSummary(summary);
}
});
addClassNameListener("tab_2_map", function () {
var className = document.getElementById("tab_2_map").className;
if (className === "content-tab active") {
console.log("... tab change to tab_2_map.");
//Populate legend
$('#legend_map').empty();
colorlegend("#legend_map", color, "quantile", {title: "results by country", boxHeight: 15, boxWidth: 30, fill: false, linearBoxes: 5});
// change summary data
resetSummary(summary);
}
});
addClassNameListener("tab_3_bar", function () {
var className = document.getElementById("tab_3_bar").className;
if (className === "content-tab active") {
console.log("... tab change to tab_3_bar.");
// change summary data
resetSummary(summary);
}
});
//ALWAYS START WITH THIS
renderCrisesCompared();
} );