-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1025 lines (827 loc) · 43.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>
<meta charset="utf-8">
<script src="d3.v3.min.js"></script>
<!--https://github.com/d3/d3-geo-projection/-->
<!--<script src="http://d3js.org/d3.geo.projection.v0.min.js" charset="utf-8"></script>-->
<script src="lib/d3.geo.projection.v0.min.js" charset="utf-8"></script>
<script src="lib/d3-legend.min.js"></script>
<script src="lib/jquery-1.10.2.min.js"></script>
<script src="lib/topojson.v1.min.js"></script>
<link href="lib/bootstrap.css" rel="stylesheet">
<script src="lib/bootstrap.min.js"></script>
<link href="lib/sticky-footer-navbar-orig.css" rel="stylesheet">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="lib/colorbrewer.js"></script>
<title>CO2 Fluxes</title>
<body>
<div id="wrap">
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">Anthropogenic CO2 Fluxes</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="sankeyView.html" target="_blank">Sankey View</a></li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
<!-- Begin page content -->
<div class="container">
<div id="infotext" style="width: 700px;"></div>
<div id="infotext2" style="width: 615px;"></div>
<div id="chart">
<ul class="nytg-sort" style='position: absolute; left: 770px; top: 130px;'>
<li id="mapButton">Reset</li>
</ul>
<!--<ul class="nytg-sort" style='position: absolute; left: 875px; top: 130px;'>
<li id="gridButton">Grid</li>
</ul>-->
<div id="legendDivTitle">
flux [mol C m<sup>-2</sup> yr<sup>-1</sup>]
</div>
<div id="legendDiv"></div>
</div>
<script src="sankey.js"></script>
<script>
var histfile = "orca05_absAnthroPerArea_TgPerYr_12june2016.tsv",
mapfile = "Continental_Shelf_mapshaper_1pc_marcatsid_10june2016.topojson",
continentsFile = "ne_110m_coastline.topojson",
gridFile = "marcat_orcat0.5_mar_mapshaper.topojson",
chartdiv = "Mchart",
mapdiv = "Mmap",
//formatX = d3.format("02d"), //for numbering countries in stackedbar x-axis
format = d3.format("5.2f"), //for tooltip values
units = "Tg C yr <sup>-1</sup>",
units_unitArea = "mol C m<sup>-2</sup> yr<sup>-1</sup>"
global_uptake = 100; //Tg
d3.select("#mapButton").style("display", "list-item").style("cursor", "auto");
//d3.select("#gridButton").style("display", "none");
plotHistogram(chartdiv, mapdiv);
function plotHistogram(chartdiv, mapdiv) {
d3.select("#infotext2").html("This stacked bar chart shows the anthropogenic carbon fluxes absorbed by MARCATS coastal regions per class <a href='http://dx.doi.org/10.5194/hess-17-2029-2013' target='_blank'>(Laruelle et al., 2013)</a>, weighted by surface area [Tg C yr <sup>-1</sup>], as calculated by our ORCA05 model. This model simulates an anthropogenic carbon uptake of 0.1 +/- 0.01 Pg C yr<sup>-1</sup> or 0.31 mol C m<sup>-2</sup> yr<sup>-1</sup> for the global coastal ocean, given as an average for years 1993 to 2012. See our publication <a href='http://dx.doi.org/10.5194/bg-13-4167-2016' target='_blank'>(Bourgeois et al., 2016)</a> for details." + "<br/>" + "<br/>" + "<p>" + "Hover over each stacked bar or map region to find the flux for the corresponding MARCATS region, as well as the flux per unit area [mol C m<sup>-2</sup> yr <sup>-1</sup>]." + "<br/>" + "<br/>" + "<p>")
.style("display", "block");
// http://www.d3noob.org/2013/01/adding-grid-lines-to-d3js-graph.html
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10)
}
var margin = {
top: 0,
right: 20,
bottom: 120,
left: 50
},
width = 600 - margin.left - margin.right,
height = 700 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
// Alphabetical Order of region names (Agulhas Current, Antarctic Shelves, etc.)
var marcat_colors = [
"#DAD1B4", "#084594", "#33B0CB", "#2171b5", "#A6AED4", "#bfd3e6",
"#ADB38D", "#C4D4D1", "#6baed6", "#f47461", "#5a5443", "#8c96c6",
"#AEC1BF", "#A09077", "#810f7c", "#8c96c6", "#2ca25f", "#ccece6",
"#88419d", "#66c2a4", "#F9D19C", "#420040", "#BFD0BB", "#C5B1AC",
"#8b0000", "#4292c6", "#c6dbef", "#9ebcda", "#99d8c9", "#e0ecf4",
"#8c6bb1", "#FFFBD3", "#5e195d", "#9ecae1", "#b81b34", "#9D928C",
"#FCD5D3", "#235CA6", "#006d2c", "#ffd59b", "#3C4055", "#ffa474",
"#db4551", "#ff8000", "#b3cde3"
];
// Dictionary for MARCATS regions: RCLASS
marcats_dict = {
"NorthEasternPacific": "1",
"CaliforniaCurrent": "2",
"TropicalEasternPacific": "3",
"PeruvianUpwellingCurrent": "4",
"SouthernAmerica": "5",
"BrazilianCurrent": "6",
"TropicalWesternAtlantic": "7",
"CaribbeanSea": "8",
"GulfofMexico": "9",
"FloridaUpwelling": "10",
"SeaofLabrador": "11",
"HudsonBay": "12",
"CanadianArchipelagos": "13",
"NorthernGreenland": "14",
"SouthernGreenland": "15",
"NorwegianBasin": "16",
"NorthEasternAtlantic": "17",
"BalticSea": "18",
"IberianUpwelling": "19",
"MediterraneanSea": "20",
"BlackSea": "21",
"MoroccanUpwelling": "22",
"TropicalEasternAtlantic": "23",
"SouthernWesternAfrica": "24",
"AgulhasCurrent": "25",
"TropicalWesternIndian": "26",
"WesternArabianSea": "27",
"RedSea": "28",
"PersianGulf": "29",
"EasternArabianSea": "30",
"BayofBengal": "31",
"TropicalEasternIndian": "32",
"LeeuwinCurrent": "33",
"SouthernAustralia": "34",
"EasternAustrialianCurrent": "35",
"NewZealand": "36",
"NorthernAustralia": "37",
"SouthEastAsia": "38",
"ChinaSea&Kuroshio": "39",
"SeaofJapan": "40",
"SeaofOkhotsk": "41",
"NorthWesternPacific": "42",
"SiberianShelves": "43",
"Barents&KaraSea": "44",
"AntarcticShelves": "45"
};
// Define marcats groups to select all map regions belonging to same class
var marcatsGroup, marcatsClass; //global var for mouseenter/mouseout on x-axis labels
var marcatsGroups_dict = {
"PolarMarcats": ".marcat-13, .marcat-14, .marcat-15, .marcat-18, .marcat-43, .marcat-44, .marcat-45",
"MarginalMarcats": ".marcat-9, .marcat-12, .marcat-16, .marcat-17, .marcat-20, .marcat-21, .marcat-28, .marcat-29, .marcat-40, .marcat-41",
"SubpolarMarcats": ".marcat-1, .marcat-5, .marcat-11, .marcat-34, .marcat-36, .marcat-42",
"TropicalMarcats": ".marcat-3, .marcat-7, .marcat-8, .marcat-23, .marcat-26, .marcat-37, .marcat-38",
"WBCMarcats": ".marcat-6, .marcat-10, .marcat-25, .marcat-35, .marcat-39",
"EBCMarcats": ".marcat-2, .marcat-4, .marcat-19, .marcat-22, .marcat-24, .marcat-33",
"IndianMarcats": ".marcat-27, .marcat-30, .marcat-31, .marcat-32"
};
var class_dict = {
"EBC": ".classCaliforniaCurrent, .classIberianUpwelling, .classLeeuwinCurrent, .classMoroccanUpwelling, .classPeruvianUpwellingCurrent, .classSouthernWesternAfrica",
"Indian margins": ".classBayofBengal, .classEasternArabianSea, .classTropicalEasternIndian, .classWesternArabianSea",
"WBC": ".classAgulhasCurrent, .classBrazilianCurrent, .classChinaSeaKuroshio, .classEasternAustrialianCurrent, .classFloridaUpwelling",
"Tropical": ".classCaribbeanSea, .classNorthernAustralia, .classSouthEastAsia, .classTropicalEasternAtlantic, .classTropicalEasternPacific, .classTropicalWesternAtlantic, .classTropicalWesternIndian",
"Subpolar": ".classNewZealand, .classNorthEasternPacific, .classNorthWesternPacific, .classSeaofLabrador, .classSouthernAmerica, .classSouthernAustralia",
"Marginal sea": ".classBalticSea, .classBlackSea, .classGulfofMexico, .classHudsonBay, .classMediterraneanSea, .classNorthEasternAtlantic, .classPersianGulf, .classRedSea, .classSeaofJapan, .classSeaofOkhotsk",
"Polar": ".classAntarcticShelves, .classBarentsKaraSea, .classCanadianArchipelagos, .classNorthernGreenland, .classNorwegianBasin, .classSiberianShelves, .classSouthernGreenland"
};
// To store total surface area flux of each class
var totalFlux_dict = {
"Polar": 0.0,
"Marginal sea": 0.0,
"Subpolar": 0.0,
"Tropical": 0.0,
"WBC": 0.0,
"EBC": 0.0,
"Indian margins": 0.0
}
var color = d3.scale.ordinal()
// .range([Coal_color, Oil_color, Gas_color, GasFlaring_color, Cement_color]);
.range(marcat_colors);
var active_bar = d3.select(null), //for mouseenter / mouseout on stacked bar
clicked_bar = d3.select(null), //for clicking stacked bar
outline = d3.select(null), //for outlining map on mouseover
outline_mapclick = d3.select(null); //for outlining map on map click
var globalg; //global g for paths
var zoomRegion = -999; //global var for region to zoom
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
//.tickFormat(d3.format(".2s"))
.tickFormat(d3.format(".2f"));
// append the chart div to <p id="chart">
var svg3 = d3.select("#chart").append("div").attr("id", chartdiv)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// add chart title
d3.select("#" + chartdiv)
.append("div")
.attr("class", "class_chartTitle")
.append("h4")
.append("foreignObject")
.html("Anthropogenic CO2 flux [Tg C yr<sup>-1</sup>]");
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
// Read in datafile for stacked bar chart
// ======================================
d3.tsv(histfile, function(error, data) {
if (error) throw error;
color.domain(d3.keys(data[0]).filter(function(key) {
if (key) {
//console.log("key: ", key)
return key !== "RCLASS"; //Region names
}
}));
data.forEach(function(d) {
var y0 = 0;
// Stack bars in order of value
//http://stackoverflow.com/questions/25253834/sorting-a-d3-js-stacked-bar-chart
var order = color.domain().map(function(d) {
return d;
})
.sort(function(a, b) {
return +d[b] - +d[a];
});
//d.sources = color.domain().map(function(name) {
d.sources = order.map(function(name) {
return {
country: d.RCLASS,
name: name,
y0: y0,
y1: y0 += +d[name],
value: d[name],
ycoord_corrected: 0
};
});
d.total = d.sources[d.sources.length - 1].y1;
});
// sort totals in descending order
data.sort(function(a, b) {
return b.total - a.total;
});
x.domain(data.map(function(d) {
return d.RCLASS;
}));
y.domain([0, d3.max(data, function(d) {
return d.total;
})]);
svg3.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text") //http://www.d3noob.org/2013/01/how-to-rotate-text-labels-for-x-axis-of.html
.text(function(d, i) {
//return d + " - " + formatX(i + 1);
return d;
})
.style("fill", "#2f2f2f")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", "rotate(-65)")
.on("mouseenter", function(d) { //hover over x-axis class labels
//console.log("orig font-weight: ", d3.select(this).style("font-weight"))
d3.select(this)
.style("cursor", "pointer")
.style("font-weight", "bold");
d3.select(".tooltip").style("display", "block");
marcatsGroup = d3.select(this).text().split(/\s+/)[0] + "Marcats";
// outline all marcats regions belonging to this class
d3.selectAll(marcatsGroups_dict[marcatsGroup]).classed("outline", true);
// outline all stacked bars in this class
marcatsClass = class_dict[d];
d3.selectAll(marcatsClass).classed("active_bar", true);
// tooltip
var class_uptake = totalFlux_dict[d];
div.transition().style("opacity", .9);
div.html(d + " (sum): " + "<br><br>" +
format(class_uptake) + " " + units + "<br>"
)
.style("left", (d3.event.pageX + 20) + "px")
.style("top", (d3.event.pageY - 20) + "px");
})
.on("mouseout", function(d) {
d3.select(this)
.style("font-weight", "400");
// remove outline on stacked bars and map regions
d3.selectAll(marcatsGroups_dict[marcatsGroup]).classed("outline", false);
d3.selectAll(marcatsClass).classed("active_bar", false);
});
svg3.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.style("font-size", "12px")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end");
//.text("Population");
svg3.append("g")
.attr("class", "grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat("")
)
// country nodes
var state = svg3.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", function(d) {
// tag g node of stacked bars with country name
return "g Country";
})
.attr("id", function(d) {
return "id_" + d.RCLASS.replace(/\s/g, '');
});
// country rects
height_diff = 0;
state.selectAll("rect")
.data(function(d) {
return d.sources;
})
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function(d) {
h_orig = y(d.y0) - y(d.y1); //based on stacked values (inaccurate)
h_correct = y(0) - y(d.value); //based on data value in csv file
height_diff = height_diff + h_orig - h_correct;
//correct y-coord
ycoord_corrected = y(d.y1) + height_diff;
d.ycoord_corrected = ycoord_corrected //store in d for later use in restorePlot()
if (d.name === "Cement") height_diff = 0; //reset for next set of stacked bars
return ycoord_corrected;
})
.attr("x", function(d) { //add to stock code
return x(d.country)
})
.attr("height", function(d) {
return y(0) - y(d.value); //heights calculated based on data value (accurate)
})
.attr("class", function(d) {
if (d.value != 0) {
classLabel = d.name.replace(/\s/g, '').replace(/&/g, ''); //remove spaces and '&'
areaFlux = d.value;
// calculate total surface area flux for each class
if (d.country === "Polar")
totalFlux_dict["Polar"] = parseFloat(totalFlux_dict["Polar"]) + parseFloat(d.value);
if (d.country === "Marginal sea")
totalFlux_dict["Marginal sea"] = parseFloat(totalFlux_dict["Marginal sea"]) + parseFloat(d.value);
if (d.country === "Subpolar")
totalFlux_dict["Subpolar"] = parseFloat(totalFlux_dict["Subpolar"]) + parseFloat(d.value);
if (d.country === "Tropical")
totalFlux_dict["Tropical"] = parseFloat(totalFlux_dict["Tropical"]) + parseFloat(d.value);
if (d.country === "WBC")
totalFlux_dict["WBC"] = parseFloat(totalFlux_dict["WBC"]) + parseFloat(d.value);
if (d.country === "EBC")
totalFlux_dict["EBC"] = parseFloat(totalFlux_dict["EBC"]) + parseFloat(d.value);
if (d.country === "Indian margins")
totalFlux_dict["Indian margins"] = parseFloat(totalFlux_dict["Indian margins"]) + parseFloat(d.value);
return "bars class" + classLabel + " areaflux-" + areaFlux;
}
})
.style("fill", function(d) {
//console.log("color(d.name): ", d.name +", "+ color(d.name))
return color(d.name);
});
// country rects event handlers
state.selectAll("rect")
.on("mouseenter", function(d) {
d3.select(this).style("cursor", "pointer");
d3.select(".tooltip").style("display", "block");
// outline clicked stacked bar
active_bar = d3.select(this).classed("active_bar", true);
// toggle active state of stacked bar to outline/de-outline it
// if (active_bar.node() === this) return reset_bar();
// active_bar.classed("active_bar", false);
// toolip. Get unitflux value stored in class of map region path
var this_class = d3.select(this).attr("class");
class_to_match = get_mapClass(this_class);
if (d3.select(this).style("opacity") != 0) {
var unitflux = d3.select(class_to_match).attr("class")
.split(/\s+/)[2].split("unitflux-").pop(),
class_uptake = totalFlux_dict[d.country];
var xPos = parseFloat(d3.select(this).attr("x"));
var yPos = parseFloat(d3.select(this).attr("y"));
var height = parseFloat(d3.select(this).attr("height"))
div.transition().style("opacity", .9);
div.html(d.country + ": " + d.name + "<br><br><b>" +
format(d.value) + " " + units + " (area flux)" + "</b>" +
"<br>" + format(unitflux) + " " + units_unitArea + " (unit flux)" +
"<br><br><b>" + format(d.value / class_uptake * 100) + "% of uptake in class" +
"<br>" + format(d.value / global_uptake * 100) + "% of global uptake" + "</b>")
.style("left", (d3.event.pageX + 20) + "px")
.style("top", (d3.event.pageY - 20) + "px");
}
// highlight corresponding areas on map
//fill_orig = d3.select(class_to_match).style("fill");
d3.selectAll(class_to_match)
.classed("outline", true);
})
.on("mouseout", function() {
var this_barRegion = marcats_dict[d3.select(this).attr("class").split(/\s+/)[1].split("class").pop()];
// remove outline on stacked bar if not clicked
if (this_barRegion != zoomRegion) reset_bar();
d3.select(this).style("cursor", "auto");
// remove tooltip display
div.transition().style("opacity", 0);
// restore map region to orig colour
d3.selectAll(class_to_match)
.classed("outline", false);
})
.on("click", function(d) {
d3.select(".tooltip").style("display", "block");
if (clicked_bar.node() === this && d3.select(this).classed("clicked_bar") === true) {
clicked_bar = d3.select(this).classed("clicked_bar", false);
clicked_bar = d3.select(null);
active_bar = d3.select(null);
return resetMap();
}
clicked_bar = d3.select(this).classed("clicked_bar", true);
d3.select("#mapButton").style("cursor", "pointer")
.classed("enabled", true);
// zoom corresponding map region
zoomRegion = parseInt(marcats_dict[d.name.replace(/\s/g, '')]);
plotMap();
// clear any previously clicked stacked bar
d3.selectAll(".active_bar")
.classed("active_bar", false)
.attr("stroke", null);
// outline clicked stacked bar
active_bar = d3.select(this).classed("active_bar", true);
});
function reset_bar() {
active_bar.classed("active_bar", false)
.attr("stroke", null);
active_bar = d3.select(null);
}
}); //d3.tsv(histfile)
//===================================================
//MAP
// Read in flux values per unit area
// ======================================
d3.tsv("orca05_absAnthroUnitArea_10june2016.tsv", function(error, unitdata) {
if (error) throw error;
// Create an array to store unit flux values, indexed by MARCATS_ID
var unit_dict = new Array();
unit_dict[0] = -999; //there is no MARCAT_ID = 0
// Store min and max unit flux values for map colourbar
var minflux = 99999,
maxflux = -99999;
unitdata.forEach(function(d) {
d.abs_anthro = +d.abs_anthro; //set to num
d.MARCATS_ID = +d.MARCATS_ID;
minflux = d.abs_anthro < minflux ? d.abs_anthro : minflux;
maxflux = d.abs_anthro > maxflux ? d.abs_anthro : maxflux;
unit_dict[d.MARCATS_ID] = d.abs_anthro;
});
// must use quantize http://stackoverflow.com/questions/26817035/colorbrewer-scale-only-returning-lightest-values-on-d3-map
// map legend with d3.Legend http://bl.ocks.org/syntagmatic/29bccce80df0f253c97e
var map_colourbar = d3.scale.quantize()
.domain([Math.floor(minflux), Math.ceil(maxflux)]) //0 - 1
.range(colorbrewer.Greys[6]);
plotMap(unit_dict, map_colourbar);
}) //end d3.tsv
function plotMap(unit_dict, map_colourbar) {
var unit_flux = [];
// append the mapdiv to <p id="chart">
var m_width = 960,
m_height = 700;
var projection = d3.geo.naturalEarth()
.translate([m_width / 2, m_height / 1.5]);
var path = d3.geo.path().projection(projection);
var t = projection.translate(); // the projection's default translation
var s = projection.scale(200) // the projection's default scale
console.log("t orig: ", t)
console.log("s orig: ", s)
var path = d3.geo.path()
.projection(projection);
var zoom = d3.behavior.zoom()
.on("zoom", zoomed);
//http://stackoverflow.com/questions/34556761/fixing-zoom-jump-when-scaling-map
//world map with zoom and pan: https://bl.ocks.org/d3noob/5189284
// reset map button
d3.select("#mapButton")
.on("click", function() {
return resetMap();
});
// Model layer, not interactive
d3.json("refs/" + gridFile, function(error, modelgrid) {
// Continent layer, not interactive
d3.json("refs/" + continentsFile, function(error, continent) {
// Continental Shelf layer, interactive
d3.json("refs/" + mapfile, function(error, us) {
if (error) throw error;
if (zoomRegion === -999) { //plot map for first time (no stacked bar clicked)
var svg4 = d3.select("#chart").append("div").attr("id", mapdiv)
.append("svg")
.attr("width", m_width + margin.left + margin.right)
.attr("height", m_height + margin.top + margin.bottom);
svg4.append("rect")
.attr("class", "background")
.attr("width", m_width)
.attr("height", m_height);
//.on("click", reset);
// svg4
// .call(zoom); // delete this line to disable free zooming
// ======================
// map legend
// http://d3-legend.susielu.com (from http://bl.ocks.org/syntagmatic/29bccce80df0f253c97e)
var svgLegend = d3.select("#legendDiv")
.append("svg")
.attr("width", 200).attr("height", 150);
svgLegend.append("g")
.attr("class", "legendQuant");
var legend = d3.legend.color()
.labelFormat(d3.format(".2f"))
.useClass(false) //if true, all boxes are black
.scale(map_colourbar);
svgLegend.select(".legendQuant")
.call(legend);
// Add thin border to legend boxes
d3.select(".legendCells")
.selectAll("rect")
.style("stroke", "black")
.style("stroke-width", ".25px");
// ======================
globalg = svg4.append("g")
.style("stroke-width", "1.5px");
// Continental shelf layer, interactive
globalg.selectAll("path.feature")
.data(topojson.feature(us, us.objects.Continental_Shelf).features)
.enter().append("path")
.attr("d", path)
.attr("class", function(d) {
// add abs anthro unit flux to class so stacked bar can get value
return "feature" +
" marcat-" + d.properties.MARCATS +
" unitflux-" + unit_dict[d.properties.MARCATS];
})
.style("fill", function(d, i) {
unit_flux[i] = unit_dict[d.properties.MARCATS];
return map_colourbar(unit_flux[i]);
})
.attr("id", function(d) {
return "id-" + d.properties.COSCAT;
})
//.attr("transform", "translate(0,-85)")
.on("mouseenter", function(d, i) {
d3.select(".tooltip").style("display", "block");
//outline all map regions of same MARCATS
outline.classed("outline", false);
var this_class = get_classFromPath(this);
outline = d3.selectAll(this_class).classed("outline", "true");
//outline corresponding stacked bar (and handle '&'' cases)
var matching_barClass = getKeyByValue(marcats_dict,
this_class.split("marcat-").pop());
if (matching_barClass === "Barents&KaraSea")
matching_barClass = "BarentsKaraSea";
else if (matching_barClass === "ChinaSea&Kuroshio")
matching_barClass = "ChinaSeaKuroshio";
d3.select(".class" + matching_barClass).classed("active_bar", true);
// tooltip
var marcats_num = d3.select(this).attr("class").split(/\s+/)[1].split("marcat-").pop()
var marcats_string = getKeyByValue(marcats_dict, marcats_num);
// Remove & to match class label
if (marcats_string === "Barents&KaraSea") marcats_string = "BarentsKaraSea";
else if (marcats_string === "ChinaSea&Kuroshio")
marcats_string = "ChinaSeaKuroshio";
if (d3.select(this).style("opacity") != 0) {
// Read areaflux stored in class of stackedbar
var areaflux = d3.select(".class" + marcats_string)
.attr("class")
.split(/\s+/)[2]
.split("areaflux-").pop();
var xPos = parseFloat(d3.select(this).attr("x"));
var yPos = parseFloat(d3.select(this).attr("y"));
var height = parseFloat(d3.select(this).attr("height"))
// Format to un-camelCase and insert & for two regions
var marcats_string_format = marcats_string.split(/(?=[A-Z])/).join(' ');
if (marcats_string_format === "Barents Kara Sea")
marcats_string_format = "Barents & Kara Sea";
else if (marcats_string_format === "China Sea Kuroshio")
marcats_string_format = "China Sea & Kuroshio";
else if (marcats_string_format === "Bayof Bengal")
marcats_string_format = "Bay of Bengal";
else if (marcats_string_format === "Gulfof Mexico")
marcats_string_format = "Gulf of Mexico";
else if (marcats_string_format === "Seaof Japan")
marcats_string_format = "Sea of Japan";
else if (marcats_string_format === "Seaof Labrador")
marcats_string_format = "Sea of Labrador";
else if (marcats_string_format === "Seaof Okhotsk")
marcats_string_format = "Sea of Okhotsk";
div.transition().style("opacity", .9);
div.html(marcats_string_format + ": " + "<br><br><b>" +
format(areaflux) + " " + units + " (area flux)" + "</b>" + "<br>" +
format(unit_flux[i]) + " " + units_unitArea + " (unit flux)")
.style("left", (d3.event.pageX + 20) + "px")
.style("top", (d3.event.pageY - 20) + "px");
}
})
.on("mouseout", function(d) {
d3.select(".tooltip").style("display", "none");
// remove outline of map regions
d3.selectAll(".outline").classed("outline", false);
// remove outline on stackedbar
d3.select(".active_bar").classed("active_bar", false);
})
.on("click", function(d) {
_this = this;
clicked(path, d, m_width, m_height, _this, modelgrid)
});
globalg.append("path")
.datum(topojson.mesh(us, us.objects.Continental_Shelf, function(a, b) {
return a !== b;
}))
.attr("class", "mesh")
.attr("d", path);
//==================================
// Continents only
// NB: must select path.subunit-boundary and not just .path, otherwise
// "d" will relate to the Continent object and not the Shelves (ruins zoom)
globalg.selectAll("path.subunit-boundary")
//.data(topojson.feature(continent, continent.objects.Continents).features) //for plates
.data(topojson.feature(continent, continent.objects.ne_110m_coastline).features)
.enter().append("path")
.attr("d", path)
.attr("class", "subunit-boundary");
globalg.append("path.subunit-boundary")
//.datum(topojson.mesh(continent, continent.objects.Continents, function(a, b) { //for plates
.datum(topojson.mesh(continent, continent.objects.ne_110m_coastline, function(a, b) {
return a !== b;
}))
.attr("class", "mesh")
.attr("d", path)
.attr("class", "subunit-boundary");
// //==================================
// // Model grid
// globalg.selectAll("path.orca-grid")
// .data(topojson.feature(modelgrid, modelgrid.objects.marcats).features)
// .enter().append("path")
// .attr("d", path)
// .attr("class", "orca-grid");
// //.style("display", "none");
// globalg.append("path.orca-grid")
// .datum(topojson.mesh(modelgrid, modelgrid.objects.marcats, function(a, b) {
// return a !== b;
// }))
// .attr("class", "mesh")
// .attr("d", path)
// .attr("class", "orca-grid");
// //.style("display", "none");
// //==================================
} else { //zoom region corresponding to clicked stacked bar
globalg.selectAll("path.feature")
.filter(function(d) {
if (d.properties && d.properties.MARCATS === zoomRegion) {
getBounds(path, d, m_width, m_height);
}
});
}
}); //end d3.json for Continental Shelf layer
}); //end d3.json for Continents layer
}); //end d3.json for model grid layer
// use to get reverse of marcats_dict dictionary
function getKeyByValue(hash, value) {
var key;
for (key in hash) {
if (hash[key] == value) return key;
}
}
function zoomed() {
//http://bl.ocks.org/biovisualize/2322933
// d3.event.translate (an array) stores the current translation from the parent SVG element
// t (an array) stores the projection's default translation
// we add the x and y vales in each array to determine the projection's new translation
var tx = t[0] * d3.event.scale + d3.event.translate[0];
var ty = t[1] * d3.event.scale + d3.event.translate[1];
projection.translate([tx, ty]);
// now we determine the projection's new scale, but there's a problem:
// the map doesn't 'zoom onto the mouse point'
projection.scale(s * d3.event.scale);
console.log("t now: ", t)
console.log("s now: ", s)
// redraw the map
//svg4.selectAll("path").attr("d", path);
//uk.selectAll("path").attr("d", path);
globalg.selectAll("path").attr("d", path);
}
} //end fn plotMap()
//=================
// Fns for map
function getBounds(path, d, m_width, m_height) {
var bounds = path.bounds(d),
dx = bounds[1][0] - bounds[0][0],
dy = bounds[1][1] - bounds[0][1],
x = (bounds[0][0] + bounds[1][0]) / 2,
y = (bounds[0][1] + bounds[1][1]) / 2,
scale = .2 / Math.max(dx / m_width, dy / m_height), //orig scale factor = .9
translate = [m_width / 2 - scale * x, m_height / 2 - scale * y];
globalg.transition()
.duration(750)
.style("stroke-width", 1.5 / scale + "px")
.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
//showGridButton();
}
function clicked(path, d, m_width, m_height, _this, modelgrid) {
var this_class = get_classFromPath(_this);
if (outline_mapclick.node() &&
get_classFromPath(outline_mapclick.node()) === get_classFromPath(_this)) {
return resetMap();
}
outline_mapclick.classed("outline_mapclick", false);
outline_mapclick = d3.selectAll(this_class).classed("outline_mapclick", true);
var bounds = path.bounds(d),
dx = bounds[1][0] - bounds[0][0],
dy = bounds[1][1] - bounds[0][1],
x = (bounds[0][0] + bounds[1][0]) / 2,
y = (bounds[0][1] + bounds[1][1]) / 2,
scale = .2 / Math.max(dx / m_width, dy / m_height), //orig scale factor = .9
translate = [m_width / 2 - scale * x, m_height / 2 - scale * y];
globalg.transition()
.duration(750)
.style("stroke-width", 1.5 / scale + "px")
.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
// .selectAll("path.orca-grid")
// .style("display", "inline");
d3.select("#mapButton").style("cursor", "pointer")
.classed("enabled", true);
//showGridButton();
}
// function showGridButton() {
// console.log("showGridButton")
// d3.select("#gridButton")
// .style("display", "list-item")
// .classed("enabled", true)
// .on("click", function (d) {
// if (d3.select(this).classed("selected")) {
// d3.select(this).classed("selected", false);
// console.log("toggle grid off")
// // // Toggle model grid off
// // globalg.selectAll("path.orca-grid")
// // .style("display", "none");
// }
// else {
// d3.select(this).classed("selected", true);
// console.log("toggle grid on")
// // Show model grid
// // globalg.selectAll("path.orca-grid")
// // .style("display", "inline");
// }
// });
// }
function resetMap() {
outline_mapclick.classed("outline_mapclick", false);
outline_mapclick = d3.select(null);
d3.selectAll(".outline_mapclick").classed("outline_mapclick", false)
zoomRegion = -999; //clear zoomRegion
globalg.transition()
.duration(750)
.style("stroke-width", "1.5px")
.attr("transform", "");
// .selectAll("path.orca-grid") //make drid visible
// .style("display", "none");
// clear outline of clicked stacked bar
d3.selectAll(".active_bar")
.classed("active_bar", false)
.attr("stroke", null);
// clear tooltip
d3.select(".tooltip").style("display", "none");
d3.select("#mapButton").style("cursor", "auto")
.classed("enabled", false);
//d3.select("#gridButton").style("display", "none");
}
} //end plotHistogram()
//=================
// General functions
function get_classFromPath(_this) { //get class from <path > element
var marcat_class = "." + d3.select(_this).attr("class").split(/\s+/)[1];
return marcat_class;
}
function get_mapClass(this_class) { //get class of map region corresponding to stacked bar
var classMarcats = this_class.split(/\s+/)[1];
if (classMarcats === "classBarentsKaraSea") classMarcats = "classBarents&KaraSea";
else if (classMarcats === "classChinaSeaKuroshio") classMarcats = "classChinaSea&Kuroshio";
var class_to_match = ".marcat-" + marcats_dict[classMarcats.split("class").pop()];
return class_to_match;
}
// hex_EBC = ["#C4D4D1", "#2ca25f", "#ccece6", "#66c2a4", "#99d8c9", "#006d2c"];
// hex_Polar = ["#7FA0FF", "#6baed6", "#2171b5", "#c6dbef", "#9ecae1", "#4292c6", "#084594"];
// function hexToRgb(hex) {
// var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
// return result ? {
// r: parseInt(result[1], 16),
// g: parseInt(result[2], 16),
// b: parseInt(result[3], 16)
// } : null;
// }
// function calc_L(hex) {
// var L = [];
// for (i=0; i<hex.length; i++) {
// var rgb = hexToRgb(hex[i]);