-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2340 lines (1804 loc) · 78.6 KB
/
script.js
File metadata and controls
2340 lines (1804 loc) · 78.6 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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function drawHeadingAreaWithButton() {
// I select the body of the HTML and append the heading area where the author information will stay
body = d3.select("body");
header = body.append("div").attr("id", "header");
footer = body.append("div").attr("id", "footer");
drawHeadingFooterArea(header, footer); // I draw the Heading area with this method
// Onclick method of the Button present in the heading area
buttonOnClick = function () {
if (document.getElementById('title') == null) {
drawHeadingFooterArea(header, footer);
showButton('minimize', buttonOnClick);
} else {
d3.select("#header").selectAll("#title").remove();
d3.select("#footer").selectAll("#author").remove();
showButton('maximize', buttonOnClick);
}
};
showButton('minimize', buttonOnClick); // Here I draw the button
}
function showButton(state, clickBehaviour) {
/*
This is the Button which is used to hide the heading area to get the user a little more space
real estate to work with the visualization and analysis.
*/
d3.select("#minimize_header").remove();
// I define the dimension of the button
var button_parameters = { height: "40", width: "40", padding: "5", stroke_width: "2" }
minimize_button = d3.select("#header").append("svg") // I select the header and append an svg for the button
.attr("id", "minimize_header") // Name of the button
.attrs({
"class": function () { // I will define the possible states of the button either minimized or maximized
if (state == 'minimize') {
return "minimize_header_maximized"
} else if (state == 'maximize') {
return "minimize_header_minimized"
}
},
"height": button_parameters.height,
"width": button_parameters.width
})
.on("mouseover", function () {
if (state == 'minimize') {
d3.select("#button_circle")
.attr("fill", "white");
d3.select("#button_text").selectAll("text")
.transition()
.duration(100)
.style("fill", "red");
} else if (state == 'maximize') {
d3.select("#button_circle")
.attr("fill", "grey");
d3.select("#button_text").selectAll("text")
.transition()
.duration(100)
.style("fill", "green");
}
})
.on("mouseout", function () { // This function in the attribute determines the behaviour or the button on mouse out
if (state == 'minimize') {
d3.select("#button_text").selectAll("text")
.transition()
.duration(500)
.style("fill", "#9ca19c");
} else if (state == 'maximize') {
d3.select("#button_text").selectAll("text")
.transition()
.duration(500)
.style("fill", "white");
}
})
.on("click", clickBehaviour); // On click the clickBehaviour will be loaded.
minimize_button.append("g") // Groups the svg elements together
.attr("id", "button_circle")
.append("circle")
.attrs({
"cx": button_parameters.height / 2,
"cy": button_parameters.width / 2,
"r": button_parameters.height / 2 - button_parameters.padding,
})
.attr("fill", function () {
if (state == 'minimize') {
return "white";
} else if (state == 'maximize') {
return "#c5c5c5";
}
});
minimize_button.append("g") // Group the svg elements for the minimize button
.attrs({
"id": "button_text",
"dominant-baseline": "middle", // The attributes id is button text and its set in the middle
})
.attr("transform", function () {
if (state == 'minimize') {
return `translate(${button_parameters.width / 2}, ${button_parameters.height / 2})`;
} else if (state == 'maximize') {
return `translate(${button_parameters.width / 2}, ${button_parameters.height / 2}) rotate(180)`;
}
})
.append("text")
.html("▲")
.style("fill", "#9ca19c");
}
function drawHeadingFooterArea(header, footer) {
/*
* This function draws the heading area with the respective information
*/
author = { name: "Sanchayan Bhunia", matricola: 4849650, e_mail: "s4849650@studenti.unige.it" };
title = header.append("div").attr("id", "title");
title.append("text").text("Migrant Stocks Data Visualization");
author_place = footer.append("div").attr("id", "author");
author_place.append("text").html(`<tspan id="author_name">${author.name} (${author.matricola})</tspan>\
<br> <tspan id="author_email"><strong>@:</strong> ${author.e_mail}</tspan>`);
}
function drawBodyArea() {
/*
This function is used to draw the body for the data section of the application
The body area will contain the map, ring chart and respective bar charts.
*/
graphs = d3.select("body").append("div").attr("id", "graphs");
// This is the top row for the graphs
top_row = graphs.append("div").attrs({
"id": "top_row",
"class": "double_grid"
});
// This is the bottom row for the graphs
bottom_row = graphs.append("div").attrs({
"id": "bottom_row",
"class": "double_grid"
});
// On the top row append the map and the stacked bar chart
top_row.append("div").attr("id", "map_view");
top_row.append("div").attr("id", "stacked_bar_chart");
// On the bottom row append the bar_chart and the ring chart
bottom_row.append("div").attr("id", "bar_chart");
bottom_row.append("div").attr("id", "ring_chart");
// For every selection get the the data, country, year gender and interval
var selection = [{
"data_selected": null,
"country_selected": null,
"year_selected": null,
"gender_selected": null,
"intervals": []
}];
// Call the loadData function
loadData(selection);
}
function loadData(selection) {
/*
This function loads the data for the application, the data is found in different csvs, so they have all been put
in a queue.
*/
// This is the queue for the csv data files
d3.queue()
.defer(d3.csv, "data/migrantion_data/origin_destination/UN_MigrantStockByOriginAndDestination.csv")
.defer(d3.csv, "data/migrantion_data/origin_destination/UN_MigrantStockByOriginAndDestination_Male.csv")
.defer(d3.csv, "data/migrantion_data/origin_destination/UN_MigrantStockByOriginAndDestination_Female.csv")
.defer(d3.csv, "data/migrantion_data/external_data/countries_iso.csv")
.defer(d3.json, "data/map/world.geojson")
.defer(d3.csv, "data/migrantion_data/age_data/Immigrants_All.csv")
.defer(d3.csv, "data/migrantion_data/age_data/Immigrants_Male.csv")
.defer(d3.csv, "data/migrantion_data/age_data/Immigrants_Female.csv")
.await(function (error, file1, file2, file3, file4, file5, file6, file7, file8) {
if (error) {
console.error('Something went wrong: ' + error);
} else {
data_files = {
"migration": {
"all": file1,
"male": file2,
"female": file3,
},
"iso": file4,
"geojson": file5,
"migrant_age": {
"all": file6,
"male": file7,
"female": file8,
}
}
// Load map data
mapContent(data_files, selection);
}
});
}
function mapContent(dataObject, selection) {
/*
This function loads the map with the respective dimensions and projection
*/
// Dimenstions
var width = 850;
var height = 320;
var map_scale = 125;
var map_offset = { "height": -30, "width": 20 }
// Tool tip
var tip = d3
.tip()
.attr("class", "d3-tip")
.attr("id", "map-tip")
.direction(function () {
if (this.getBBox().y <= 26) {
return 's';
} else {
return 'n';
}
})
.offset(function () {
if (this.id === "USA") {
return [50, 50];
} else if (this.id === "RUS") {
return [-10, 200];
} else if (this.getBBox().y <= 26) {
return [5, 50];
} else {
return [-5, 0];
}
})
.html(function () {
if (this.className.baseVal == "countries" || this.className.baseVal == "selectedCountry") {
text = `${this.__data__.properties.name}`;
} else if (this.className.baseVal == "destination") {
text = `<span style="color: ${this.__data__.colour}">\
<pre>${this.__data__.properties.name} ▸ ${this.__data__.mass}</pre></span>`;
} else if (this.className.baseVal == "lagend_selected_country") {
text = `<span style="color: #FBC02D">\
<pre>${this.__data__.properties.name} ▸ ${this.__data__.mass}</pre></span>`;
}
return `<span class="tip_text">${text}<span>`
});
// Select the map_view element from the canvas and attact respective svgs.
var svg = d3
.select("#map_view")
.append("svg")
.attrs({
"width": width,
"height": height,
"id": "map"
})
.call(tip);
// Map and projection
var projection = d3
.geoEquirectangular()
.scale(map_scale)
.translate([width / 2 - map_offset.width, height / 2 - map_offset.height]);
// A path generator
var path = d3.geoPath().projection(projection);
let mouseClick = function (data) {
d3.selectAll(".selectedCountry, .destination").attr("class", "countries");
d3.select(this).attr("class", "selectedCountry");
selection[selection.length - 1].country_selected = data.properties.name;
if (selection[selection.length - 1].data_selected !== null) {
stackedBarContent(selection, dataObject);
}
};
// Group the svg elements
svg.append("g")
.attr("id", "world_map")
.selectAll("path")
.data(dataObject.geojson.features)
.enter()
.append("path")
.attrs({
"class": "countries",
"id": function (d) { return d.id },
"d": path
})
.on("mouseover.tip", tip.show)
.on("mouseout.tip", tip.hide)
.on("click", mouseClick);
d3.select("#world_map").datum({ "projection": projection });
dataSelectionLagend(selection, dataObject);
}
function dataSelectionLagend(selection, dataObject) {
/*
This function selects the data for either Emigration of Immigration.
*/
selection.slice().reverse().every(function (element) {
previous_data_selection = element.data_selected;
if (previous_data_selection !== null) return false
else return true
});
// Create buttons for the selection
button_radius = 6;
line_length = 5;
group_spacing = 15;
// These are the possible data types either Immigration of emigration
types_of_data = ["immigration", "emigration"];
world_map = d3.select("#map");
// Create a legend for the data on the map.
dataLagend = world_map.append("g").attrs({
"id": "data_selection_lagend",
"transform": `translate(${world_map.node().getBBox().width - 50}, ${7.5})`,
"style": "cursor: pointer"
});
oneGroup = dataLagend.selectAll("g")
.data(types_of_data).enter().append("g").attrs({
"id": function (d) { return d },
"fill": function (d, i) {
if (d == "emigration") {
return "#cf5f65"
} else if (d == "immigration") {
return "#8080FC"
}
},
"stroke": function (d, i) {
if (d == "emigration") {
return "#cf5f65"
} else if (d == "immigration") {
return "#8080FC"
}
},
"transform": function (d, i) {
if (i % 2 == 0) {
return `translate(${-2 * button_radius}, ${0})`
} else {
return `translate(${2 * button_radius}, ${0})`
}
},
"style": "cursor: pointer"
});
oneGroup.append("circle").attrs({
"cx": 0,
"cy": 0,
"r": button_radius,
"stroke-width": 1.5,
"fill-opacity": "0"
});
oneGroup.append("line").attrs({
"x1": function (d, i) { if (i % 2 == 0) { return -button_radius } else { return button_radius } },
"y1": 0,
"x2": function (d, i) { if (i % 2 == 0) { return -(button_radius + line_length) } else { return button_radius + line_length } },
"y2": 0,
"stroke-width": 1.5
});
oneGroup.append("text").attrs({
"dominant-baseline": "middle",
"style": function (d, i) { if (i % 2 == 0) { return "text-anchor: end" } else { return "text-anchor: start" } },
"class": "dataLagendText",
"x": function (d, i) { if (i % 2 == 0) { return -(button_radius + line_length + 5) } else { return button_radius + line_length + 5 } },
"y": 0,
"stroke": "none"
}).text(function (d) { return d.charAt(0).toUpperCase() + d.slice(1) });
oneGroup.on("mouseover", function () { d3.select(this).attr("opacity", "50%") });
oneGroup.on("mouseout", function () { d3.select(this).attr("opacity", "100%") });
oneGroup.on("click", function (data, i) {
selection[selection.length - 1].data_selected = data;
makeSelection(data);
if (selection[selection.length - 1].country_selected !== null) {
stackedBarContent(selection, dataObject);
}
});
// The selection happens in this place.
function makeSelection(data_to_select) {
d3.select("#data_selection_lagend").selectAll("#selection_circle").remove();
d3.select(`#${data_to_select}`).append("circle").attrs({
"id": "selection_circle",
"cx": 0,
"r": button_radius - 2.5
}).attr("cy", function () {
button_dimensions = d3.select(`#${data_to_select}`).select("circle").node().getBBox();
return button_dimensions.y + button_dimensions.height / 2;
});
};
}
function stackedBarContent(selection, data) {
/*
This function gets the stacked bar content to be used for the stacked bar.
*/
var selected_data_type = selection[selection.length - 1].data_selected;
var selected_country_on_map = selection[selection.length - 1].country_selected;
var migrant = data.migration;
var years = new Set();
// This will select all the migrants both male or female.
migrant.all.forEach(function (row) {
if (Number(row["Year"]) != 0) {
years.add(Number(row["Year"]));
}
});
// This will select only male migrants
migrant.male.forEach(function (row) {
if (Number(row["Year"]) != 0) {
years.add(Number(row["Year"]));
}
});
// This will select female migrants.
migrant.female.forEach(function (row) {
if (Number(row["Year"]) != 0) {
years.add(Number(row["Year"]));
}
});
male_female_migration_list = [];
// If use selects emigration then the world map will show only data for emigration
if (selected_data_type == "immigration") {
years.forEach(function (year) {
var male_number = null;
var female_number = null;
migrant.male.forEach(function (d) {
if (Number(d.Year) == year) {
for (const [key, value] of Object.entries(d)) {
if (key == selected_country_on_map) {
if (d.Destination == "WORLD") {
male_number = Number(value);
}
}
}
}
});
migrant.female.forEach(function (d) {
if (Number(d.Year) == year) {
for (const [key, value] of Object.entries(d)) {
if (key == selected_country_on_map) {
if (d.Destination == "WORLD") {
female_number = Number(value);
}
}
}
}
});
male_female_migration_list.push({ "year": year, "male": male_number, "female": female_number });
});
// If the use select immigration data then the map will show only that selection.
} else if (selected_data_type == "emigration") {
years.forEach(function (year) {
var male_number = null;
var female_number = null;
migrant.male.forEach(function (d) {
if (Number(d.Year) == year && d.Destination == selected_country_on_map) {
male_number = Number(d.Total);
}
});
migrant.female.forEach(function (d) {
if (Number(d.Year) == year && d.Destination == selected_country_on_map) {
female_number = Number(d.Total);
}
});
male_female_migration_list.push({ "year": year, "male": male_number, "female": female_number });
});
}
// With the repective data selection call the stackedBar function using the parameters shown.
showStackedBar(selection, male_female_migration_list, data);
}
function showStackedBar(selection, stackedBarData, all_data_files) {
/*
This function shows the stacked bar with the respective data.
*/
d3.select("#no_data").remove()
d3.selectAll(".connector_string").remove();
d3.selectAll(".d3-tip-stacked-bar").remove();
selected_country = selection[selection.length - 1].country_selected;
selection.slice().reverse().every(function (element) {
previous_year_selection = element.year_selected;
if (previous_year_selection !== null) return false
else return true
});
// Make the selection on the canvas.
d3.select("#stacked_bar_chart").selectAll("svg").remove();
var margin = { top: 10, right: 80, bottom: 60, left: 80 },
width = 640 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var heading_height = 15;
var stacked_bar_chart = d3.select("#stacked_bar_chart");
// Append the heading to the bar chart.
var heading = stacked_bar_chart.append("svg").attrs({
"id": "stacked_bar_title",
"height": heading_height,
"width": width + margin.left + margin.right,
"transform": `translate(${0}, ${0})`
});
heading.append("text").attrs({
"text-anchor": "middle",
"dominant-baseline": "middle",
"x": "50%",
"y": "50%"
}).html(function () {
if (selection[selection.length - 1].data_selected == "emigration") {
return `<tspan style="fill: #cf5f65">Emigration</tspan> Data of <tspan class="selectedCountryName">${selected_country}</tspan>`
} else if (selection[selection.length - 1].data_selected == "immigration") {
return `<tspan style="fill: #8080FC">Immigration</tspan> Data of <tspan class="selectedCountryName">${selected_country}</tspan>`
}
}
);
// Append svg elements
graph = stacked_bar_chart.append("svg").attrs({
"id": "stacked_bar_svg",
"width": width + margin.left + margin.right,
"height": height + margin.top + margin.bottom
})
// Group the svg elements
.append("g").attrs({
"id": "stacked_bar_graph",
"transform": `translate(${margin.left}, ${margin.top})`,
"style": "cursor: pointer"
});
var bar_padding = 0.6;
var groups = stackedBarData.map(function (d) {
return d.year;
});
var subgroups = Object.keys(stackedBarData[0]).slice(1);
var colourScale = d3.scaleOrdinal().domain([...subgroups, "all"]).range(["#4593C7", "#7970B3", "#41AB5D"]);
var stackedData = d3.stack().keys(subgroups)(stackedBarData);
selection = selectGenderOnLagend(graph, subgroups, colourScale, stackedBarData, selection, all_data_files);
// Make tool tip
var stacked_bar_tip = d3
.tip()
.attr("class", "d3-tip-stacked-bar")
.attr("id", "stacked_bar_tip")
.offset([-10, 0])
.html(function (d) {
var gender_selected = selection[selection.length - 1].gender_selected;
if (gender_selected == "all" || gender_selected == null) {
total = d.data.male + d.data.female;
male_percent = d.data.male / total * 100;
female_precent = d.data.female / total * 100;
var text = `Female ♀ ▸ <span style= 'color: ${colourScale("female")}'>${d.data.female} (${female_precent.toFixed(2)}%)</span><br>
Male ♂ ▸ <span style= 'color: ${colourScale("male")}'>${d.data.male} (${male_percent.toFixed(2)}%)</span><br>
<hr>
<strong>Total ⚥ ▸</strong> ${total}`;
} else if (gender_selected == "female") {
var text = `Female ♀ ▸ <span style= 'color: ${colourScale("female")}'>${d.female}</span>`;
} else if (gender_selected == "male") {
var text = `Male ♂ ▸ <span style= 'color: ${colourScale("male")}'>${d.male}`;
}
return `<tspan class="tip_text">${text}</tspan>`;
});
var x = d3.scaleBand() // Scales the chart since the data is categorical.
.domain(groups)
.range([0, width])
.padding(bar_padding);
graph.append("g")
.attr("transform", `translate(${0}, ${height})`)
.call(d3.axisBottom(x).tickSizeOuter(0))
.selectAll("text")
.attr("class", "xyStackedBarAxis").call(stacked_bar_tip);
if (selection[selection.length - 1].gender_selected === "male") {
drawBarForOneGender("male");
} else if (selection[selection.length - 1].gender_selected === "female") {
drawBarForOneGender("female");
} else {
var y = d3.scaleLinear()
.domain([0, d3.max(stackedBarData, function (d) {
return d.male + d.female;
})]).nice()
.range([height, 0])
graph.append("g")
.call(d3.axisLeft(y).tickSizeOuter(0))
.selectAll("text")
.attr("class", "xyStackedBarAxis");
var bar_area = graph.append("g").attrs({
"id": "bar_area",
"transform": `translate(${0}, ${0})`
});
bar_area.selectAll("g").data(d3.stack().key);
bar_area.append("g")
.selectAll("g")
.data(stackedData)
.enter().append("g")
.attr("fill", function (d) { return colourScale(d.key); })
.selectAll("rect")
.data(function (d) { return d; })
.enter().append("rect")
.attrs({
"id": function (d) { return `year${d.data.year}` },
"x": function (d) { return x(d.data.year); },
"y": function (d) { return y(0); },
"height": function (d) { return y(d[0]) - y(d[0]); },
"width": x.bandwidth()
})
.on("click", function (d) { // Behaviour on click
d3.selectAll(".stackedBarSelected").attr("class", null);
d3.selectAll(`#year${d.data.year}`).attr("class", "stackedBarSelected");
selection[selection.length - 1].year_selected = d.data.year;
selectedMigrationBarAndAgeDoughnut(selection, all_data_files, colourScale);
})
.on("mouseover", function (d) { // Behaviour on mouseover
stacked_bar_tip.show(d);
d3.selectAll(`#year${d.data.year}`).attr("opacity", "100%").transition().duration(200).attr("opacity", "60%");
})
.on("mouseout", function (d) { // Behaviour on mouseout
stacked_bar_tip.hide(d);
d3.selectAll(`#year${d.data.year}`).attr("opacity", "100%").transition().duration(200).attr("opacity", "100%");
})
.transition().duration(200)
.attrs({
"id": function (d) { return `year${d.data.year}` },
"x": function (d) { return x(d.data.year); },
"y": function (d) { return y(d[1]); },
"height": function (d) { return y(d[0]) - y(d[1]); },
"width": x.bandwidth()
})
.delay(function (d, i) { return (i * 50) });
}
stacked_bar_chart.on("mouseover", function () {
d3.select("#dummy_bar_group").remove()
});
stacked_bar_chart.on("mouseout", function () { drawDummies() });
if (previous_year_selection !== null) {
d3.selectAll(`#year${previous_year_selection}`).attr("class", "stackedBarSelected");
drawDummies();
}
selectedMigrationBarAndAgeDoughnut(selection, all_data_files, colourScale);
year_index = 0;
selection[selection.length - 1].intervals.forEach((interval) => clearInterval(interval));
playPauseButton();
function drawBarForOneGender(gender) {
/*
Based on the selected gender draw the bars based on that selection
*/
y = d3.scaleLinear() // Use the linear scale in this case.
.domain([0, d3.max(stackedBarData, function (d) {
return d[gender];
})]).nice()
.range([height, 0])
graph.append("g")
.call(d3.axisLeft(y).tickSizeOuter(0))
.selectAll("text")
.attr("class", "xyStackedBarAxis");
var bar_area = graph.append("g").attr("transform", `translate(${0}, ${0})`).call(stacked_bar_tip);
bar_area.selectAll("rect")
.data(stackedBarData)
.enter()
.append("rect").attrs({
"id": function (d) { return `year${d.year}` },
"class": "male_female_bar",
"x": function (d) { return x(d.year); },
"y": function (d) { return y(0); },
"fill": colourScale(gender),
"height": function (d) { return height - y(0); },
"width": x.bandwidth()
}).on("click", function (d) { // Mouse behaviour on click
d3.selectAll(".stackedBarSelected").attr("class", null);
d3.select(this).attr("class", "stackedBarSelected");
selection[selection.length - 1].year_selected = d.year;
selectedMigrationBarAndAgeDoughnut(selection, all_data_files, colourScale)
}).on("mouseover", function (d) { // Mouse behavior on mouse over
stacked_bar_tip.show(d, selection);
})
.on("mouseout", function (d) { // Mouse behaviour on mouse out
stacked_bar_tip.hide();
})
.transition().duration(200).attrs({
"x": function (d) { return x(d.year); },
"y": function (d) { return y(d[gender]); },
"fill": colourScale(gender),
"height": function (d) { return height - y(d[gender]); },
"width": x.bandwidth()
})
.delay(function (d, i) { return (i * 50) });
}
function drawDummies() {
if (selection[selection.length - 1].gender_selected == "all" || selection[selection.length - 1].gender_selected == null) {
y = d3.scaleLinear()
.domain([0, d3.max(stackedBarData, function (d) {
return d.male + d.female;
})]).nice()
.range([height, 0])
var bar_area = graph.append("g").attrs({
"id": "dummy_bar_group",
"transform": `translate(${0}, ${0})`
});
bar_area.selectAll("rect").data(stackedBarData)
.enter()
.append("rect")
.attrs({
"id": function (d) {
return `year${d.year}`
},
"x": function (d) { return x(d.year); },
"y": function (d) { return y(0) },
"fill": "#41AB5D",
"height": function (d) { return height - y(0); },
"width": x.bandwidth()
}).transition().duration(1000).attrs({
"y": function (d) { return y(d.male + d.female) },
"height": function (d) { return height - y(d.male + d.female); }
}).delay(function (d, i) { return 3000 + (i * 100) });
stackedBarData.forEach((bar) => {
if (d3.select("#bar_area").selectAll(`#year${bar.year}`).attr('class') == "stackedBarSelected") {
d3.select("#dummy_bar_group").select(`#year${bar.year}`).attr("class", "stackedBarSelected");
};
});
}
}
function playPauseButton(state) {
/*
This function plays through the respective years and displays the data on the barch chart for a a particluar
country.
*/
// Player respective variables.
var frame_lag = 1800;
var year_index = 0;
var loop = 0;
var loops = 3;
if (state == null) {
state = ["play"];
}
// Remove all elements for the button element
d3.select("#play_pause_button").remove();
svg = d3.select("#stacked_bar_svg");
var buttonStyles = { "x": 300, "y": 280, "radius": 15 };
// Group svg elements
button = svg.append("g").attrs({
"id": "play_pause_button",
"transform": `translate(${buttonStyles.x}, ${buttonStyles.y})`,
"style": "cursor: pointer"
});
button.attr("class", function () {
if (state[0] == "play") {
return "play_button"
} else {
return "pause_button"
}
});
button.data(state);
// The button is circular
button.append("circle").attrs({
"cx": 0,
"cy": 0,
"r": buttonStyles.radius,
"fill": function (d) { if (d == "play") { return "green" } else if (d == "pause") { return "#C70D39" } }
});
button.append("text")
.attrs({
"x": function (d) { if (d == "play") { return 1 } else if (d == "pause") { return 0 } },
"y": 1,
"text-anchor": "middle",
"dominant-baseline": "middle",
"style": "user-select: none",
"fill": "#F1F1F1"
})
.html(function (d) { if (d == "play") { return "▶" } else if (d == "pause") { return "❚❚" } });
// Pause button behavior on click
d3.select(".pause_button").on("click", function () {
selection[selection.length - 1].intervals.forEach(interval => {
clearInterval(interval);
});
playPauseButton(["play"]);
});
// Play button behavior
d3.select(".play_button").on("click", function () {
playPauseButton(["pause"]);
selected_bar = d3.selectAll(".stackedBarSelected");
if (selected_bar._groups[0][0] !== undefined) {
selected_year = Number(selected_bar.attr("id").replace(/[^0-9]/g, ""));
year_index = groups.indexOf(selected_year) + 1;
}
// the epoch function in terms of intervals
interval = setInterval(function () {
if (d3.select(".pause_button")._groups[0][0] !== null && year_index < groups.length) {
d3.selectAll(".stackedBarSelected").attr("class", null);
d3.selectAll(`#year${groups[year_index]}`).attr("class", "stackedBarSelected");
selection[selection.length - 1].year_selected = groups[year_index];
selectedMigrationBarAndAgeDoughnut(selection, all_data_files, colourScale);
year_index++;
if (year_index == groups.length && loop < loops) {
year_index = 0;
loop++;
// Exactly loops desired number of times if the play button is kept presses
} else if (loop == loops) {
selection[selection.length - 1].intervals.forEach((interval) => clearInterval(interval));
playPauseButton(["play"])
}
}
}, frame_lag);
selection[selection.length - 1].intervals.push(interval);
})
}
}
function selectGenderOnLagend(stacked_bar_chart, subgroups, colourscale, stackedBarData, selection, all_data_files) {
/*
This function shows the data based on gender on the bar charts for every particular country.
*/
button_radius = 6;
line_length = 5;
group_spacing = 15;
selection.slice().reverse().every(function (element) {
previous_gender_selection = element.gender_selected;
if (previous_gender_selection !== null) return false
else return true
});
gender_lagend = stacked_bar_chart.append("g").attrs({
"id": "gender_lagend",