-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.js
1649 lines (1221 loc) · 50.5 KB
/
map.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
// We define a variable holding the current key to visualize on the map.
// var datasets0 = ['DAILY_CASES',
// 'DAILY_DIED',
// 'DAILY_RECOVERED',
// 'ASYMPTOMATIC',
// 'MILD',
// 'CRITICAL',
// 'SEVERE',
// 'TOT_CASES',
// 'TOT_DIED',
// 'TOT_RECOVERED',
// ]
var datasets = ['DAILY CASES',
'DAILY DEATHS',
'DAILY RECOVERIES',
'ASYMPTOMATIC',
'MILD',
'CRITICAL',
'SEVERE',
'TOTAL CASES',
'TOTAL DIED',
'TOTAL RECOVERIES',
]
var varList = ['CASES PER 100K POP', 'CASES']
function convertToVar(VAR) {
var ANS
if (VAR == 'CASES PER 100K POP' || VAR.includes('_per_100kpop')==true) {
ANS = '_per_100kpop'
}
if (VAR == 'CASES' || VAR == "" ) {
ANS = "" // crucial!!!!!!!
}
return ANS
}
function convertToColumnName(KEY, VAR) {
var KEY_NEW = KEY
if (KEY_NEW.includes('NUM_')==false){
KEY_NEW = 'NUM_' + KEY_NEW
}
if (VAR !='_per_100kpop' && KEY_NEW.includes('_per_100kpop')==false){
KEY_NEW = KEY_NEW.replace('_per_100kpop','')
}
if (VAR == "_per_100kpop" && KEY_NEW.includes('_per_100kpop')==false) {
KEY_NEW = KEY_NEW + VAR
}
if (VAR != "_per_100kpop" && KEY_NEW.includes('_per_100kpop')==true) {
KEY_NEW = KEY_NEW.replace('_per_100kpop','')
}
// if (VAR == "_per_100kpop" && KEY_NEW.includes('_per_100kpop')==true) {
// KEY_NEW = KEY_NEW
// }
return KEY_NEW.replace(' ','_').replace('RECOVERIES','RECOVERED').replace('DEATHS','DIED').replace('TOTAL','TOT')
}
function convertToFileName(KEY) {
return KEY.replace('NUM_','').replace('_per_100kpop','').replace(' ','_').replace('RECOVERIES','RECOVERED').replace('DEATHS','DIED').replace('TOTAL','TOT')
}
function convertToText(KEY) {
ANS = KEY.replace("_"," ").replace('RECOVERED','RECOVERIES').replace('DIED','DEATHS').replace('TOT','TOTAL').replace('NUM ','').replace("DAILY_","DAILY ").replace("TOTAL_","TOTAL ") // fix this later
if (KEY.includes('_per_100kpop')==true) {
ANS = ANS.replace('_per_100kpop', ' PER 100K POP')
}
return ANS
}
var currentVar = convertToVar('CASES PER 100K POP')
var currentKey = convertToColumnName('DAILY CASES', currentVar)
console.log(currentKey)
///////////////
d3.select("#factorButton")
.selectAll("myOptions")
.data(varList)
.enter()
.append('option')
.text(function (d) { return d; }) // text showed in the menu
// .attr("value", function (d) { return d; }) // corresponding value returned by the button
.attr("value", function(d){ return d })
///////////////
///////////////
d3.select("#selectButton")
.selectAll("myOptions")
.data(datasets)
.enter()
.append('option')
.text(function (d) { return d; }) // text showed in the menu
// .attr("value", function (d) { return d; }) // corresponding value returned by the button
.attr("value", function(d){ return d })
///////////////
///////////////
// A "listener" is added to the browser window; updateLegend is called when
// the window is resized.
window.onresize = updateLegend;
// The dimensions for the map container are specified. The same
// width and height are used (as specified in the CSS above).
var width = 900,
height = 250;
// A variable mapData is defined to hold the data of the CSV later.
var mapData;
// Get and prepare the Mustache template; parsing the template speeds up future uses
var template = d3.select('#template').html();
Mustache.parse(template);
// An SVG element is created in the map container and provided it with
// dimensions. A viewbox is then used; preserve the aspect ratio. This yields
// a responsive map that rescales and "adapts" with different screen sizes.
var svg = d3.select('#map').append('svg')
.attr("preserveAspectRatio", "xMidYMid")
.attr("viewBox", "0 0 " + width + " " + height);
// Add a <g> element to the SVG element and give it a class to
// style. We also add a class name for Colorbrewer.
var mapFeatures = svg.append('g')
.attr('class', 'features YlGnBu');
// Add a <div> container for the tooltip, which is hidden by default.
var tooltip = d3.select("#map")
.append("div")
.attr("class", "tooltip hidden");
// Define the zoom and attach it to the map
var zoom = d3.behavior.zoom()
.scaleExtent([0.5,60]) //[1, 10])
.on('zoom', doZoom);
svg.call(zoom);
// Define a geographical projection
// https://github.com/mbostock/d3/wiki/Geo-Projections
// and set some dummy initial scale. The correct scale, center and
// translate parameters will be set once the features are loaded.
var projection = d3.geo.mercator()
.scale(1);
// Prepare a path object and apply the projections to it.
var path = d3.geo.path()
.projection(projection);
// Prepare an object to have easier access to the data.
var dataById = d3.map();
// Prepare a quantized scale to categorize the values in 9 groups.
// The scale returns text values which can be used for the color CSS
// classes (q0-9, q1-9 ... q8-9). The domain will be defined once the
// values are known.
var quantize = d3.scale.quantize()
.range(d3.range(8).map(function(i) { return 'q' + i + '-9'})); // 9 scales
// ^ only VALID TILL 9 TIERS FOR YlGnBu
// .range(d3.range(11).map(function(i) { console.log('q' + i + '-9'); return 'q' + i + '-9'})); // 9 scales
// Prepare a number format which will always return 2 decimal places.
var formatNumber = d3.format('.2f');
// console.log(toString(1.00).size())
// For the legend, we prepare a very simple linear scale. Domain and
// range will be set later as they depend on the data currently shown.
// var legendX = d3.scale.linear();
var legendX = d3.scale.linear();
// Use the scale to define an axis. The tickvalues will be set later
// as they also depend on the data.
var legendXAxis = d3.svg.axis()
.scale(legendX)
.orient("bottom")
.tickSize(13)
.tickFormat(function(d) {
return formatNumber(d);
});
// Create an SVG element in the legend container and give it some
// dimensions.
var legendSvg = d3.select('#legend').append('svg')
.attr('width', '100%')
.attr('height', '44');
// To this SVG element, add a <g> element which will hold all of our
// legend entries.
var g = legendSvg.append('g')
.attr("class", "legend-key YlGnBu")
.attr("transform", "translate(" + 20 + "," + 20 + ")");
// Add a <rect> element for each quantize category. The width and
// color of the rectangles will be set later.
g.selectAll("rect")
.data(quantize.range().map(function(d) {
return quantize.invertExtent(d);
}))
.enter().append("rect");
// Add a <text> element acting as the caption of the legend. The text
// will be set later.
g.append("text")
.attr("class", "caption")
.attr("y", -6)
// console.log(getIdOfFeature)
/**
* Function to update the legend.
* Loosely based on http://bl.ocks.org/mbostock/4573883
*/
function updateLegend() {
// Determine the width of the legend. It is based on the width of
// the map minus some spacing left and right.
var legendWidth = d3.select('#map').node().getBoundingClientRect().width - 50;
// Determine the domain of the quantize scale which will be used as
// tick values. We cannot directly use the scale via quantize.scale()
// because this returns only the minimum and maximum values but we need all
// the steps of the scale. The range() function returns all categories
// and we need to map the category values (q0-9, ..., q8-9) to the
// number values. To do this, we can use invertExtent().
var legendDomain = quantize.range().map(function(d) {
var r = quantize.invertExtent(d);
return r[1];
});
// Since we always only took the upper limit of the category, we also
// need to add the lower limit of the very first category to the top
// of the domain.
legendDomain.unshift(quantize.domain()[0]);
// On smaller screens, there is not enough room to show all 10
// category values. In this case, we add a filter leaving only every
// third value of the domain.
if (legendWidth < 400) {
legendDomain = legendDomain.filter(function(d, i) {
return i % 3 == 0;
});
}
// Set the domain and range for the x scale of the legend. The
// domain is the same as for the quantize scale and the range takes up
// all the space available to draw the legend.
legendX
.domain(quantize.domain())
.range([0, legendWidth]);
// Update the rectangles by (re)defining their position and width
// (both based on the legend scale) and setting the correct class.
g.selectAll("rect")
.data(quantize.range().map(function(d) {
return quantize.invertExtent(d);
}))
.attr("height", 8)
.attr("x", function(d) { return legendX(d[0]); })
.attr("width", function(d) { return legendX(d[1]) - legendX(d[0]); })
.attr('class', function(d, i) {
return quantize.range()[i];
});
// Update the legend caption. To do this, we take the text of the
// currently selected dropdown option.
// var keyDropdown = d3.select('#select-key').node();
// var selectedOption = keyDropdown.options[keyDropdown.selectedIndex];
formatDate = d3.time.format("%d %b %Y")
// console.log(currentKey + ' ( latest count as of ' + formatDate(lrangx[1]) + ')')
///////
/// LEGEND TEXT
///////
//////
// var textL = currentKey// .replace('TOT','TOTAL').replace('RECOVERED','RECOVERIES').replace('DIED','DEATHS').replace('NUM_','').replace('_',' ');
console.log(currentKey)
console.log(currentVar)
g.selectAll('text.caption')
.text(convertToText(currentKey)); // + ' (latest value)');
// .text(selectedOption.text);
// We set the calculated domain as tickValues for the legend axis.
legendXAxis
.tickValues(legendDomain)
// We call the axis to draw the axis.
g.call(legendXAxis);
}
// Load the features from the GeoJSON.
// Load the file corresponding to the Philippine regions.
d3.json('data/Regions-p1p2p3.json', function(error, features) {
// Get the scale and center parameters from the features.
var scaleCenter = calculateScaleCenter(features);
// Apply scale, center and translate parameters.
projection.scale(scaleCenter.scale)
.center(scaleCenter.center)
.translate([width/2, height/2]);
// Read the data for the cartogram
// d3.csv('data/sample_data_ph.csv', function(data) {
// d3.csv('data/covid19ph/LATEST_daily_and_movAve_ph_covid19_stats_forDashboards_nWindow=7.csv', function(data) {
d3.csv('data/covid19ph/combi_LATEST_daily_and_movAve_ph_covid19_stats_forDashboards_nWindow=7.csv', function(data) {
// We store the data object in the variable which is accessible from
// outside of this function..csv
// We add the features to the <g> element created before.
// D3 wants us to select the (non-existing) path objects first ...
function Xupdate() {
mapData = data;
// This maps the data of the CSV so it can be easily accessed by
// the ID of the municipality, for example: dataById[2196]
dataById = d3.nest()
// .key(function(d) { return d.REGION; })
.key(function(d) { return d.REGION_L; })
.rollup(function(d) { return d[0]; })
.map(data);
console.log(dataById)
console.log(currentKey)
mapFeatures.selectAll('path')
// ... and then enter the data. For each feature, a <path>
// element is added.
.data(features.features)
.enter().append('path')
// As "d" attribute, we set the path of the feature.
.attr('d', path)
// When the mouse moves over a feature, show the tooltip.
.on('mousemove', showTooltip)
// When the mouse moves out of a feature, hide the tooltip.
.on('mouseout', hideTooltip)
// When a feature is clicked, show the details of it.
.on('click', plotF); // , showDetails);
/// dito mo idadagdag yung plot...
// .on('click', showDetails);
// Call the function to update the map colors.
updateMapColors();
}
Xupdate()
d3.select("#selectButton").on("change", function(d) {
// recover the option that has been chosen
// currentKey = 'NUM_' + d3.select(this).property("value") + cVar
currentKey = d3.select(this).property("value")
// var cVar = currentVar
console.log(currentKey)
console.log(currentVar)
// function convertToVar(VAR) {
// var ANS = null
// if (VAR == 'CASES PER 100K POP') {
// ANS = '_per_100kpop'
// }
// if (VAR == 'CASES') {
// ANS = ""
// }
// return ANS
// }
// function convertToColumnName(KEY, VAR) {
// var KEY_NEW = 'NUM_' + KEY + VAR
// if( VAR != "_per_100kpop" ) { // meaning it's actual cases (so "")
// KEY_NEW = 'NUM_' + KEY
// }
// return KEY_NEW.replace(' ','_').replace('RECOVERIES','RECOVERED').replace('DEATHS','DIED').replace('TOTAL','TOT')
// }
currentVar = convertToVar(currentVar)
// if( cVar != '_per_100kpop'){
// cVar = ""
// }
// if( cVar != ""){
// cVar = '_per_100kpop'
// }
currentKey = convertToColumnName(currentKey, currentVar)
// if( cVar != '_per_100kpop'){
// currentKey = 'NUM_' + d3.select(this).property("value");
// }
// run the updateChart function with this selected option
// updateMapColors()
console.log(currentVar)
console.log(currentKey)
Xupdate()
})
d3.select("#factorButton").on("change", function(q) {
// recover the option that has been chosen
currentVar = d3.select(this).property("value")
// run the updateChart function with this selected option
// updateMapColors()
console.log(currentVar)
currentVar = convertToVar(currentVar)
console.log(currentVar)
// if( cVar != '_per_100kpop'){
// cVar = "";
// }
console.log(currentKey)
currentKey = convertToColumnName(currentKey, currentVar)
// function revertCol(KEY) {
// if(KEY.includes('_per_100kpop')==false){ // time to add '_per_100kpop' at the end
// currentKey = revertCol(currentKey)
console.log(currentKey)
// console.log(cVar)
Xupdate()
})
});
});
/**
* Update the colors of the features on the map. Each feature is given a
* CSS class based on its value.
*/
function updateMapColors() {
// Set the domain of the values (the minimum and maximum values of
// all values of the current key) to the quantize scale.
quantize.domain([
d3.min(mapData, function(d) { return getValueOfData(d); }),
d3.max(mapData, function(d) { return getValueOfData(d); })
]);
// Update the class (determining the color) of the features.
mapFeatures.selectAll('path')
.attr('class', function(f) {
// Use the quantized value for the class
return quantize(getValueOfData(dataById[getIdOfFeature(f)]));
});
// We call the function to update the legend.
updateLegend();
}
/**
* Show the details of a feature in the details <div> container.
* The content is rendered with a Mustache template.
*
* @param {object} f - A GeoJSON Feature object.
*/
function showDetails(f) {
// Get the ID of the feature.
// console.log(f)
var id = getIdOfFeature(f);
console.log(id);
// Use the ID to get the data entry.
var d = dataById[id];
// console.log(d);
// Render the Mustache template with the data object and put the
// resulting HTML output in the details container.
var detailsHtml = Mustache.render(template, d);
// Hide the initial container.
d3.select('#initial').classed("hidden", true);
// Put the HTML output in the details container and show (unhide) it.
d3.select('#details').html(detailsHtml);
d3.select('#details').classed("hidden", false);
}
/**
* Hide the details <div> container and show the initial content instead.
*/
function hideDetails() {
// Hide the details
d3.select('#details').classed("hidden", true);
// Show the initial content
d3.select('#initial').classed("hidden", false);
}
/**
* Show a tooltip with the name of the feature.
*
* @param {object} f - A GeoJSON Feature object.
*/
function showTooltip(f) {
// Get the ID of the feature.
var id = getIdOfFeature(f);
// Use the ID to get the data entry.
var d = dataById[id];
console.log(d)
// Get the current mouse position (as integer)
var mouse = d3.mouse(d3.select('#map').node()).map(
function(d) { return parseInt(d); }
);
// Calculate the absolute left and top offsets of the tooltip. If the
// mouse is close to the right border of the map, show the tooltip on
// the left.
var left = Math.min(width - 4 * d.REGION_L.length, mouse[0] + 5);
var top = mouse[1] + 25;
// Show the tooltip (unhide it) and set the name of the data entry.
// Set the position as calculated before.
var formatDate0 = d3.time.format("%Y-%m-%d")
var formatDate1 = d3.time.format("%Y %b %d")
var formatDecimal = d3.format(".2f") // d3.format(".2f") if NOT per 100k; otherwise, d3.format(".0f")
const dateV = formatDate0.parse(d.DATE)
console.log(formatDate1(dateV))
tooltip.classed('hidden', false)
.attr("style", "left:" + left + "px; top:" + top + "px")
.html(d.REGION_L + "<br/><i>VALUE</i> (as of " + formatDate1(dateV) + "): " + formatDecimal(d[currentKey])); //
console.log(currentKey)
// div.html("<b>" + DateFormat(d.month) + "</b><br/> <i>actual</i> : " + d.mav.toFixed(0) + "<br/> <i>7-day MA</i> : " + d.count.toFixed(0))
// useful for d3 js v3: https://stackoverflow.com/questions/37774053/d3-function-to-parse-the-date-not-working
// ish (for d3 js v4) https://stackoverflow.com/questions/17721929/date-format-in-d3-js
}
/**
* Hide the tooltip.
*/
function hideTooltip() {
tooltip.classed('hidden', true);
}
/**
* Zoom the features on the map. This rescales the features on the map.
* Keep the stroke width proportional when zooming in.
*/
function doZoom() {
mapFeatures.attr("transform",
"translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")")
// Keep the stroke width proportional. The initial stroke width
// (0.5) must match the one set in the CSS.
.style("stroke-width", 0.5 / d3.event.scale + "px");
}
/**
* Calculate the scale factor and the center coordinates of a GeoJSON
* FeatureCollection. For the calculation, the height and width of the
* map container is needed.
*
* Thanks to: http://stackoverflow.com/a/17067379/841644
*
* @param {object} features - A GeoJSON FeatureCollection object
* containing a list of features.
*
* @return {object} An object containing the following attributes:
* - scale: The calculated scale factor.
* - center: A list of two coordinates marking the center.
*/
function calculateScaleCenter(features) {
// Get the bounding box of the paths (in pixels!) and calculate a
// scale factor based on the size of the bounding box and the map
// size.
var bbox_path = path.bounds(features),
scale = 0.95 / Math.max(
(bbox_path[1][0] - bbox_path[0][0]) / width,
(bbox_path[1][1] - bbox_path[0][1]) / height
);
// Get the bounding box of the features (in map units!) and use it
// to calculate the center of the features.
var bbox_feature = d3.geo.bounds(features),
center = [
(bbox_feature[1][0] + bbox_feature[0][0]) / 2,
(bbox_feature[1][1] + bbox_feature[0][1]) / 2];
return {
'scale': scale,
'center': center
};
}
/**
* Helper function to access the (current) value of a data object.
*
* Use "+" to convert text values to numbers.
*
* @param {object} d - A data object representing an entry (one line) of
* the data CSV.
*/
function getValueOfData(d) {
return +d[currentKey];
}
/**
* Helper function to retrieve the ID of a feature. The ID is found in
* the properties of the feature.
*
* @param {object} f - A GeoJSON Feature object.
*/
function getIdOfFeature(f) {
return f.properties.REGION;
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
// example data
var metricName = "cases";
// for this: increase bottom from 100 -> 150 (any value >100)
var margin = { top:50, right: 0, bottom: 120, left: 30 },
widthP = 630// 960 - margin.left - margin.right,
heightP = 430 - margin.top - margin.bottom,
gridSize = Math.floor(widthP / 24),
legendElementWidth = gridSize*2,
buckets = 9;
var optwidth = widthP // 800 //430 //300 //1000 //600;
var optheight = 390 // 450 //390 //400 //400//370;
// the length of a day/year in milliseconds
var day_in_ms = 86400000,
ms_in_year = 31540000000;
// var vis
////////////////////////////////////
////////////////////////////////////
////// crucial /////
////// dapat nasa labas ng loop ang svg and
///// select button to avoid
///// the dropdown list to add up
///// each time a choice is selected
var svgP = d3.select("#chart").append("svg")
.attr("width", widthP + margin.left + margin.right)
.attr("height", heightP + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
function getFname(dkey) {
return 'data/covid19ph/combi_' + dkey + '_daily_and_movAve_ph_covid19_stats_forDashboards_nWindow=7.csv'
// return 'data/' + dkey + '_data.csv'
} /// crucial!!!!!!!!
function plotF(f) {
// var plotF = function(csvFile) {
// var vis = 0
var id = getIdOfFeature(f)
console.log(id)
// console.log(csvFile)
cKey = convertToFileName(currentKey, currentVar)
console.log(cKey)
console.log(currentVar)
d3.csv(getFname(cKey), function(error, datasetInit) {
datasetInit.forEach(function(r) {
r.month = r.DATE;
r.mav = +r[currentKey];
r.count = +r['MA7_' + currentKey];
r.region = r.REGION_L;
});
// console.log(datasetInit)
// console.log(datasetInit[0])
// format month as a date
datasetInit = datasetInit.filter(function(q){return q.month!=""}) // temporary fix kase inaappend din niya yung header :(
datasetInit.forEach(function(d) {
d.month = d3.time.format("%Y-%m-%d").parse(d.month);
// d.month = d3.time.hour.offset(d.month, -3) // offset by 3 h; goal is to center the bar wrt to the scatter-line plot; https://stackoverflow.com/questions/20276173/how-to-define-custom-time-interval-in-d3-js
});
// sort datasetInit by month
datasetInit.sort(function(x, y){
return d3.ascending(x.month, y.month);
});
console.log(datasetInit)
dataset = datasetInit.filter(function(q){return q.region==id})
console.log(dataset)
// .datum(data.filter(function(d){return d.name==allGroup[0]}))
// a dataset without the null values is also needed to draw the missing data lines/areas
var dataset_no_null = dataset // dataset.filter(function(d) { return d.mav;}); //!== null; });
/*
* ========================================================================
* sizing
* ========================================================================
*/
/* === Focus chart === */
var margin = {top: 40, right: 30, bottom: 100, left: 20},
width = optwidth - margin.left - margin.right,
height = optheight - margin.top - margin.bottom;
/* === Context chart === */
var margin_context = {top: 320, right: 30, bottom: 20, left: 20},
height_context = optheight - margin_context.top - margin_context.bottom;
/*
* ========================================================================
* x and y coordinates
* ========================================================================
*/
// the date range of available data:
var lrangx = d3.extent(datasetInit, function(d) { return d.month; });
var maxLrangy = [];
maxLrangy.push(d3.max(dataset, function(d) { return d.count; }));
maxLrangy.push(d3.max(dataset, function(d) { return d.mav; }));
var minLrangy = [];
minLrangy.push(d3.min(dataset, function(d) { return d.count; })); // crucial!!!!!; to include negative values
// https://stackoverflow.com/questions/43855104/how-to-automatically-resize-d3-js-graph-to-include-axis
minLrangy.push(d3.min(dataset, function(d) { return d.mav; }));
// console.log([0, d3.max(lrangy)*1.])
var dataYrange = [d3.min(minLrangy)*1.3, d3.max(maxLrangy)*1.3];
console.log(dataYrange[0])
var dataXrange = []
// var dataXrange = [lrangx[0], lrangx[1]];
offsetMin = -1
offsetMax = 2
dataXrange.push(d3.time.day.offset(lrangx[0], offsetMin));
dataXrange.push(d3.time.day.offset(lrangx[1], offsetMax)); // in d3 js v4, it's d3.timeDay
// inspo from: https://stackoverflow.com/questions/45570438/how-to-modify-a-domain-dealing-with-dates-in-d3-js
console.log(lrangx)
console.log(dataXrange)
//////
if(dataYrange[1] < 10){
formatNumber = d3.format('.2f');
}
///////
/////////////////////
// add about a month to the end of the x range to show the last bar (which starts on the first of the month)
var x_full_extent = d3.extent(dataset, function(d) { return d.month; });//,
new_max_date = new Date(x_full_extent[1].getTime() + (day_in_ms * 24)),
x_full_extent = [x_full_extent[0], new_max_date];
// maximum date range allowed to display
formatter = d3.time.format("%Y-%m-%d");
var mindate = d3.time.hour.offset(dataXrange[0], -1*offsetMin*24 - offsetMin*24/4) // dataXrange[0], //formatter(d3.time.day.offset(dataXrange[0], 7)), // use the range of the data
maxdate = d3.time.hour.offset(dataXrange[1], -1*offsetMax*24 + offsetMax*24/4) // dataXrange[1] //formatter(d3.time.day.offset(dataXrange[1], -7));
// formatter(d3.time.day.offset(mindate, 3)); // Returns "2014-06-27" (and today is the 24th!)
// console.log(formatter(d3.time.day.offset(dataXrange[0], 0))) // https://stackoverflow.com/questions/24368109/storing-a-date-and-this-date-3-days-with-d3-js
var DateFormat = d3.time.format("%d %b %Y");
var dynamicDateFormat = timeFormat([
[d3.time.format("%Y"), function() { return true; }],// <-- how to display when Jan 1 YYYY
[d3.time.format("%b %Y"), function(d) { return d.getMonth(); }],
[function(){return "";}, function(d) { return d.getDate() != 1; }]
]);
/* === Focus Chart === */
var x = d3.time.scale()
.range([0, (widthP)])
// .domain([d3.time.hour.offset(dataXrange[0], -1*offsetMin*24 - 1*offsetMin*24/3), d3.time.hour.offset(dataXrange[1], -1*offsetMax*24 + offsetMax*24/4)]);
.domain(dataXrange);
console.log(x)
// var x = d3.scale.ordinal()
// .rangeBands([0, width], 0, 0.09)
// .domain(dataset.map(function(d){ return d.month}));
// The ordinal scale is used only for its `rangeBands` method, to automatially
// calculate the width of columns of column chart for details, see:
// https://stackoverflow.com/questions/12186366/d3-js-evenly-spaced-bars-on-a-time-scale
var x_ordinal = d3.scale.ordinal()
.rangeBands([0, widthP], 0, 200)
.domain(dataXrange)//(dataset.map(function(d){ return d.month}));
//// ^ from: https://bl.ocks.org/robyngit/981590aa194d930b22aa45cdba79beaf
var y = d3.scale.linear()
.range([heightP, 0])
.domain(dataYrange);
console.log(dataYrange)
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(-(heightP))
.ticks(customTickFunction)
// .ticks(5)
.tickFormat(dynamicDateFormat);
var yAxis = d3.svg.axis()
.scale(y)
.ticks(4)
.tickSize(-(widthP))
.orient("right");
/* === Context Chart === */
var x2 = d3.time.scale()
.range([0, widthP])
// .domain([mindate, maxdate]);
.domain(dataXrange);
var y2 = d3.scale.linear()
.range([height_context, 0])
.domain(y.domain());
console.log(y.domain())
var xAxis_context = d3.svg.axis()
.scale(x2)
.orient("bottom")
// .ticks(2) // update this to be adaptive!
.ticks(xcustomTickFunction)
// .tickFormat(cdynamicDateFormat);
// .tickFormat(d3.time.format("%b %Y"))
/*
* ========================================================================
* Plotted line and area variables
* ========================================================================
*/
/* === Focus Chart === */
var line = d3.svg.line()
.defined(function(d) { return d['count']!== null ; }) //!== null; }) --> crucial!!!!
// inspos from: https://stackoverflow.com/questions/54610592/how-to-continue-line-when-data-is-null-or-zero
// https://stackoverflow.com/questions/19221320/d3-line-defined-doesnt-draw-zero-value
.x(function(d) { return x(d.month); })
.y(function(d) { return y(d.mav); });
// .y(function(d) { return y(Math.max(0, d.mav)); });
var line_missing = d3.svg.line()
.x(function(d) { return x(d.month); })
.y(function(d) { return y(d.mav); });
/* === Context Chart === */
var line_context = d3.svg.line()
.defined(function(d) { return d.mav ; }) //!== null; })
.x(function(d) { return x2(d.month); })
// .y(function(d) { return y2(d.mav); });
// .y(function(d) { return y(d.mav); });
.y(function(d) { return y2(Math.max(0, d.mav)); });
var line_context_missing = d3.svg.line()
.x(function(d) { return x2(d.month); })
.y(function(d) { return y2(d.mav); });
/*
* ========================================================================
* Variables for brushing and zooming behaviour
* ========================================================================
*/
var brush = d3.svg.brush()
.x(x2)
.on("brush", brushed)
.on("brushend", brushend);
var zoom = d3.behavior.zoom()
.on("zoom", draw)
.on("zoomend", brushend);
/*
* ========================================================================
* Define the SVG area ("vis") and append all the layers
* ========================================================================