-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviz_all.js
1810 lines (1528 loc) · 79.8 KB
/
viz_all.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
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
const FONT_SIZES = {
tick: 10,
axisTitle: 14,
title: 20,
markerText: 12,
legendLabel: 10,
lineLabel: 10
};
// color scale is here: https://github.com/d3/d3-scale-chromatic#schemeTableau10
const continentColors = d3.scaleOrdinal(d3.schemeTableau10)
.domain(["Africa", "Asia", "Europe", "North America", "Oceania", "South America"]);
var parseDate = d3.timeParse("%Y-%m-%d"); // for converting strings to dates ("2020-03-31", for example)
var formatDateLong = d3.timeFormat("%b %e, %Y"); // for converting dates to strings (format is like "Mar 3, 2020")
var formatDate_yyyymmdd = d3.timeFormat("%Y-%m-%d");
var formatDateMonthDay = d3.timeFormat("%b %e");
var formatMonthYear = function (d) {
if (d3.timeFormat("%m")(d) == "01") {
return d3.timeFormat("%Y")(d);
} else {
return d3.timeFormat("%b")(d);
}
};
var covidData;
var dataDict;
var geomData;
var minDate;
var maxDate;
// these properties apply to all 3 parts of viz1
var viz1 = {
selectedCountries: [],
scaleMaxToDate: false, // if false, set scales' maxes to the max over whole timeframe; if true, set max to just values observed on selected date
quantileColor: false, // if true, use scaleSequentialQuantile for colors; if false, use scaleSequential
shortenTransitions: 0 // this is to allow us to speed up transitions when dragging the date slider
};
// these are specific to viz 1a, 1b, and 1c
var viz1a = {};
var viz1b = {};
var viz1c = {
clicked: null // if a user clicks on a country, this will be a string with the country name
};
var viz2 = {};
var viz3 = {
selectedCountries: [],
shortenTransitions: 0 // this is to allow us to speed up transitions when dragging the date slider
};
function dictRowParser(d) {
return {
variable_name : d.variable_name, // name of attribute in CSV
data_type : d.data_type, // string, date, numeric, or ordinal
display_name : d.display_name, // pretty name of variable, for dropdowns, titles, etc.
sort_order : parseInt(d.sort_order), // when showing in dropdown menus, sort in this order
category : d.category, // when grouping variables (e.g., in a summary table, these are the groupings)
numeric_column : d.numeric_column, // for ordinal columns, e.g., c1_school_closing, there is a corresponding "numeric" column
larger_is : d.larger_is // determines whether a large value is "good", "bad", or "neutral", which determines the color scale on the map
};
}
function dataRowParser(d) {
return {
countryname : d.countryname,
date : parseDate(d.date),
continent : d.continent,
new_cases : parseFloat(d.new_cases),
new_cases_per_million : parseFloat(d.new_cases_per_million),
total_cases : parseFloat(d.total_cases),
total_cases_per_million : parseFloat(d.total_cases_per_million),
new_deaths : parseFloat(d.new_deaths),
new_deaths_per_million : parseFloat(d.new_deaths_per_million),
total_deaths : parseFloat(d.total_deaths),
total_deaths_per_million : parseFloat(d.total_deaths_per_million),
new_tests : parseFloat(d.new_tests),
new_tests_per_thousand : parseFloat(d.new_tests_per_thousand),
total_tests : parseFloat(d.total_tests),
total_tests_per_thousand : parseFloat(d.total_tests_per_thousand),
positive_rate : parseFloat(d.positive_rate),
reproduction_rate : parseFloat(d.reproduction_rate),
new_vaccinations : parseFloat(d.new_vaccinations),
new_vaccinations_per_hundred : parseFloat(d.new_vaccinations_per_hundred),
people_vaccinated : parseFloat(d.people_vaccinated),
people_vaccinated_per_hundred : parseFloat(d.people_vaccinated_per_hundred),
people_fully_vaccinated : parseFloat(d.people_fully_vaccinated),
people_fully_vaccinated_per_hundred : parseFloat(d.people_fully_vaccinated_per_hundred),
icu_patients : parseFloat(d.icu_patients),
icu_patients_per_million : parseFloat(d.icu_patients_per_million),
hosp_patients : parseFloat(d.hosp_patients),
hosp_patients_per_million : parseFloat(d.hosp_patients_per_million),
weekly_icu_admissions : parseFloat(d.weekly_icu_admissions),
weekly_icu_admissions_per_million : parseFloat(d.weekly_icu_admissions_per_million),
weekly_hosp_admissions : parseFloat(d.weekly_hosp_admissions),
weekly_hosp_admissions_per_million : parseFloat(d.weekly_hosp_admissions_per_million),
stringency_index : parseFloat(d.stringency_index),
government_response_index : parseFloat(d.government_response_index),
containment_health_index : parseFloat(d.containment_health_index),
economic_support_index : parseFloat(d.economic_support_index),
c1_school_closing : d.c1_school_closing,
c1_school_closing_numeric : parseFloat(d.c1_school_closing_numeric),
c2_workplace_closing : d.c2_workplace_closing,
c2_workplace_closing_numeric : parseFloat(d.c2_workplace_closing_numeric),
c3_cancel_public_events : d.c3_cancel_public_events,
c3_cancel_public_events_numeric : parseFloat(d.c3_cancel_public_events_numeric),
c4_restrictions_on_gatherings : d.c4_restrictions_on_gatherings,
c4_restrictions_on_gatherings_numeric : parseFloat(d.c4_restrictions_on_gatherings_numeric),
c5_close_public_transport : d.c5_close_public_transport,
c5_close_public_transport_numeric : parseFloat(d.c5_close_public_transport_numeric),
c6_stay_at_home_requirements : d.c6_stay_at_home_requirements,
c6_stay_at_home_requirements_numeric : parseFloat(d.c6_stay_at_home_requirements_numeric),
c7_restrictions_on_internal_movement : d.c7_restrictions_on_internal_movement,
c7_restrictions_on_internal_movement_numeric : parseFloat(d.c7_restrictions_on_internal_movement_numeric),
c8_international_travel_controls : d.c8_international_travel_controls,
c8_international_travel_controls_numeric : parseFloat(d.c8_international_travel_controls_numeric),
e1_income_support : d.e1_income_support,
e1_income_support_numeric : parseFloat(d.e1_income_support_numeric),
e2_debt_contract_relief : d.e2_debt_contract_relief,
e2_debt_contract_relief_numeric : parseFloat(d.e2_debt_contract_relief_numeric),
e3_fiscal_measures : parseFloat(d.e3_fiscal_measures),
e4_international_support : parseFloat(d.e4_international_support),
h1_public_information_campaigns : d.h1_public_information_campaigns,
h1_public_information_campaigns_numeric : parseFloat(d.h1_public_information_campaigns_numeric),
h2_testing_policy : d.h2_testing_policy,
h2_testing_policy_numeric : parseFloat(d.h2_testing_policy_numeric),
h3_contact_tracing : d.h3_contact_tracing,
h3_contact_tracing_numeric : parseFloat(d.h3_contact_tracing_numeric),
h6_facial_coverings : d.h6_facial_coverings,
h6_facial_coverings_numeric : parseFloat(d.h6_facial_coverings_numeric),
h7_vaccination_policy : d.h7_vaccination_policy,
h7_vaccination_policy_numeric : parseFloat(d.h7_vaccination_policy_numeric),
h4_emergency_investment_in_healthcare : parseFloat(d.h4_emergency_investment_in_healthcare),
h5_investment_in_vaccines : parseFloat(d.h5_investment_in_vaccines),
population : parseFloat(d.population),
population_density : parseFloat(d.population_density),
median_age : parseFloat(d.median_age),
aged_65_older : parseFloat(d.aged_65_older),
aged_70_older : parseFloat(d.aged_70_older),
gdp_per_capita : parseFloat(d.gdp_per_capita),
extreme_poverty : parseFloat(d.extreme_poverty),
cardiovasc_death_rate : parseFloat(d.cardiovasc_death_rate),
diabetes_prevalence : parseFloat(d.diabetes_prevalence),
female_smokers : parseFloat(d.female_smokers),
male_smokers : parseFloat(d.male_smokers),
life_expectancy : parseFloat(d.life_expectancy),
human_development_index : parseFloat(d.human_development_index),
iso_code : d.iso_code
};
}
function makeDateSlider(viz, cssLocation) {
/****************************
* Set up date slider
* Slider code adapted from: https://bl.ocks.org/officeofjane/47d2b0bfeecfcb41d2212d06d095c763
***************************/
viz.dateSliderValue = 0;
viz.dateSliderWidth = 400;
viz.dateXScale = d3.scaleTime()
.domain([minDate, maxDate])
.range([0, viz.dateSliderWidth])
.clamp(true); // prevent dot from going off scale
viz.svgSlider = d3.select(cssLocation)
.append("svg")
.attr("width", viz.dateSliderWidth + 100)
.attr("height", "100")
.style("vertical-align", "top")
.attr("transform", "translate(0, -15)")
.append("g")
.attr("class", "slider")
.attr("transform", "translate(50,50)");
viz.svgSlider.append("line")
.attr("class", "date-slider track")
.attr("x1", viz.dateXScale.range()[0])
.attr("x2", viz.dateXScale.range()[1])
.select(function () { return this.parentNode.appendChild(this.cloneNode(true)); })
.attr("class", "date-slider track-inset")
.select(function () { return this.parentNode.appendChild(this.cloneNode(true)); })
.attr("class", "date-slider track-overlay")
.call(d3.drag()
.on("start.interrupt", function () { viz.svgSlider.interrupt(); })
.on("start drag", function (event, d) {
viz.shortenTransitions = 100; // shorten all transition durations to 100ms
viz.dateSliderValue = event.x;
dateUpdate(viz);
})
.on("end", function () {
viz.shortenTransitions = 0; // go back to normal transitions
})
);
viz.svgSlider.insert("g", ".date-slider.track-overlay")
.attr("class", "date-slider date-ticks")
.attr("transform", "translate(0," + 18 + ")")
.selectAll("text")
.data(viz.dateXScale.ticks(10))
.enter()
.append("text")
.attr("x", viz.dateXScale)
.attr("y", 10)
.attr("text-anchor", "middle")
.text(function (d) { return formatMonthYear(d); });
// make the years in the scale bold face
d3.selectAll(cssLocation + " .date-ticks text")
.style("font-weight", function(d) {return (isNaN(1*formatMonthYear(d)) ? "normal" : "bolder");});
viz.dateHandle = viz.svgSlider.insert("circle", ".date-slider.track-overlay")
.attr("class", "date-slider handle")
.attr("r", 9);
viz.dateLabel = viz.svgSlider.append("text")
.attr("class", "label")
.attr("text-anchor", "middle")
.text(formatDateLong(minDate))
.attr("transform", "translate(0," + (-25) + ")");
viz.playButton = d3.select(cssLocation + " .play-button");
viz.playButton
.on("click", function () {
let button = d3.select(this);
if (button.text() == "Pause") {
clearInterval(viz.dateTimer);
button.text("Play");
} else {
viz.dateTimer = setInterval(dateStep, 400, viz);
button.text("Pause");
}
});
}
// function used to handle updating dates from a date slider
function dateUpdate(viz, setDate = null) {
const newDate = setDate == null ? viz.dateXScale.invert(viz.dateSliderValue) : setDate;
// update position and text of label according to slider scale
viz.dateHandle.attr("cx", viz.dateXScale(newDate));
viz.dateLabel
.attr("x", viz.dateXScale(newDate))
.text(formatDateLong(newDate));
viz.selectedDate = d3.timeDay.floor(newDate); // round down to whole day at midnight
viz.redrawFunc();
}
// function used to move date slider forward one day
function dateStep(viz) {
if (viz.dateSliderValue < 0) {
viz.dateSliderValue = 0;
}
dateUpdate(viz);
viz.dateSliderValue = Math.floor(viz.dateSliderValue + (viz.dateSliderWidth / 151));
if (viz.dateSliderValue > viz.dateSliderWidth) {
viz.dateSliderValue = 0;
clearInterval(viz.dateTimer);
viz.playButton.text("Play");
}
}
function redrawViz1a() {
const viz1aData = covidData.filter(d => d.date.getTime() == viz1.selectedDate.getTime());
const varMetadata = dataDict.filter(d => d.variable_name == viz1.selectedAttribute)[0];
const attributeName = varMetadata.display_name;
viz1a.title.text(attributeName + " among countries on " + formatDateLong(viz1.selectedDate));
if(varMetadata.data_type == "ordinal") {
// uncheck and disable both checkboxes for ordinal variables
viz1.quantileColor = false;
d3.select("input[name='viz1-quantile-checkbox']").property("checked", false);
viz1.scaleMaxToDate = false;
d3.select("input[name='viz1-scale-checkbox']").property("checked", false);
d3.selectAll(".viz1.checkbox-container").style("display","none");
} else {
d3.selectAll(".viz1.checkbox-container").style("display","inline-block");
}
/******
* update legend and colors in map
******/
let colorScale; // this is used to decide which color scale to use for the legend
let colorPalette;
let ordinalValues = [];
if(varMetadata.larger_is == "good") {
colorPalette = (varMetadata.data_type == "ordinal" ? d3.schemeYlGn : d3.interpolateYlGn);
} else if(varMetadata.larger_is == "bad") {
colorPalette = (varMetadata.data_type == "ordinal" ? d3.schemeYlOrBr : d3.interpolateYlOrBr);
} else { // neutral
colorPalette = (varMetadata.data_type == "ordinal" ? d3.schemePurples : d3.interpolatePurples);
}
if (varMetadata.data_type == "ordinal") {
// get possible values, using the text version of attribute (1-Local, 1-National, etc.)
ordinalValues = Array.from(new Set(covidData.map(d => (((d[viz1.selectedAttribute] === "NA") || (d[viz1.selectedAttribute] === "")) ? "0" : d[viz1.selectedAttribute]) ))).sort();
colorScale = d3.scaleOrdinal(colorPalette[ordinalValues.length]).domain(ordinalValues); // note: the max # of colors for this color scale is 9
} else if (viz1.quantileColor) {
colorScale = d3.scaleSequentialQuantile(colorPalette)
.domain(viz1aData.map(d => (d[viz1.selectedAttribute] < 0 ? 0 : d[viz1.selectedAttribute])));
} else {
let maxValue;
if ((!viz1.scaleMaxToDate) && (varMetadata.category == "aggregate indices")) {
maxValue = 100.0;
} else {
// if scaling to just today, use the filtered data in viz1aData, otherwise use all data in covidData
maxValue = d3.max((viz1.scaleMaxToDate ? viz1aData : covidData), d => d[viz1.selectedAttribute]);
maxValue = maxValue > 0 ? maxValue : 0;
}
colorScale = d3.scaleSequential(colorPalette).domain([0, maxValue]);
}
const legendHeight = varMetadata.data_type == "ordinal" ? (25 * ordinalValues.length) : 50;
d3.selectAll(".viz1a.legend").remove(); // if it already exists, remove it and replace it
const mapDiv = d3.select("#map")
.append("div") // this ensures it doesn't move with the map when we drag it
.classed("viz1a legend", true);
if(colorScale.domain().length > 0) {
mapDiv.append(() => legend({
color: colorScale,
title: attributeName,
width: varMetadata.data_type == "ordinal" ? 25 : 200,
height: legendHeight,
ticks: 4,
tickFormat: ".0f"
}));
const legendTop = viz1a.svg.attr("height") - 150 - (varMetadata.data_type != "ordinal" ?
0 :
ordinalValues.length * d3.select(".legend rect").attr("height"));
d3.select("#map .legend svg")
.style("position", "relative")
.style("top", legendTop + "px")
.style("left", 20 + "px");
}
d3.selectAll("#map .tick text").style("font-size", FONT_SIZES.legendLabel + "px");
d3.select("#map .legend-title").style("font-size", FONT_SIZES.axisTitle + "px");
// bind data to each path
d3.selectAll("#map path[class^='shape-']")
.data(viz1aData, function (d) {
return d ? d.iso_code : d3.select(this).attr("class").match(/(?<=shape-)[A-Z]{3}/)[0];
}).on("mouseover", function (event, d) {
d3.select(this).classed("hover-country", true);
let dataText = d[viz1.selectedAttribute];
if(typeof dataText == "number") {
dataText = (isNaN(dataText) ? "No data" : (Math.round(1000 * dataText) / 1000).toLocaleString()); // round to 3 digits
} else {
dataText = (dataText == "NA" ? "No data" : dataText);
}
viz1a.tooltip.style("display", "inline-block")
.html((d.countryname) + "<br><b>" + attributeName + "</b>: " + dataText);
}).on("mousemove", function (event, d) {
viz1a.tooltip.style("left", (event.pageX < 50 ? 0 : event.pageX - 50) + "px")
.style("top", event.pageY < 70 ? 0 : event.pageY - 70 + "px");
}).on("mouseout", function () {
d3.select(this).classed("hover-country", false);
viz1a.tooltip.style("display", "none");
}).on("click", function (event, d) {
let country = d.countryname;
if (event.ctrlKey) {
// add this country to the selection if it's not there. If it is there, remove it.
if (!viz1.selectedCountries.includes(country)) {
viz1.selectedCountries.push(country);
d3.select(this).classed("selected-country", true);
d3.select("#map .selected-country")
.classed("selected-country", false)
.classed("selected-country", true);
} else {
viz1.selectedCountries = viz1.selectedCountries.filter(d => d != country);
d3.select(this).classed("selected-country", false);
}
} else {
if (viz1.selectedCountries.length > 0) {
// if the clicked country was already in the list, clear out the entire list
// if the clicked country was not in the list, clear the list and put this country in
const includedCountry = viz1.selectedCountries.includes(country);
viz1.selectedCountries = [];
d3.selectAll("#map .selected-country").classed("selected-country", false);
if (!includedCountry) {
viz1.selectedCountries.push(country);
d3.select(this).classed("selected-country", true);
}
} else {
viz1.selectedCountries.push(country);
d3.select(this).classed("selected-country", true);
}
}
// selection changed: re-draw!
redrawViz1b();
redrawViz1c();
redrawViz2();
}).transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 200)
.attr("fill", function (d) {
let val;
if(varMetadata.data_type == "ordinal") {
val = (((d[viz1.selectedAttribute] === "NA") || (d[viz1.selectedAttribute] === "")) ? "0" : d[viz1.selectedAttribute]);
} else {
val = (d[viz1.selectedAttribute] > 0 ? d[viz1.selectedAttribute] : 0);
}
return (colorScale.domain().length > 0 ? colorScale(val) : "rgb(255, 255, 229)");
});
}
function redrawViz1b() {
const viz1bData = covidData.filter(d => viz1.selectedCountries.includes(d.countryname) &&
(d.date.getTime() == viz1.selectedDate.getTime()));
const varMetadata = dataDict.filter(d => d.variable_name == viz1.selectedAttribute)[0];
// if ordinal, use numeric_column attribute (e.g., c1_school_closing_numeric), otherwise use attribute as selected
const attributeName = varMetadata.display_name;
const attributeData = (varMetadata.data_type == "ordinal" ? varMetadata.numeric_column : viz1.selectedAttribute);
// in case we removed all the data, don't show any axes or gridlines
const axisVisibility = viz1bData.length == 0 ? "none" : "inherit";
d3.selectAll(".viz1b .x").style("display", axisVisibility);
d3.selectAll(".viz1b .y").style("display", axisVisibility);
d3.selectAll(".viz1b .grid").style("display", axisVisibility);
d3.selectAll("div.viz1-continents").style("display", axisVisibility);
/******
* update y-axis
******/
// Doing it this way so that we can maintain the order in which the user selected countries
viz1b.yScale.domain(viz1.selectedCountries);
d3.select(".viz1b.y.axis")
.transition()
.duration(500)
.call(viz1b.yAxis);
// remove y-axis ticks and vertical black line
d3.selectAll(".viz1b.y.axis .tick line").remove();
d3.selectAll(".viz1b.y.axis path").remove();
/******
* update x-axis
******/
// see if this variable is ordinal; if it is, use its "_numeric" column
let maxValue;
if ((varMetadata.data_type == "ordinal")) {
// get largest value over entire dataset, not just selection
maxValue = d3.max(covidData, d => (d[attributeData] > 0 ? d[attributeData] : 0));
let ordinalValues = ["0", "1-Local", "1-National", "2-Local", "2-National", "3-Local", "3-National", "4-Local", "4-National", "5-Local", "5-National"];
// set tick values to exactly these values
// e.g., if maxValue = 2.5, ticks will be: 0, 0.5, 1, 1.5, 2, 2.5
viz1b.xScale.domain([0, maxValue]);
viz1b.xAxis
.tickValues(d3.range(0, maxValue + 0.5, 0.5))
.tickFormat(d => ordinalValues[Math.floor(d * 2)]);
} else {
// If we're showing an aggregate index like "stringency index", always show 0 to 100.
// Otherwise, get the maximum value for the attribute *across the whole dataset* for
// the selected countries. This is because we don't want the scales to keep jumping
// around for a given set of countries and making it hard to see changes.
if ((!viz1.scaleMaxToDate) && (varMetadata.category == "aggregate indices")) {
maxValue = 100.0;
} else {
const dataset = (viz1.scaleMaxToDate ? viz1bData : covidData);
maxValue = d3.max(dataset.filter(d => viz1.selectedCountries.includes(d.countryname)),
d => (d[attributeData] > 0 ? d[attributeData] : 0));
}
viz1b.xScale.domain([0, maxValue]);
// if we switched from an ordinal variable, get rid of the manually specified ticks
viz1b.xAxis.tickValues(null).tickFormat(null);
viz1b.xAxisTicks.ticks(5);
}
d3.select(".viz1b.x.axis")
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 300)
.call(viz1b.xAxis);
// add the X gridlines
// see: https://bl.ocks.org/d3noob/c506ac45617cf9ed39337f99f8511218
d3.select(".viz1b.grid")
.call(viz1b.xAxisTicks);
// set all ticks' fonts. These aren't styles/CSS, these are attributes
d3.selectAll(".viz1b.axis")
.attr("font-size", FONT_SIZES.tick)
.attr("font-family", "sans-serif");
// rotate x-axis ticks
d3.selectAll('.viz1b.x.axis .tick text')
.attr("transform", "rotate(-45)")
.attr("text-anchor", "end");
// Create the bars: there will be one with the actual data, and one that is invisible
// which extends the length of the chart and activates the hover effect
let bars = viz1b.svg.selectAll("rect.data")
.data(viz1bData, d => d.countryname);
bars.exit()
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 300)
.style("fill-opacity", 0)
.remove();
bars.enter()
.append("rect")
.attr("fill", d => continentColors(d.continent))
.classed("viz1b bar data", true)
.attr("id", function (d, i) { return "viz1b-bar" + i; })
.merge(bars)
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 500)
.attr("y", d => viz1b.yScale(d.countryname))
.attr("height", viz1b.yScale.bandwidth())
.attr("width", d => viz1b.xScale((d[attributeData] > 0 ? d[attributeData] : 0)));
/**********************
* use "invisible" bars to allow hovering even over very small values
***********************/
let invisibleBars = viz1b.svg.selectAll("rect.invisible")
.data(viz1bData, d => d.countryname);
invisibleBars.exit()
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 300)
.style("fill-opacity", 0)
.remove();
invisibleBars.enter()
.append("rect")
.attr("fill-opacity", "0.05")
.classed("viz1b bar invisible", true)
.merge(invisibleBars)
.on("mouseover", function (event, d) {
d3.select(this).classed("hover-bar", true);
let dataText = d[viz1.selectedAttribute];
if(typeof dataText == "number") {
dataText = (isNaN(dataText) ? "No data" : (Math.round(1000 * dataText) / 1000).toLocaleString()); // round to 3 digits
} else {
dataText = (((dataText === "NA") || (dataText === "")) ? "No data" : dataText);
}
viz1b.tooltip
.style("display", "inline-block")
// note: display attributeName's value, not attributeData, because we want to see the categorical value, not numeric version
// Also, don't show NaN or "NA". If no data, write "No data"
.html((d.countryname) + "<br><b>" + attributeName + "</b>: " + dataText);
}).on("mousemove", function (event, d) {
viz1b.tooltip.style("left", event.pageX - 50 + "px")
.style("top", event.pageY - 70 + "px");
}).on("mouseout", function () {
d3.select(this).classed("hover-bar", false);
viz1b.tooltip.style("display", "none");
})
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 500)
.attr("y", d => viz1b.yScale(d.countryname))
.attr("height", viz1b.yScale.bandwidth())
.attr("width", d => viz1b.xScale(viz1b.xScale.domain()[1]));
/**********************
* Add a text label specifying "No data" when a country doesn't have any data (to differentiate it from 0)
**********************/
let noData = viz1b.svg.selectAll("text.no-data")
.data(viz1bData, d => d.countryname);
noData.exit()
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 300)
.style("fill-opacity", 0)
.remove();
noData.enter()
.append("text")
.classed("viz1b no-data", true)
.attr("id", function (d, i) { return "viz1b-nodata" + i; })
.merge(noData)
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 500)
.attr("y", d => viz1b.yScale(d.countryname) + 0.5 * viz1b.yScale.bandwidth())
.attr("dy", "0.3em")
.style("visibility", d => ((isNaN(d[attributeData]) || (d[attributeData] === "NA") || (d[attributeData] === "")) ? "visible" : "hidden"))
.text(d => ((isNaN(d[attributeData]) || (d[attributeData] === "NA") || (d[attributeData] === "")) ? "No data" : ""));
}
function redrawViz1c() {
// get all data for selected countries
const viz1cData = covidData.filter(d => viz1.selectedCountries.includes(d.countryname));
const varMetadata = dataDict.filter(d => d.variable_name == viz1.selectedAttribute)[0];
// if ordinal, use numeric_column attribute (e.g., c1_school_closing_numeric), otherwise use attribute as selected
// these are defined as object attributes so that we can define the hover effects in makeViz1c
viz1c.attributeName = varMetadata.display_name;
viz1c.attributeData = varMetadata.data_type == "ordinal" ? varMetadata.numeric_column : viz1.selectedAttribute;
// in case we removed all the data, don't show any axes or gridlines
const axisVisibility = (viz1cData.length == 0 ? "none" : "inherit");
d3.selectAll(".viz1c .x").style("display", axisVisibility);
d3.selectAll(".viz1c .y").style("display", axisVisibility);
d3.selectAll(".viz1c .grid").style("display", axisVisibility);
viz1c.dateLine
.style("display", axisVisibility)
.transition()
.duration(viz1.shortenTransitions > 0 ? 0 : 200) // move the line immediately if dragging the time slider
.attr("x1", viz1c.xScale(viz1.selectedDate))
.attr("x2", viz1c.xScale(viz1.selectedDate));
/******
* update y-axis (attribute)
******/
// see if this variable is ordinal; if it is, use its "_numeric" column
let maxValue;
if (varMetadata.data_type == "ordinal") {
// get largest value over entire dataset, not just selection
maxValue = d3.max(covidData, d => (d[viz1c.attributeData] > 0 ? d[viz1c.attributeData] : 0));
let ordinalValues = ["0", "1-Local", "1-National", "2-Local", "2-National", "3-Local", "3-National", "4-Local", "4-National", "5-Local", "5-National"];
// set tick values to exactly these values
// e.g., if maxValue = 2.5, ticks will be: 0, 0.5, 1, 1.5, 2, 2.5
viz1c.yScale.domain([0, maxValue]);
viz1c.yAxis
.tickValues(d3.range(0, maxValue + 0.5, 0.5))
.tickFormat(d => ordinalValues[Math.floor(d * 2)]);
} else {
// If we're showing an aggregate index like "stringency index", always show 0 to 100.
// Otherwise, get the maximum value for the attribute *across the whole dataset* for
// the selected countries. This is because we don't want the scales to keep jumping
// around for a given set of countries and making it hard to see changes.
if (varMetadata.category == 'aggregate indices') {
maxValue = 100.0;
} else {
maxValue = d3.max(covidData.filter(d => viz1.selectedCountries.includes(d.countryname)),
d => (d[viz1c.attributeData] > 0 ? d[viz1c.attributeData] : 0));
}
viz1c.yScale.domain([0, maxValue]);
// if we switched from an ordinal variable, get rid of the manually specified ticks
viz1c.yAxis.tickValues(null).tickFormat(null);
viz1c.yAxisTicks.ticks(5);
}
// Update y-axis (x-axis is constant)
d3.select(".viz1c.y.axis")
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 300)
.call(viz1c.yAxis);
// add the Y gridlines (x-axis is constant)
// see: https://bl.ocks.org/d3noob/c506ac45617cf9ed39337f99f8511218
d3.select(".viz1c.y.grid")
.call(viz1c.yAxisTicks);
// rotate x-axis ticks
d3.selectAll('.viz1c.x.axis .tick text')
.attr("transform", "rotate(-45)")
.attr("text-anchor", "end");
// set all ticks' fonts. These aren't styles/CSS, these are attributes
d3.selectAll(".viz1c.axis")
.attr("font-size", FONT_SIZES.tick)
.attr("font-family", "sans-serif");
// create a "nested" structure to allow us to draw one line per country
// see https://stackoverflow.com/a/35279106/1102199
// "d3.nest()" is deprecated; see https://github.com/d3/d3-array/blob/master/README.md#group
viz1c.nestedData = d3.groups(viz1cData, d => d.countryname);
let lineGenerator = d3.line()
.defined(function (d) { return !isNaN(d[viz1c.attributeData]); })
.x(d => viz1c.xScale(d.date))
.y(d => viz1c.yScale(d[viz1c.attributeData] > 0 ? d[viz1c.attributeData] : 0));
let lines = viz1c.svg.selectAll(".viz1c.line")
.data(viz1c.nestedData, d => d[0]); // use the country name in d[0] as the "key" for merging later
let labels = viz1c.svg.selectAll(".viz1c.line-label")
.data(viz1c.nestedData, d => d[0]);
lines.exit()
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 200)
.style("stroke-opacity", 0)
.remove();
labels.exit()
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 200)
.style("fill-opacity", 0)
.remove();
if (viz1c.clicked && !(viz1c.nestedData.map(d => d[0]).includes(viz1c.clicked))) {
// if we had clicked on a country, but now we've changed our country selection
// and the clicked country doesn't exist in our selection, reset the clicked state
viz1c.clicked = null;
}
lines.enter()
.append("path")
.classed("viz1c line", true)
.attr("stroke-width", 1.5)
.attr("fill", "none")
.merge(lines)
.attr("stroke", function (d) {
const color = continentColors(d[1][0].continent);
if (viz1c.clicked) {
if (d[1][0].countryname == viz1c.clicked) {
return color;
}
return "#ddd";
} else {
return color;
}
}) // d[1] is array of all rows for a country; d[1][0] is the first row of data in that array; we get the continent just from the first row
.attr("id", d => "line-" + d[0].replaceAll(" ", "-"))
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 500)
.attr("d", d => lineGenerator(d[1]));
labels.enter()
.append("text")
.classed("viz1c line-label", true)
.attr("font-size", FONT_SIZES.lineLabel)
.merge(labels)
.text(d => d[0])
.attr("x", viz1c.dims.innerWidth + 5)
.attr("stroke", function (d) {
const color = continentColors(d[1][0].continent);
if (viz1c.clicked) {
if (d[1][0].countryname == viz1c.clicked) {
return color;
}
return "#ddd";
} else {
return color;
}
}) // d[1] is array of all rows for a country; d[1][0] is the first row of data in that array; we get the continent just from the first row
.attr("stroke-width", 0.75)
.transition()
.duration(viz1.shortenTransitions > 0 ? viz1.shortenTransitions : 500)
.style("fill-opacity", 1)
.attr("y", function(d) {
const lastValue = d[1].slice(-1)[0][viz1c.attributeData];
return viz1c.yScale(lastValue > 0 ? lastValue : 0);
});
}
function redrawViz1All() {
redrawViz1a();
redrawViz1b();
redrawViz1c();
}
function redrawViz2() {
let viz2Data = covidData.filter(d => (viz1.selectedCountries.includes(d.countryname)
&& (d.date.getTime() == maxDate.getTime()))); // table only shows latest data
if(viz2Data.length == 0) {
d3.select("div.viz2").style("display","none");
return;
} else {
d3.select("div.viz2").style("display","inherit");
}
// replace the table we're updating
d3.select(".viz2-table table").remove();
const table = d3.select(".viz2-table").append("table");
const WIDTH_PER_COUNTRY_COL = 125;
const WIDTH_ATTRIBUTE_COL = 200;
table.attr("width", WIDTH_ATTRIBUTE_COL + viz1.selectedCountries.length * WIDTH_PER_COUNTRY_COL);
// append the header row. First column = "attribute", then one column per country
const headerRow = table.append("thead").append("tr");
headerRow.append("th")
.text("Attribute")
.attr("width", WIDTH_ATTRIBUTE_COL);
viz1.selectedCountries.forEach(function(country) {
headerRow.append("th")
.text(country)
.attr("width", WIDTH_PER_COUNTRY_COL);
});
// add the data rows. First cell in each row is the attribute, the remaining cells are the countries' values
const tbody = table.append("tbody");
dataDict.filter(d => d.category == viz2.selectedCategory)
.forEach(function(attribute) {
const tr = tbody.append("tr");
tr.classed("selected-row", attribute.variable_name == viz1.selectedAttribute)
.append("td").text(attribute.display_name);
// make a hashmap/dictionary from country --> attribute value
const attributeMap = viz2Data.reduce(
function(map, obj) {
map[obj.countryname] = obj[attribute.variable_name];
return map;
}, {});
// add each country's value, in order of appearance
// round numeric values to 3 decimal places, and replace "NAN" or "NA" with "No data"
viz1.selectedCountries.forEach(function(country) {
let valText = attributeMap[country];
if(typeof valText == "number") {
valText = (isNaN(valText) ? "No data" : (Math.round(1000 * valText) / 1000).toLocaleString()); // round to nearest 3 decimal places
} else {
valText = (((valText === "NA") || (valText === "")) ? "No data" : valText);
}
tr.append("td").text(valText);
});
});
}
function redrawViz3() {
const viz3Data = covidData.filter(d => (viz3.selectedCountries.includes(d.countryname) &&
(d.date.getTime() == viz3.selectedDate.getTime())));
const varMetadata = {
'x': dataDict.filter(d => d.variable_name == viz3.selectedXAttribute)[0],
'y': dataDict.filter(d => d.variable_name == viz3.selectedYAttribute)[0]
};
// Note: if ordinal, use numeric_column attribute (e.g., c1_school_closing_numeric), otherwise use attribute as selected
const attributeNames = {
'x': {'name': varMetadata.x.display_name,
'data': (varMetadata.x.data_type == "ordinal" ? varMetadata.x.numeric_column : viz3.selectedXAttribute)},
'y': {'name': varMetadata.y.display_name,
'data': (varMetadata.y.data_type == "ordinal" ? varMetadata.y.numeric_column : viz3.selectedYAttribute)}
};
// in case we removed all the data, don't show any axes or gridlines
let axis_visibility = viz3Data.length == 0 ? "none" : "inherit";
d3.selectAll(".viz3 .x").style("display", axis_visibility);
d3.selectAll(".viz3 .y").style("display", axis_visibility);
d3.selectAll(".viz3 .grid").style("display", axis_visibility);
d3.selectAll(".viz3-legend").style("display", axis_visibility);
/******************
* update x and y axes
******************/
const updateAxis = function(xOrY="x") {
let scale, axis, axisTicks;
if(xOrY == "x") {
scale = viz3.xScale;
axis = viz3.xAxis;
axisTicks = viz3.xAxisTicks;
} else {
scale = viz3.yScale;
axis = viz3.yAxis;
axisTicks = viz3.yAxisTicks;
}
// see if this variable is ordinal; if it is, use its "_numeric" column
let maxValue;
if((varMetadata[xOrY].data_type == "ordinal")) {
// get largest value over entire dataset, not just selection
maxValue = d3.max(covidData, d => (d[attributeNames[xOrY].data] > 0 ? d[attributeNames[xOrY].data] : 0));
let ordinalValues = ["0", "1-Local", "1-National", "2-Local", "2-National", "3-Local", "3-National", "4-Local", "4-National", "5-Local", "5-National"];
// set tick values to exactly these values
// e.g., if maxValue = 2.5, ticks will be: 0, 0.5, 1, 1.5, 2, 2.5
scale.domain([0, maxValue]);
axis.tickValues(d3.range(0, maxValue + 0.5, 0.5))
.tickFormat(d => ordinalValues[Math.floor(d * 2)]);
} else {
// If we're showing an aggregate index like "stringency index", always show 0 to 100.
// Otherwise, get the maximum value for the attribute *across the whole dataset* for
// the selected countries. This is because we don't want the scales to keep jumping
// around for a given set of countries and making it hard to see changes.
if (varMetadata[xOrY].category == 'aggregate indices') {
maxValue = 100.0;
} else {
// Note: using viz3Data, not entire dataset. We want to see the trend at any point in time
maxValue = d3.max(viz3Data.filter(d => viz3.selectedCountries.includes(d.countryname)),
d => (d[attributeNames[xOrY].data] > 0 ? d[attributeNames[xOrY].data] : 0));
}
scale.domain([0, maxValue]);
// if we switched from an ordinal variable, get rid of the manually specified ticks
axis.tickValues(null).tickFormat(null);
axisTicks.ticks(5);
}
d3.select(`.viz3.${xOrY}.axis`)
.transition()
.duration(viz3.shortenTransitions > 0 ? viz3.shortenTransitions : 300)
.call(axis);
// update axis title
d3.select(`text.viz3.${xOrY}.axis-title`)
.text(attributeNames[xOrY].name);
// add the gridlines
// see: https://bl.ocks.org/d3noob/c506ac45617cf9ed39337f99f8511218
d3.select(`.viz3.${xOrY}.grid`)
.call(axisTicks);
};
updateAxis("x");
updateAxis("y");
// rotate x-axis ticks
d3.selectAll('.viz3.x.axis .tick text')
.attr("transform","rotate(-45)")
.attr("text-anchor","end");
// set all ticks' fonts. These aren't styles/CSS, these are attributes
d3.selectAll(".viz3.axis")
.attr("font-size", FONT_SIZES.tick)
.attr("font-family", "sans-serif");
/************************
* Create the actual points on the plot
************************/
const dots = viz3.svg.selectAll("circle.dot")
.data(viz3Data, d => d.countryname);
dots.exit()
.transition()
.duration(viz3.shortenTransitions > 0 ? viz3.shortenTransitions : 300)
.style("fill-opacity", 0)
.remove();
dots.enter()
.append("circle")
.attr("r", 3.5)
.attr("fill", d => continentColors(d.continent))
.classed("dot", true)
.merge(dots)
.on("mouseover", function(event, d) {
const getDataText = function(xOrY="x") {
let dataText = d[(xOrY == "x" ? viz3.selectedXAttribute : viz3.selectedYAttribute)];
if(typeof dataText == "number") {
dataText = (isNaN(dataText) ? "No data" : (Math.round(1000 * dataText) / 1000).toLocaleString()); // round to 3 digits
} else {
dataText = (((dataText === "NA") || (dataText === "")) ? "No data" : dataText);
}
return dataText;
};
d3.select(this).classed("hover-point", true);
viz3.tooltip.style("display", "inline-block")
.html(d.countryname + "<br>" +
"<b>" + attributeNames.x.name + "</b>: " + getDataText("x") + "<br>" +
"<b>" + attributeNames.y.name + "</b>: " + getDataText("y"));
}).on("mousemove", function(event, d) {
viz3.tooltip.style("left", event.pageX - 50 + "px")
.style("top", event.pageY - 70 + "px");
}).on("mouseout", function() {
d3.select(this).classed("hover-point", false);
viz3.tooltip.style("display", "none");
})
.transition()
.duration(viz3.shortenTransitions > 0 ? viz3.shortenTransitions : 300)
.attr("cy", d => viz3.yScale(isNaN(d[attributeNames.y.data]) ? 0 : d[attributeNames.y.data]))
.attr("cx", d => viz3.xScale(isNaN(d[attributeNames.x.data]) ? 0 : d[attributeNames.x.data]));
}
function makeViz1a() {
viz1a.tooltip = d3.select("body")
.append("div")
.classed("viz1a tooltip", true);
viz1a.title = d3.select(".viz1a.title span")
.style("font-size", FONT_SIZES.title + "px")