-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1068 lines (892 loc) · 33.5 KB
/
index.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
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
<!doctype html>
<html>
<head>
<title>World Population, Growth, and Demographic Changes Throughout Time (1950 to 2021)</title>
<meta name="description" content="Answering the qustion: What is the world population demographic and its (growth/decline) trend throughout time?">
<meta name="keywords" content="World population demographic and trend">
<style>
html
{
margin: 0px; padding: 0px; height: 100%; overflow: hidden
}
body {
margin: 0px;
padding: 0px;
/* background-color: rgb(243, 237, 237); */
}
.center{
margin: auto;
/* border: 3px solid blue; */
padding: 10px;
text-align: center;
vertical-align: center;
align-content: center;
}
.title{
background-color: bisque;
color: brown;
border: 2px solid rgb(207, 201, 201);
padding:0px ;
margin:0px ;
height:70px;
text-align: center;
vertical-align: center;
align-content: center;
}
.wholeBody{
}
.container {
/* background-color:#2E4272; */
display:flex;
text-align: center;
vertical-align: center;
align-content: center;
margin-top: 2.5%;
width: 100%;
height:100%;
}
.fixed {
/* background-color:#4F628E; */
width: 60%;
}
.flex-left {
/* background-color:#7887AB; */
flex-grow: 1;
}
.box {
display: flex;
flex-direction: column;
align-items: flex-start;
/* background-color: brown; */
}
.allContent {
margin: auto;
/* border: 3px solid black; */
padding:0px ;
margin:0px ;
height:100%;
}
#D3container{
margin: auto;
/* border: 3px solid green; */
padding: 10px;
flex-direction: row;
width: 100%;
}
.narrative{
width:4%;
/* background-color:red; */
}
#backButton{
position: relative;
left: 10px;
top:300px;
height:75px;
width:100px;
background-color:grey;
border: black;
}
#nextButton{
position: relative;
left: 0px;
margin-left:-30px;
top:300px;
height:75px;
width:100px;
background-color:yellow;
border: dashed red;
}
#yearDropDown{
display:none
}
#year{
display:none
}
.rightGutter{
width:5%;
/* background-color:yellow; */
}
.rightNarrative{
width:30%;
padding:10 px;
}
.rightMargin{
width:1%;
/* background-color:yellow; */
}
.densityMapsvg{
/* outline: 2px solid grey;
outline-offset: -1px; */
}
.falseFooter{
/* margin: 0 auto;
height:300px;
width:100%;
display:flex;
text-align: center;
vertical-align: center;
align-content: center;
align-items: center;
justify-content: center; */
}
.timelineSliderSVGID{
margin: 0 auto;
display:flex;
text-align: center;
vertical-align: center;
align-content: center;
align-items: center;
justify-content: center;
height:100px;
}
.content{
text-align: justify;
text-justify: inter-word;
padding:25px 50px 75px 100px;
}
#content0{
display: inline;
}
#content1{
display: none;
}
#content2{
display: none;
}
#content3{
display: none;
}
#content4{
display:none;
}
.offset{
position: relative;
right: 10px;
width: 100px;
}
</style>
</head>
<body class="wholeBody">
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-annotation/2.5.1/d3-annotation.min.js"></script>
<script async>
// Parts of the codes are inspired and referred from: https://d3-graph-gallery.com/scatter.html
// Scales and legend inspired and referred from: https://observablehq.com/@d3/continuous-scales
var data;
var dataPerYear;
var region;
var yearTest=['1950'];//default value of year
var yearMartini=['1950','1965','1981','2021']
//starting, boomer+GenX, Millenials+GenZ, Gen Alpha and beyond? --> probably continue declining
//https://www.beresfordresearch.com/age-range-by-generation/
// var yearMartini=['1950','1975','2000','2021']
async function dataQuery() {
console.log('data querying')
data=await d3.csv('./joined_world_population_data.csv').then(()=>{console.log('async call for data completed')}).then((data)=>{return new Promise((resolve,reject)=>{
resolve(data);
})})
}
// Function to populate the dropdown with years
//declaration
var yearsAll=[];
var firstSceneBool=true;
var circleRadiusScale;
var color;
var svg;
var svgLegend;
var xAxisDomain;
var xAxisRange;
var yAxisDomain;
var yAxisRange;
var xAxis;
var yAxis;
var globalTop3Centroid=[];
var globalMedian3Centroid=[];
var annotationVariables;
var globalCircle;
var densityColorMapdomain=[0,0.003];
var slideTimeScale;
var timelineSliderAxis;
var timelineSliderSVG;
var currentPurpleBall;
var firstLoad=true;
var timelineSliderGroup;
var currentYear='1950'
// var currentYear = String(getElementById('year').value);
if (currentYear==null || currentYear==undefined) {
currentYear='1950'
}
for (let i = 1950; i < 2022; i++) {
yearsAll.push(i.toString());
}
var martiniDone=false;
//global scale
// Prepare a color palette for density map
// var colorDensityMap = d3.scaleLinear()
// .domain([0,0.003]) // Points per square pixel.
// .range(["#FFFFFF","#CB4335"])
var colorDensityMap = d3.scaleLinear()
.domain([0,0.003]) // Points per square pixel.
.range(["yellow","red"])
//console.log(querying data)
regionDistinct=['East Asia & Pacific', 'Europe & Central Asia', 'Latin America & Caribbean', 'Middle East & North Africa', 'North America', 'South Asia', 'Sub-Saharan Africa']
async function dataRequestandInit(year)
{
console.log('data init running, waiting for data HTTP request')
data=await d3.csv('./joined_world_population_data.csv')
dataPerYear=d3.group(data,d=>d.Year)
console.log('query done')
// dataPerYear=d3.group(data,d=>d.Year);
console.log('data init running, waiting for data HTTP request')
//scales
//circle scale to indicate relative size of population
circleRadiusScale = d3.scaleSqrt()
.domain([0,d3.max(data,function(d) { return d['Total Population, as of 1 July (thousands)']; })])
.range([0,4])
//color scale to separate by regions
color = d3.scaleOrdinal()
.domain([...Array(7).keys()])
.range(d3.schemeCategory10)
// Reserve the SVG space
//color scale for density:
// rgb(255, 255, 255)
// rgb(242, 208, 205)
// rgb(229, 161, 154)
// rgb(216, 114, 104)
// rgb(203, 67, 53)
//main body
await mainRendering(year);
firstLoad=false;
}
//init
dataRequestandInit(currentYear);
//annotation
var type = d3.annotationCalloutCircle
//layout
var width = 600;
var height = 600;
var marginTop = 30;
var marginRight = 6;
var marginBottom = 55;
var marginLeft = 60;
var axisSyncDomain=60;
//legend layoutfyear
var legendWidth = 200;
var legendHeight = height + marginTop + marginBottom
var legendMarginLeft=20;
var legendMarginRight=20;
var colorDensityMapLegendWidth= 200;
var colorDensityMapLegendHeight= 200;
var timeSliderWidth=1200;
//main function and other functions
async function mainRendering(year)
{
console.log("first load is:",firstLoad)
if (firstLoad==false){
tempArrayCurrentyear=[];
tempArrayCurrentyear.push(parseInt(year))
// currentPurpleBall.data(tempArrayCurrentyear).enter().append('circle')
// .attr('x',(d,i)=>{return slideTimeScale(parseInt(d))})
// .attr("transform", `translate(${0}, ${-8})`)
// .attr('r', 10)
// .attr('fill', 'purple')
// .attr("style", "dominant-baseline: hanging; text-anchor: middle; font-weight: 900;").attr("class", "dynamicComponent").attr("id", "purpleBall")
// .raise();
await d3.selectAll("#purpleBall").remove();
await d3.selectAll(".dynamicComponent").remove();
// await d3.selectAll("#dynamicComponent").remove();
console.log('current year is', year);
firstSceneBool==false;
}
if (firstLoad==true){
//required init
//create svg component
svg = d3.select("#D3MainContent")
.append("svg")
.attr("class", "svgD3MainContent")
.attr("width", width + marginLeft + marginRight) //give ad hoc 100 for slider
.attr("height", height + marginTop + marginBottom)
.append("g")
.attr("transform", `translate(${marginLeft}, ${marginTop})`)
globalCircle = svg.append('circle').attr("id","animationPath")
.attr('fill', 'maroon')
.attr('r', 10)
.attr('style','position: relative; z-index: 99;')
.raise()
timelineSliderSVG= d3.select("#falseFooter")
.append("svg")
.attr('width', timeSliderWidth)
.attr('height', 300)
.attr("transform", `translate(${0}, ${0})`)
//axis setup
// var xAxisDomain = [0, d3.max(data,function(d) { return +d['Crude Birth Rate (births per 1,000 population)']; })];
xAxisDomain = [0, axisSyncDomain];
var xAxisRange=[0,width];
// var yAxisDomain=[0, d3.max(data,function(d) { return +d['Crude Death Rate (deaths per 1,000 population)']; })];
yAxisDomain=[0, axisSyncDomain];
yAxisRange=[height,0];
//create axis
xAxis=d3.scaleLinear().domain(xAxisDomain).range(xAxisRange);
svg.append("g")
.attr("class", "xAxis")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(xAxis));
yAxis=d3.scaleLinear().domain(yAxisDomain).range(yAxisRange);
svg.append("g")
.call(d3.axisLeft(yAxis));
// Include X axis title:
svg.append("text")
.attr("text-anchor", "end")
.attr("x", width)
.attr("y", height + marginTop + 20)
.text('Crude Death Rate (deaths per 1,000 population)');
// Include Y axis title:
svg.append("text")
.attr("text-anchor", "end")
.attr("transform", "rotate(-90)")
.attr("y", -marginLeft+20)
.attr("x", -marginTop)
.text('Crude Birth Rate (births per 1,000 population)')
// Time scale
slideTimeScale=d3.scaleLinear().domain([1950,2021]).range([0,timeSliderWidth-100]);//give margin for the actual svg
//create the legend for circles
var circleLegendValues=[0,500000,1000000,1425862]
svgLegend = d3.select("#D3MainContent")
.append("svg")
.attr("class", "svgLegend")
.attr("width", legendWidth)
.attr("height", height + marginTop + marginBottom)
.append("g")
.attr("transform", `translate(0,0)`)
var circleLegend = svgLegend.append("g")
.attr("class", "circleLegend")
.selectAll('circle')
.data(circleLegendValues)
.enter()
.append("g")
.append("circle")
.attr("cx", 0)
.attr("cy", (d) => {return (legendHeight - marginBottom - circleRadiusScale(d))})
.attr("r", (d) => {return circleRadiusScale(d)})
.attr("stroke", "black")
.attr("stroke-width", 1.5)
.attr("fill", "none")
.attr("transform", `translate(${legendWidth/2},0)`)
;
var circleLegendText=svgLegend.append("g")
.attr("style", "dominant-baseline: hanging; text-anchor: middle;") // Text alignment and styling
.attr("font-size", 10)
.selectAll("text")
.data(circleLegendValues)
.join("text")
.attr("dy", "0.35em")
.attr("x",0)
.attr("y", d => legendHeight - marginBottom - 2 * circleRadiusScale(d) + 3) // Position text below circle
.text(d=>d)
.attr("transform", `translate(${legendWidth/2},0)`)
;
var circleLegendTitle=svgLegend.append("g")
.attr("class", "circleLegendTitle")
.attr("style", "dominant-baseline: hanging; text-anchor: middle; font-weight: 900;") // Text alignment and styling
.attr("font-size", 10)
.selectAll("text")
.data([circleLegendValues[circleLegendValues.length-1]])
.join("text")
.attr("dy", "0.35em")
.attr("x",0)
.attr("y", d => legendHeight - marginBottom - 2 * circleRadiusScale(d) + 3 - 25) // Position text below circle
.text('Size of Population')
.attr("transform", `translate(${legendWidth/2},0)`); // Display the data value
//Create increasing/declining population reference line
const referenceLineData = [[0, 0], [axisSyncDomain, axisSyncDomain]]; // Adjust points as needed
const lineGenerator = d3.line()
.x(d => xAxis(d[0]))
.y(d => yAxis(d[1]));
svg.append("path")
.attr("d", lineGenerator(referenceLineData))
.attr("stroke", "brown") // Adjust color as needed
.attr("stroke-dasharray", "5,5"); // Optional: dashed line
// Reserve the SVG space inside SVG legend for density heatmap data legend
var colorDensityMapLegendBarSvg= svgLegend.append("svg").append('g')
.attr("class", "densityMapsvg")
.attr("width", colorDensityMapLegendWidth)
.attr("height", colorDensityMapLegendHeight)
.attr("transform", `translate(0,${marginTop+(legendHeight/2)+85})`)
.raise();
//create the actual legend bar
var colorDensityMapLegendBar= colorDensityMapLegendBarSvg.selectAll("rect")
.data([0,0.00075,0.0015,0.00225,0.003])
.enter()
.append("rect")
.attr("x", (d, i) => (i * 30)+25) // 25 is offset to center the bar into svgLegend
.attr("y", 5)
.attr("width", 30)
.attr("height", 20)
.attr("stroke", "black")
.attr("stroke-width", 1)
.attr("fill", d => colorDensityMap(d)).raise();
var colorDensityMapLegendnumber= colorDensityMapLegendBarSvg.selectAll('number').data([0,0.00075,0.0015,0.00225,0.003])
.enter()
.append("text")
.attr("x", (d, i) => {if (i===0){return (i * 30)} else if (i===4){return (i * 30)+30} }) // -15 to offset the rectangle to center it; +30 to offset rectangle width
.attr("y", 5+20+10) //10 offset from bar x,y origin point
.text((d,i)=>{
if (i===0){
return 'Lowest'
}
if (i===(4)){
return 'Highest'
}
})
.raise();
var colorDensityMapLegendText= colorDensityMapLegendBarSvg.append("text")
.attr("x", parseInt(colorDensityMapLegendWidth/2))
.attr("y", 0) // Adjust title position to be on top for the legend bar
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Density of country number")
.raise();
// Add one dot in the legend for each name.
var size = 20
svgLegend.selectAll("legendBoxes")
.data(regionDistinct)
.enter()
.append("rect")
.attr("x", 100)
.attr("y", function(d,i){ return 100 + i*(size+5)}) // 100 is where the first dot appears. 25 is the distance between dots
.attr("width", size)
.attr("height", size)
.style("fill", function(d,i){ return color(d)}).attr("transform", `translate(${-110}, ${25})`)
// Add one dot in the legend for each name.
svgLegend.selectAll("labelsBox")
.data(regionDistinct)
.enter()
.append("text")
.attr("x", 100 + size*1.2)
.attr("y", function(d,i){ return 100 + i*(size+5) + (size/2)}) // 100 is where the first dot appears. 25 is the distance between dots
.style("fill", function(d){ return color(d)})
.text(function(d,i){ return d})
.attr("text-anchor", "left").attr("transform", `translate(${-110}, ${30})`)
//END OF STATICS COMPONENT, DO NOT DELETE THE CURLY
}
//MAIN DYNAMIC COMPONENT, to be destroyed for each sequence of year
//Add graph title
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (marginTop / 2))
.attr("text-anchor", "middle")
.attr("class", "dynamicComponent")
.style("font-size", "16px")
.style("text-decoration", "underline")
.text("Birth Rate to Death Rate Scaterplot:"+" YEAR "+year);
//create data points on graph
svg.append('g')
.selectAll("circle")
.data(dataPerYear.get(year))
.enter()
.append("circle")
.attr("class", "dynamicComponent")
.attr('cx',(d,i)=>{return xAxis(d['Crude Death Rate (deaths per 1,000 population)'])})
.attr('cy',(d,i)=>{return yAxis(d['Crude Birth Rate (births per 1,000 population)'])})
.attr('r',(d,i)=>{return circleRadiusScale(d['Total Population, as of 1 July (thousands)'])})
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("fill", (d,i)=>{return color(d['Region'])})
//Create label for the data points
svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("class", "dynamicComponent")
.selectAll("text")
.data(dataPerYear.get(year))
.join("text")
.attr("dy", "0.35em")
.attr("x", (d,i)=> {return xAxis(d['Crude Death Rate (deaths per 1,000 population)'])+7})
.attr("y", (d,i)=> {return yAxis(d['Crude Birth Rate (births per 1,000 population)'])})
.text(d => d['Region, subregion, country or area *'])
.each(function(d, i, nodes) {
const label = this;
const otherLabels = nodes.slice(0, i);
const circleNodes = svg.selectAll('circle').nodes()
let adjusted = false;
// Adjust label position if overlapping
otherLabels.forEach(otherLabel => {
if (isOverlapping(label, otherLabel)) {
label.setAttribute('y', label.getAttribute('y') - 5);
adjusted = true;
}
});
circleNodes.forEach(circleNode => {
if (isOverlapping(label, circleNode)) {
label.setAttribute('y', label.getAttribute('y') - 5);
adjusted = true;
}
});
// If label was adjusted, check for new overlaps and adjust again if needed
if (adjusted) {
let secondAdjusted=false;
otherLabels.forEach(otherLabel => {
if (isOverlapping(label, otherLabel)) {
secondAdjusted=true
}
});
circleNodes.forEach(circleNode => {
if (isOverlapping(label, circleNode)) {
secondAdjusted=true
}
if (secondAdjusted===true){
label.remove();
}
});
}
});
//Function to check element overlap
function isOverlapping(element1, element2) {
const bbox1 = element1.getBBox();
const bbox2 = element2.getBBox();
return !(bbox1.x + bbox1.width < bbox2.x ||
bbox1.x > bbox2.x + bbox2.width ||
bbox1.y + bbox1.height < bbox2.y ||
bbox1.y > bbox2.y + bbox2.height);
}
//Create density map
// compute the density data
const densityData = d3.contourDensity()
.x(function(d) {return xAxis(d['Crude Death Rate (deaths per 1,000 population)']); })
.y(function(d) { return yAxis(d['Crude Birth Rate (births per 1,000 population)']); })
.size([width, height])
.bandwidth(7)
(dataPerYear.get(year))
// show the shape of density map
svg.insert("g", "g")
.attr("class", "dynamicComponent")
.selectAll("path")
.data(densityData)
.enter().append("path")
.attr("d",d3.geoPath())
.attr("fill", function(d) { return colorDensityMap(d.value); }).attr('opacity', "0.2")
// Top 3 density countour annotation
// Sort the densityData by value in descending order
var sortedDensityData = densityData.sort((a, b) => b.value - a.value);
// Get the top 3 densest contours
var top3DensestContours = [];
top3DensestContours= [sortedDensityData[0],sortedDensityData[parseInt((sortedDensityData.length)/2)],sortedDensityData[sortedDensityData.length-1]];
var top3Centroid = [];
for (const contour of top3DensestContours) {
let countourGroup=[...contour.coordinates[0]];
let tempCoordinates=[];
tempCoordinates=await d3.polygonCentroid(...countourGroup);
top3Centroid.push(tempCoordinates);
}
await globalTop3Centroid.push(top3Centroid)
var referenceny=50
var referencenx=50
var labelMax="HIGHEST density number of country"
var labelMedian='MEDIAN density of number of country'
var labelMin='LOWEST density of number of country'
if (parseInt(year)==1950){
labelMedian='CONVERGENCE of Median and highest: high birth and high death'
}
else if (parseInt(year)==1965){
labelMedian='MEDIAN density of number of country'
labelMax='STAGNATION: highest density is in low birth and low death'
}
else if (parseInt(year)==1981){
labelMax="HIGHEST density number of country"
labelMedian='MEDIAN DENSITY TRENDS TO STAGNATION'
}
else if (parseInt(year)==2021){
labelMedian='START OF DECLINE: start of low birth rate and low death rate'
}
else {
labelMax="HIGHEST density number of country"
labelMedian='MEDIAN density of number of country'
labelMin='LOWEST density of number of country'
}
var annotations = [{
note: {
label: labelMax,
title: year
},
x: top3Centroid[0][0], // Use calculated x directly
y: top3Centroid[0][1], // Use calculated y directly
nx: xAxis(referencenx-13),
ny: yAxis(referenceny-40),
className: "show-bg",
subject: { radius: 50, radiusPadding: -50 },
color: ['red'],
connector:{end: "arrow"}
},
{
note: {
label: labelMedian,
title: year
},
x: top3Centroid[1][0], // Use calculated x directly
y: top3Centroid[1][1], // Use calculated y directly
nx: xAxis(referencenx-8),
ny: yAxis(referenceny-25),
className: "show-bg",
subject: { radius: 30, radiusPadding: -30 },
color: ['rgb(255, 128, 0)'],
connector:{end: "arrow"}
},
{
note: {
label: labelMin,
title: year
},
x: top3Centroid[2][0], // Use calculated x directly
y: top3Centroid[2][1], // Use calculated y directly
nx: xAxis(referencenx-3),
ny: yAxis(referenceny-5),
className: "show-bg",
subject: { radius: 10, radiusPadding: -10},
color: ['orange'],
connector:{end: "arrow"}
}
]
const makeAnnotations = d3.annotation()
.editMode(true)
.notePadding(15)
.type(type)
.annotations(annotations)
var localAnnotationVariables= svg.append("g")
.attr("class", "annotation-group")
.style("font-size", 15)
.style("font-weight", 'bold')
.style("filter", 'saturate(4)')
.call(await makeAnnotations.annotations(annotations)).attr("class", "dynamicComponent");
//Inspired and adapted from https://stackoverflow.com/questions/70415772/d3-js-animate-a-circle-along-x-y-coordinates
// add path
for (const iter of globalTop3Centroid){
if (!globalMedian3Centroid.includes(iter[1]))
{
globalMedian3Centroid.push(iter[1]);
}
}
//stop annimation, after martini complete
if (martiniDone==false){
//animation for annotation
const annotationGroup = d3.selectAll('.annotation-group');
// Create a transition object
const annotationAnimationObject = d3.transition()
.duration(1000) // Adjust duration as needed
.ease(d3.easeLinear); // Adjust easing function as needed
// Select the annotation note and transition and sytle
const annotationNote = await annotationGroup.transition(annotationAnimationObject).style('opacity', 1);
const animationPathGenerator = d3.line()
.x(d => d[0])
.y(d => d[1]);
const annotationTracePath = await svg.append('path')
.attr('d', animationPathGenerator(globalMedian3Centroid))
.attr('stroke', 'maroon')
.attr('fill', 'none').attr("id","animationPath")
// draw circle at initial location
// animation for circle
globalCircle.raise().transition()
.ease(d3.easePolyOut.exponent(4))
.duration(3000)
.attrTween('transform', translateAlong(annotationTracePath.node()));
// code referred to from https://bl.ocks.org/mbostock/1705868
function translateAlong(path) {
const length = path.getTotalLength();
return function() {
return function(t) {
const {x, y} = path.getPointAtLength(t * length);
return `translate(${x},${y})`;
}
}
}
}
//create bottom time slider
timelineSliderGroup=timelineSliderSVG.append('g').attr("class", "dynamicComponent").attr("transform", `translate(${50}, ${25})`)
timelineSliderGroup.append("g")
.attr("class", "dynamicComponent")
.call(d3.axisBottom(slideTimeScale));
const timelineSliderAnnotationLine = timelineSliderGroup.selectAll().data(yearMartini).enter().append('rect').attr("class", "dynamicComponent")
.attr('x',(d,i)=>{return (slideTimeScale(d)-1.5)})
.attr('width', 3)
.attr('rx', 2)
.attr('height', 60)
.attr('fill', 'red')
.attr('class', 'timelineSlider').attr('opacity', "0.2")
.attr("transform", `translate(${0}, ${0})`).lower(); // -15 to offset the rectangle to center it; +30 to offset rectangle width
timelineSlidertext = timelineSliderGroup.selectAll().data(yearMartini).enter().append('text').attr("class", "dynamicComponent")
.attr('x',(d,i)=>{return slideTimeScale(d)})
.attr("transform", `translate(${0}, ${60})`)
.text((d,i)=>{return d})
.attr("style", "dominant-baseline: hanging; text-anchor: middle; font-weight: 900;") // Text alignment and styling
.attr("font-size", 20)
.attr('border', 'dashed red')
.raise();
//Create the circle handle for timeline bar
let tempArr=[];
tempArr.push(parseInt(currentYear))
timelineSliderGroup.selectAll('circle').remove()
timelineSliderGroup.selectAll().data(tempArr).enter().append('circle')
.attr('cx',(d,i)=>{return slideTimeScale(d)})
.attr("transform", `translate(${0}, ${-8})`)
.attr('r', 10)
.attr('fill', 'purple')
.raise();
console.log ('end of mainRendering function')
//end of mainRendering, don't remove curly
}
function recreatePurpleHandler (currentYear){
let tempArr=[];
tempArr.push(parseInt(currentYear))
}
var currentPageIndex=0;
var pageArrayIndexing=['content0', 'content1','content2','content3']
document.addEventListener("DOMContentLoaded", async function() {
recreatePurpleHandler(currentYear);
window.onload= document.getElementById('submitBtn');
submitBtn.addEventListener('click', () => {
console.log('button click detected, value is: ',yearSelect.value)
const selectedYear = yearSelect.value;
currentYear=String(selectedYear);
mainRendering(currentYear)
});
window.onload= document.getElementById("nextButton").addEventListener("click", async ()=>{
var dropdownComponent=[];
if (martiniDone==false){
console.log (currentYear,currentPageIndex)
if ((currentPageIndex<=pageArrayIndexing.length-1) && (currentPageIndex>=0)){
const elementToHide = document.getElementById(pageArrayIndexing[currentPageIndex]);
const elementToShow= document.getElementById(pageArrayIndexing[currentPageIndex+1]);
if (currentPageIndex==pageArrayIndexing.length-1){
console.log ('end of martini detected',currentPageIndex,pageArrayIndexing.length-1)
//last run before pass down
document.getElementById('yearDropDown').style.display='block';
elementToHide.style.display="none"
document.getElementById('content4').style.display='inline';
document.getElementById('nextButton').style.display='none';
document.getElementById('year').style.display='inline';
d3.selectAll('#animationPath').remove();
currentPageIndex=parseInt(currentPageIndex)+1;
martiniDone=true;
console.log ('current year and counter is')
console.log (currentYear,currentPageIndex,pageArrayIndexing)
}
else {
document.getElementById('content4').style.display='none';
document.getElementById('year').style.display='none';
currentYear=String(yearMartini[currentPageIndex+1])
const placeholder= await dataRequestandInit(yearMartini[currentPageIndex+1]).then(()=>
{
elementToShow.style.display='inline';
currentPageIndex=parseInt(currentPageIndex)+1;
elementToHide.style.display="none"
console.log ('current year and counter is')
console.log (currentYear,currentPageIndex,pageArrayIndexing)
}
)
}
}
}
})
})
</script>
<div class="allContent">
<p style='position:absolute; z-index: 99; margin-top:0;'><a href="mailto:[email protected]"><b>Ghosananda Wijaya</b></a></p>
<div class="title center">
<h1>World Population, Growth, and Demographic Changes Throughout Time (1950 to 2021)</h1>
</div>
<div class="mainContainer box">
<div id="D3container" class="container">
<div id="D3Narrative" class="narrative box">
<button onClick="window.location.reload();">Refresh Page</button>
<div>
</div>
</div>
<div id="D3MainContent" class="fixed" >
</div>
<div id="D3Misc" class="rightGutter box">
<div id="yearDropDown" class="offset" style="border:dash red;">
<span class="offset" >
<form class="offset" style="border:dash red;">
<label for="year" class="offset">Choose a year:</label>
<select name="year" id="year" class="offset" value=year>
<script>
const yearSelect = document.getElementById('year');
for (let year = 2021; year >= 1950; year--) {
const option = document.createElement('option');
option.value = year;
option.text = year;
yearSelect.appendChild(option);
}
</script>
</select>
<br><br>
<button type="button"id='submitBtn' class="offset" click="" style="height:20px; background-color:yellow; border:dash red">Select a year</button>
</form>
</span>
</div>
<button id='nextButton'type="button" class="offset" click="">Following Generation</button>
</div>
<div id="rightNarrative" class="rightNarrative">
<span id="content0" class='content'>
<h2><b><u>Beginning of data: 1950</u></b></h>
<h3>Baby Boomers Generation</h3>
<h4>Introduction to the data and visualization</h4>