forked from LOSD-Data/docker-cube-visualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataCube_vis.js
More file actions
1574 lines (1337 loc) · 61.8 KB
/
Copy pathdataCube_vis.js
File metadata and controls
1574 lines (1337 loc) · 61.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var _metadata = null; //Will hold the dataset's metadata
var _measures = null; //API results for measures (object)
var _measureSelected = null; //Will hold the index of the selected measure
var _dimensions = null; //API results for dimensions (object)
var _freeDimension = null; //Will hold the index of the selected free dimension (for x axis)
var _dimensionsValues = []; //API results for dimension values (Array: one row for each dimension)
var _dimensionsValueSelected = null; //Will hold an array with the selected value per dimension [dim idx]=value idx
var _observations = []; //Will hold an array of observations with {label, value} pairs sorted by
// label in ascending order
var _ui = { //UI related switches and selections
'selectedChartType' : uiConfig.chartTypeInitiallySelected
};
var _dataLoaded = false; //Will be true only when there is any available data
var _datasets = null; //Will hold the datasets list
var _datasetsLoaded = false; //Will be true only when there is any available dataset
//On load page
$(function(){
configStaticUI();
$.when(getMeasures(prop.dataCubeURI), getDimensions(prop.dataCubeURI), getMetadata(prop.dataCubeURI))
.done (function() {
configUI_Title_Meas_Dim();
//Load Dimension Values after we've got the dimensions first
getDimensionValues(prop.dataCubeURI, _dimensions)
.done(function(){
//Populate & make dimension value selectors visible
configUI_DimsValues();
//Populate & make chart selector visible
configChartSelector();
//Load data and visualize
refreshData();
})
.fail(function(){
removeSelectionBar();
showErrorMessage(uiConfig.msg_loadingError);
});
})
.fail(function(){
showErrorMessage(uiConfig.msg_loadingError);
// try to list available Data Cubes and allow to navigate
removeSelectionBar();
getDatasets();
});
});
//----------- helper UI functions -----------------
//Enables spinner (loader)
function spinnerOn() {
if (!($("#loader").hasClass("spinning"))) {
$("#loader").addClass("spinning");
}
}
//Disables spinner (loader)
function spinnerOff() {
$("#loader").removeClass("spinning");
}
//Shows an error message under the spinner
function showErrorMessage(msg) {
$("#errorMessage").append("p")
.text(msg)
}
//Removes the error message
function removeErrorMessage() {
$("#errorMessage").empty();
}
//Shows selection bar
function showSelectionBar() {
$("#selectionBar").fadeIn();
}
//Removes selection bar
function removeSelectionBar() {
$("#selectionBar").fadeOut();
}
//Calls functions for getting appropriate data and for presenting them
function refreshData() {
//Disable the refresh button (to prevent multiple calls)
$("#refreshButton").attr("disabled", "disabled");
//During loading: disable all the input elements
disableUserInputElements();
removeErrorMessage(); // Remove error message if any
spinnerOn();
getTableRow(prop.dataCubeURI)
.then(function(){
//Set the flag ("there is data")
_dataLoaded = true;
//Create an appropriate visualization for the data
createVisualization();
})
.fail(function() {
showErrorMessage(uiConfig.msg_refreshDataError);
//Make the refresh button enabled
$("#refreshButton").removeAttr("disabled");
})
.always(function() {
spinnerOff();
enableUserInputElements();
});
}
//Disables all the selectors
function disableUserInputElements() {
$("#measureSelection").attr("disabled", "disabled");
$("#freeDimensionSelection").attr("disabled", "disabled");
$("#chartTypeSelection").attr("disabled", "disabled");
for (var d=0; d < _dimensions[ARJK.dimensions].length; d++) {
$("#dimValueSelection"+d).attr("disabled", "disabled");
}
}
//Enables all the selectors
function enableUserInputElements() {
$("#measureSelection").removeAttr("disabled");
$("#freeDimensionSelection").removeAttr("disabled");
$("#chartTypeSelection").removeAttr("disabled");
for (var d=0; d < _dimensions[ARJK.dimensions].length; d++) {
$("#dimValueSelection"+d).removeAttr("disabled");
}
}
function configStaticUI() {
//Enable the spinner
spinnerOn();
//Make the refresh button disabled
$("#refreshButton").attr("disabled", "disabled");
//Hide the refresh button
$("#refreshButton").addClass("hidden");
//Add the function to be called on click
$("#refreshButton").on("click", refreshData);
}
//Updates the top bar with the cube's name and also the measure and dimension selectors
function configUI_Title_Meas_Dim(){
//Set the navbar Title
$("#navbarTitle").append(_metadata[ARJK.label]);
//Set the browser's tab title
$("#tabTitle").append(_metadata[ARJK.label]);
//If there is no measured selected yet > default = 0
if (_measureSelected === null) {
_measureSelected = 0;
}
$("#measureSelection").empty();
d3.select("#measureSelection")
.attr('disabled', 'disabled') //initially disabled (until first automatic refresh)
.on("change", function() {
_measureSelected = $('#measureSelection').prop('selectedIndex');
//Make the refresh button enabled
$("#refreshButton").removeAttr("disabled");
})
.selectAll("option")
.data(_measures[ARJK.measures])
.enter()
.append("option")
.text(function (d) {return d[ARJK.label];})
.attr("value", function (d) { return d[ARJK.id]; });
//Set the selected option
$('#measureSelection').val(_measures[ARJK.measures][_measureSelected][ARJK.id]);
//Find the dimension that contains a preferred string (e.g. "time") as a first choice otherwise 0
if (_freeDimension === null) {
_freeDimension = 0; //default selection
//Search for the preferred dimension string
for (var j=0; j < _dimensions[ARJK.dimensions].length; j++) {
var label = _dimensions[ARJK.dimensions][j][ARJK.label];
label = label.toString().toLowerCase();
for (var k=0; k < preferredFreeDimensionString.length; k++) {
if (label.indexOf(preferredFreeDimensionString[k]) !== -1) {
_freeDimension = j;
}
}
}
}
$("#freeDimensionSelection").empty();
d3.select("#freeDimensionSelection")
.attr('disabled', 'disabled') //initially disabled (until first automatic refresh)
.on("change", function() {
_freeDimension = $('#freeDimensionSelection').prop('selectedIndex');
//Redraw dimension value selectors
dimValueSelectorsVisibility();
//Make the refresh button enabled
$("#refreshButton").removeAttr("disabled");
})
.selectAll("option")
.data(_dimensions[ARJK.dimensions])
.enter()
.append("option")
.text(function (d) {return d[ARJK.label];})
.attr("value", function (d) { return d[ARJK.id]; });
//Set the selected option
$('#freeDimensionSelection').val(_dimensions[ARJK.dimensions][_freeDimension][ARJK.id]);
}
//Updates the side bar with the dimension values selectors
function configUI_DimsValues() {
//Disable the spinner
spinnerOff();
$("#dimensionValuesSelections").empty();
//Check if this is the first time
var firstTime = false;
if (_dimensionsValueSelected === null) {
_dimensionsValueSelected = [];
firstTime = true;
}
for (var d=0; d < _dimensions[ARJK.dimensions].length; d++) {
//If first time > default values to selected values in each dimension (0 index)
if (firstTime) {
_dimensionsValueSelected[d] = 0;
}
var element = d3.select("#dimensionValuesSelections");
element.append("br")
.attr("id", "dimValueSelection"+d+"_br");
element.append("label")
.attr("for", "dimValueSelection"+d)
.attr("id", "dimValueSelection"+d+"_label")
.text(_dimensionsValues[d][ARJK.dimension][ARJK.label])
.attr("value", [ARJK.dimension][ARJK.id]);
element.append("select")
.attr("class", "form-control")
.attr('disabled', 'disabled') //initially disabled (until first automatic refresh)
.attr("id", "dimValueSelection"+d)
.attr("data-index", ""+d) //custom attribute for easy retrieval of dim. value selector index
.on("change", function() {
//Get the index of this selector to use it for the dim selected values array
var dimNo = parseInt(d3.select(this).attr("data-index"));
_dimensionsValueSelected[dimNo] = d3.select(this).property("selectedIndex");
//Enable the refresh button
$("#refreshButton").removeAttr("disabled");
});
d3.select("#dimValueSelection"+d)
.selectAll("option")
.data(_dimensionsValues[d][ARJK.values])
.enter()
.append("option")
.text(function (data) {return data[ARJK.label];})
.attr("value", function (data) { return data[ARJK.id]; });
}
dimValueSelectorsVisibility();
//
$("#refreshButton").removeClass("hidden");
}
function configChartSelector() {
$("#chartTypeSelection").empty();
d3.select("#chartTypeSelection")
.on("change", function() {
//Get the index of the selection from the drop down
_ui.selectedChartType = $('#chartTypeSelection').prop('selectedIndex');
if (_dataLoaded) { //only if data is loaded
createVisualization(); //on change > create immediately new chart (no data reloading needed)
}
})
.selectAll("option")
.data(uiConfig.chartTypes)
.enter()
.append("option")
.text(function (d) {return d;});
$('#chartTypeGroup').removeClass('hidden');
}
//Hides the selector for the dimension that is used as an axis (free dimension)
function dimValueSelectorsVisibility() {
for (var d=0; d < _dimensions[ARJK.dimensions].length; d++) {
$("#dimValueSelection"+d+"_label").removeClass("hidden");
$("#dimValueSelection"+d+"_br").removeClass("hidden");
$("#dimValueSelection"+d).removeClass("hidden");
//Remove from view the dimension that is used for x axis
if (d === _freeDimension) {
$("#dimValueSelection"+d+"_label").addClass("hidden");
$("#dimValueSelection"+d+"_br").addClass("hidden");
$("#dimValueSelection"+d).addClass("hidden");
}
}
}
//D3 visualization functions ---------------------------------------------------------------
function createVisualization() {
switch (_ui.selectedChartType) {
case 0:
createBarChartOrdinalX();
break;
case 1:
createPieChart(false);
break;
case 2:
createPieChart(true);
break;
case 3:
//The following code looks at the first dim value for time format compliance
var validDimension = false;
var sampleDimValue = _observations[0][CKEYS.dimLabel];
for (var k=0; k<timeFormats.length; k++) {
if (d3.timeParse(timeFormats[k])(sampleDimValue)) {
validDimension = true;
createAreaChartLinearX(timeFormats[k]);
break;
}
}
if (!validDimension) {
graphAlarm(uiConfig.msg_wrongChart);
}
break;
default:
createBarChartOrdinalX();
break;
}
}
//Clears the graph and presents an alarm in the graph area
function graphAlarm(alarmText) {
$("#graph").empty();
d3.select("#graph")
.append("p")
.attr('class', 'graphAlarm')
.text(alarmText);
}
function createAreaChartLinearX(timeFormatString) {
//Clear the graph
$("#graph").empty();
//------------------------------------------------------------------------------
//Calculate left margin according to max number of digits of y axis labels
var maxVal = d3.max(_observations, function(d) { return parseFloat(d[CKEYS.measObs]); });
maxVal = parseInt(maxVal);
var maxValLength = maxVal.toString().length;
var leftMargin = areaConfig.perLetterSpaceForYAxisLabels * maxValLength + 10; //10 + 8px per character
//------------------------------------------------------------------------------
//Find the min value
var minVal = d3.min(_observations, function(d) { return parseFloat(d[CKEYS.measObs]); });
if (minVal > 0) minVal = 0; //so that the graph is not biased
//If all values are 0, we increase the maxValue and so the scale is valid and axis has a 0 label
if (minVal === 0 && maxVal === 0) maxVal = 10;
//In case the max value is small (eg 2) the d3 js creates ticks with decimal values. In order to avoid that
//we check the max Value and if it is less that say 10, we create a suggestion for the number of ticks to d3
var ticksSpecificValue = null;
if (maxVal < 10) ticksSpecificValue = parseInt(maxVal); //ticksSpecificValue will be used in yAxis definition
//------------------------------------------------------------------------------
var margin = {
'top' : areaConfig.topMargin,
'right' : areaConfig.rightMargin,
'bottom': areaConfig.bottomMargin,
'left' : leftMargin
};
//Get the #graph div's width
var width = $('#graph').width() - margin.left - margin.right;
//Find the current browser window height (depends on zoom scale!)
// subtract the top of the graph element (dynamic), subtract the height of the footer (if any)
// and also subtract the two margins that are gonna be added later to the svg
var innerWindowHeight = $(window).height();
//getBoundingClientRect().top is relative to window
var graphTop = d3.select("#graph").node().getBoundingClientRect().top;
var height = innerWindowHeight - graphTop - uiConfig.footerSize - margin.top - margin.bottom;
//in case it is small or negative (eg mobile phone > of screen) retain a minimum height
if (height < areaConfig.areaChartMinHeight) {
height = areaConfig.areaChartMinHeight;
}
//Returns a function that parses dates
var parseDate = d3.timeParse(timeFormatString);
//test the parser
//Re-enable next piece of code in order to check all dim values for being compliant with time format
/*
for (var i=0; i<_observations.length; i++) {
if (!parseDate(_observations[i][CKEYS.dimLabel])) {
graphAlarm(uiConfig.msg_wrongChart);
return;
}
}
*/
//lineObservations will be used as data for the chart
var lineObservations = _observations
.filter(function(d) {
if (parseDate(d[CKEYS.dimLabel])) { //If it is a valid date / time
return true;
} else { //Else ignore data points with free dimension values that are not
return false; // valid dates (e.g 'unknown date').
}
})
.map(function(d) {
var obs = {};
obs['time'] = parseDate(d[CKEYS.dimLabel]); //Parse the date
obs['value'] = +d[CKEYS.measObs];
return obs;
});
//Sort array (otherwise time scale is not working correctly)
lineObservations.sort(function(a,b){
return new Date(b['time']) - new Date(a['time']);
});
var svg = d3.select("#graph")
.classed("bgr_vlgray", true)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top +margin.bottom);
//Create the clipping path (mask) for the filled area
svg.append("defs").append("clipPath")
.attr("id", "clipLine")
.append("rect")
.attr("width", width)
.attr("height", height);
//Create the clipping path (mask) for the data circles
svg.append("defs").append("clipPath")
.attr("id", "clipDataCircles")
.append("rect")
.attr("width", width + 2 * areaConfig.dataCircleRadius)
.attr("height", height + 2 * areaConfig.dataCircleRadius)
.attr("transform", "translate(" + (-areaConfig.dataCircleRadius) + ","
+ (-areaConfig.dataCircleRadius) + ")");
//Create scale functions
var xScale = d3.scaleTime()
.domain(d3.extent(lineObservations, function(d){
return d['time'];
}))
.range([0 , width ]);
var yScale = d3.scaleLinear()
.domain([minVal, maxVal])
.range([height, 0]);
//Calculate the max zoom according to the observations population
var maxZoom = _observations.length / areaConfig.populationToZoom_ratio;
var zoom = d3.zoom()
.scaleExtent([1,maxZoom])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", lineZoomed);
var area = d3.area()
.x(function(d) { return xScale(d['time']); })
.y0(height)
.y1(function(d) { return yScale(d['value']); });
var yAxis = d3.axisLeft()
.scale(yScale);
if (ticksSpecificValue) yAxis.ticks(ticksSpecificValue);
var xAxis = d3.axisBottom()
.scale(xScale)
//The following is needed especially when the scale is e.g just hours of a day
// and not a specific date (00:00 - 23:59). Then in order not to show the Tue 1/1/1900
// we have to format the axis according to the received dataset's format.
.ticks()
.tickFormat(d3.timeFormat(timeFormatString));
//Create a group
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
g.append("path")
.datum(lineObservations)
.attr("class", "area")
.attr("fill", areaConfig.fillColor)
.attr("clip-path", "url(#clipLine)")
.attr("d", area);
g.append("g")
.attr("class", "dataCircles")
.attr("clip-path", "url(#clipDataCircles)")
.selectAll("circle")
.data(lineObservations)
.enter()
.append("circle")
.attr("class", "dataCircle")
.attr("cx", function(d){
return xScale(d['time']);
})
.attr("cy", function(d) {
return yScale(d['value']);
})
.attr("r", areaConfig.dataCircleRadius)
.attr("fill", areaConfig.dataCircleColor)
//Add tooltip
.on("mouseover", function(d) {
//get this circle's x/y values, then adjust for the tooltip
var xPosition = parseFloat(d3.select(this).attr("cx")) + margin.left;
var yPosition = parseFloat(d3.select(this).attr("cy")) + margin.top;
//Create the tooltip label
var tooltip = svg.append("text")
.attr("id", "tooltip")
.attr("x", xPosition)
.attr("y", yPosition + areaConfig.tooltipLabelYOffset)
.attr("text-anchor", areaConfig.tooltipAnchor)
.attr("font-family", areaConfig.tooltipFontFamily)
.attr("font-size", areaConfig.tooltipFontSize);
tooltip.append("tspan")
.attr("class", "tooltipText tooltip_line1")
.attr("x", xPosition)
.attr("dy", 0)
.attr("fill", areaConfig.tooltipLabelColor)
.text(d3.timeFormat(timeFormatString)(d['time']) + areaConfig.tooltipLabelExtraText);
tooltip.append("tspan")
.attr("class", "tooltipText tooltip_line2")
.attr("x", xPosition)
.attr("dy", areaConfig.tooltipLineHeight)
.attr("fill", areaConfig.tooltipValueColor)
.text(d['value']);
var rectWidth = d3.select("#tooltip").node().getBBox().width + 2 * areaConfig.tooltipBackgroundMargin;
var rectHeight = d3.select("#tooltip").node().getBBox().height + 2 * areaConfig.tooltipBackgroundMargin;
var rect = svg.append("rect")
.attr("id", "tooltipBackground")
.attr("x", xPosition - rectWidth / 2)
.attr("y", yPosition - rectHeight / 2 + areaConfig.tooltipBackgroundMarginYOffset)
.attr("width", rectWidth)
.attr("height", rectHeight)
.style("fill", areaConfig.tooltipBackgroundColor)
.style("stroke", areaConfig.tooltipBackgroundStrokeColor);
d3.select("#tooltip").raise(); //Make it the last child of the svg (parent) so that is shows on top
})
.on("mouseout", function() {
//Remove the tooltip
d3.select("#tooltip").remove();
d3.select("#tooltipBackground").remove();
});
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll(".tick text")
.attr("fill", areaConfig.axisLabelColor);
g.append("g")
.attr("class", "axis axis--y")
.call(yAxis)
.selectAll(".tick text")
.attr("fill", areaConfig.axisLabelColor);
svg.call(zoom);
function lineZoomed() {
var t = d3.event.transform;
var xt = t.rescaleX(xScale);
g.select(".area").attr("d", area.x(function(d) { return xt(d['time']); }));
g.select(".dataCircles")
.selectAll("circle")
.attr("cx", function(d){
return xt(d['time']);
});
g.select(".axis--x").call(xAxis.scale(xt));
}
}
//Creates a bar chart with an ordinal x scale
function createBarChartOrdinalX() {
//Clear the graph
$("#graph").empty();
//------------------------------------------------------------------------------
//Calculate left margin according to max number of digits of y axis labels
var maxVal = d3.max(_observations, function(d) { return parseFloat(d[CKEYS.measObs]); });
maxVal = parseInt(maxVal);
var maxValLength = maxVal.toString().length;
var leftMargin =barConfig.perLetterSpaceForYAxisLabels * maxValLength + 10; //10 + 8px per character
//------------------------------------------------------------------------------
//Find the min value
var minVal = d3.min(_observations, function(d) { return parseFloat(d[CKEYS.measObs]); });
if (minVal > 0) minVal = 0; //so that the graph is not biased
//If all values are 0, we increase the maxValue and so the scale is valid and axis has a 0 label
if (minVal === 0 && maxVal === 0) maxVal = 10;
//In case the max value is small (eg 2) the d3 js creates ticks with decimal values. In order to avoid that
// we check the max Value and if it is less that say 10, we create a suggestion for the number of ticks to d3
var ticksSpecificValue = null;
if (maxVal < 10) ticksSpecificValue = parseInt(maxVal); //ticksSpecificValue will be used in yAxis definition
//------------------------------------------------------------------------------
var margin = {};
//Find the max x axis label's length
var maxXaxisLabelLength = d3.max(_observations, function(d) {return (d[CKEYS.dimLabel].length)});
//If length > threshold, create a test svg with rotated text (like those in x-axis) and measure its height
// from that change the bottom margin so that it can fit
var rotateXaxisLabels = false; //a flag that if true will make the x axis labels rotated
//Check that the length of x labels are larger than threshold.
// If yes create a dummy axis with rotated labels and measure its height > set this as bottom margin
if (maxXaxisLabelLength > barConfig.xLabelLengthTresholdForRotation) {
rotateXaxisLabels = true;
var testText = "";
//Create a dummy string with equal length as the 'maxXaxisLabelLength'
for (var c = 0; c < maxXaxisLabelLength ; c++) {
testText += "W";
}
var tempXScale = d3.scaleBand()
//Pass as the domain: an array with the labels
.domain(_observations.map(function(d) { return d[CKEYS.dimLabel]; }))
.range([0 , 500 ]); //arbitrary width
//Create a temp axis
var tempXAxis = d3.axisBottom()
.scale(tempXScale);
d3.select("#scratchSpace")
.append("svg")
.attr("class", "axis testText") //axis: so that the format is the same, hidden: so that is invisible
.call(tempXAxis)
.selectAll(".tick")
.selectAll("text")
.attr("fill", barConfig.axisLabelColor)
.style("text-anchor", "end")
.attr("dx", barConfig.xRotatedLabel_dx)
.attr("dy", barConfig.xRotatedLabel_dy)
.attr("transform", function(d) {
return "rotate(" + barConfig.xLabelRotationDegrees + ")";
});
//Calculate the height of the temporary axis
var xAxisHeight = d3.select(".testText").node().getBBox().height;
//Clear the element
$("#scratchSpace").empty();
//Clamp the height to the max allowed (see config)
if (xAxisHeight > barConfig.bottomMarginMax) {xAxisHeight = barConfig.bottomMarginMax;}
margin = {
'top': barConfig.topMargin,
'right': barConfig.rightMargin,
'bottom': xAxisHeight,
'left': leftMargin
};
} else {
rotateXaxisLabels = false;
//Set the margins (bottom is default, because labels are not going to be rotated
margin = {
'top': barConfig.topMargin,
'right': barConfig.rightMargin,
'bottom': barConfig.bottomMarginDefault,
'left': leftMargin
};
}
//------------------------------------------------------------------------------
//Get the #graph div's width
var width = $('#graph').width() - margin.left - margin.right;
//Find the current browser window height (depends on zoom scale!)
// and subtract the top of the graph element (dynamic), subtract the height of the footer (if any)
// and also subtract the two margins that are going to be added later to the svg
var innerWindowHeight = $(window).height();
//getBoundingClientRect().top is relative to window
var graphTop = d3.select("#graph").node().getBoundingClientRect().top;
var height = innerWindowHeight - graphTop - uiConfig.footerSize - margin.top - margin.bottom;
//In case it is small or negative (eg mobile phone > of screen) retain a minimum height
if (height < barConfig.barChartMinHeight) {
height = barConfig.barChartMinHeight;
}
var svg = d3.select("#graph")
.classed("bgr_vlgray", true)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top +margin.bottom);
//Create scale functions
var xScale = d3.scaleBand()
//Pass as the domain: an array with the labels
.domain(_observations.map(function(d) { return d[CKEYS.dimLabel]; }))
.range([0 , width ]) //rangeRound better for sharper graphics but pixel accuracy problem when many bars
.paddingInner(0.05); //the distance between bars (internally) - as a percentage
var yScale = d3.scaleLinear()
.domain([minVal, maxVal])
.range([height - 1, 0]); //height-1 so that value 0 is just a thin line
//Calculate the max zoom according to the observations population
var maxZoom = _observations.length / barConfig.populationToZoom_ratio;
var zoom = d3.zoom()
.scaleExtent([1,maxZoom])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
var yAxis = d3.axisLeft()
.scale(yScale);
if (ticksSpecificValue) yAxis.ticks(ticksSpecificValue);
var xAxis = d3.axisBottom()
.scale(xScale);
//Create the clipping path (mask) for the bars and labels
svg.append("defs").append("clipPath")
.attr("id", "clipBars")
.append("rect")
.attr("width", width)
.attr("height", height);
//Create the clipping path (mask) for the x axis
//x axis is just bellow the bars clipping mask, so needs a specific clipping mask (longer in y dim)
svg.append("defs").append("clipPath")
.attr("id", "clipXAxis")
.append("rect")
.attr("width", width)
.attr("height", height + margin.top + margin.bottom);
var gb = svg.append("g") //g will hold the bars
.attr("id", "barGroup")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr("clip-path", "url(#clipBars)"); //Apply the clip path
var gl = svg.append("g") //g will hold the value labels
.attr("id", "labelGroup")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr("clip-path", "url(#clipBars)"); //Apply the clip path
var ga = svg.append("g") //g2 will hold the x and y axis
.attr("id", "axesGroup")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//Depending on the bars width, this boolean will be used to hide value and x-axis labels
var hide = (xScale.bandwidth() < barConfig.minimumXBandwidthForLabels);
//Create bars
gb.selectAll("rect")
.data(_observations)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(d[CKEYS.dimLabel]);
})
.attr("y", function(d) {
return yScale(d[CKEYS.measObs]);
})
.attr("width", xScale.bandwidth())
.attr("height", function(d) {
return height - yScale(d[CKEYS.measObs]);
})
.attr("fill", function(d) {
return barConfig.barColor;
});
//The class valueLabel is important in order to distinguish these text(s) with the ones created
// automatically inside the axis
gl.selectAll("text.valueLabel")
.data(_observations)
.enter()
.append("text")
.text(function(d) {
return d[CKEYS.measObs];
})
.attr("class", "valueLabel")
.attr("x", function(d) {
return xScale(d[CKEYS.dimLabel]) + xScale.bandwidth() / 2 ; //centering the text
})
.attr("y", function(d) {
var y = yScale(d[CKEYS.measObs]) + barConfig.valueLabelYTransformation;
var thisElement = d3.select(this); //Get a reference to the current label
if ( y > height - 3 ) {
//If the label is going to cross the x axis, move it over the bar and change the color
y = yScale(d[CKEYS.measObs]) - 3; //
thisElement.attr("fill", barConfig.valueLabelFontColor_whenExternal);
} else {
thisElement.attr("fill", barConfig.valueLabelFontColor); //default color
}
return y;
})
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", barConfig.valueLabelFontSize);
gl.classed("hidden", hide); //Hide value labels if bar width is small
//Create Y axis
ga.append("g")
.attr("class", "axis axis--y") //The second class is for being able to separately call each axis
.call(yAxis)
.selectAll(".tick text")
.attr("fill", barConfig.axisLabelColor);
//Create X axis
ga.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")") //so that it goes to the bottom
.attr("clip-path", "url(#clipXAxis)") //Apply the clip path for the X Axis
.call(xAxis)
.selectAll(".tick") //Select all x axis ticks (containing also the label text)
.classed("hidden", hide) //if bar width small > hide them
.selectAll("text")
.attr("fill", barConfig.axisLabelColor);
//Rotate the text labels of x axis in case they are big
if (rotateXaxisLabels) {
ga.selectAll(".axis--x .tick")
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", barConfig.xRotatedLabel_dx)
.attr("dy", barConfig.xRotatedLabel_dy)
.attr("transform", function(d) {
return "rotate(" + barConfig.xLabelRotationDegrees + ")";
});
}
svg.call(zoom);
//IMP: Automatic zooming is valid only for continuous scales and not for ordinal
//IMP: So custom code was implemented
function zoomed() {
var t = d3.event.transform;
var hide = (xScale.bandwidth() < barConfig.minimumXBandwidthForLabels);
//t.k is the scale factor and t.x the movement along x axis
xScale.range([t.x, width*t.k + t.x]); //total range will always be t.k times the width
gb.selectAll("rect")
//.transition() //transition is good for zoom - not for pan
//.duration(200)
.attr("x", function(d, i) {
return xScale(d[CKEYS.dimLabel]);
})
.attr("width", xScale.bandwidth());
gl.selectAll("text.valueLabel")
.attr("x", function(d) {
return xScale(d[CKEYS.dimLabel]) + xScale.bandwidth() / 2 ; //centering the text
});
gl.classed("hidden", hide); //Hide value labels if bar width is small
ga.select(".axis--x")
.call(xAxis)
.selectAll(".tick") //Select all x axis ticks (containing also label text)
.classed("hidden", hide); //Hide them if bar width is small
}
}
//Parameter: sorting (true/false)
function createPieChart(sorting) {
var pieObservations = _observations.slice(); //Create a shallow copy of the object before sorting
var colorIndex = [];
//Add the original index as value to each object of the array
// This will be used for color consistency when changing from pie chart to sorted pie chart
// That means, we want the same colors for the same piece of data, independently of each position
// in the pie
pieObservations.forEach(function(value, index){
value['index'] = index;
});
if (sorting) {
pieObservations.sort(function(a,b) {
return b[CKEYS.measObs] - a[CKEYS.measObs];
});
}
//Populate color index array (for position n the value is the original index)
//This will be used for color consistency when changing from pie chart to sorted pie chart
var i = 0;
pieObservations.forEach(function(value){
colorIndex[i] = value['index'];
i++;
});
//Clear the graph
$("#graph").empty();
var margin = {
'left' : pieConfig.marginLeft,
'right' : pieConfig.marginRight,
'top' : pieConfig.marginTop,
'bottom' : pieConfig.marginBottom
};
//Create two responsive divs inside the container
//The padding is inherited form parent div
d3.select("#graph")
.append("div")
.attr("id", "pieDiv")
.classed("col-sm-9 col-xs-12", true);
d3.select("#graph")
.append("div")
.attr("id", "legendDiv")
.classed("col-sm-3 col-xs-12", true);
//The .width() method is not totally accurate due to responsive divs
// (it's close though) (innerWidth / outerWidth are not suitable: they include padding)
//Get the pie div's width and subtract the internal custom margins
var pieWidth = $("#pieDiv").width() - margin.left - margin.right;
//Find the current browser window height (depends on browser's zoom scale!)
// and subtract the top of the pie div (dynamic), subtract the height of the footer (if any)
// and also subtract the two margins that are gonna be added later to the svg
var innerWindowHeight = $(window).height();
var pieTop = d3.select("#pieDiv").node().getBoundingClientRect().top; //Distance to top of window
var pieHeight = innerWindowHeight - pieTop - uiConfig.footerSize - margin.top - margin.bottom;
//In case it is small or negative (eg mobile phone > of screen) retain a minimum height
if (pieHeight < pieConfig.pieChartMinimumHeight) {
pieHeight = pieConfig.pieChartMinimumHeight;
}
//In pie chart width is automatic (responsive design), so we should't intervene
/*
//Retain a minimum width
if (width < pieConfig.pieChartMinimumWidth) {
width = pieConfig.pieChartMinimumWidth;
}
*/
//Make the div containing the legend scrollable and fix the height (same as pie's svg)
//Its width is automatically set by bootstrap
$("#legendDiv")
.css({
overflowY: 'scroll',
overflowX: 'scroll',
maxHeight: pieHeight + margin.top + margin.bottom ,
height: pieHeight + margin.top + margin.bottom
});
//Find the smallest between width and height
var smallAxis = (pieWidth < pieHeight) ? pieWidth : pieHeight;
var outerRadius = smallAxis / 2;
var innerRadius = smallAxis / 4;
//arc generator (creates the svg path definition parameters)
var arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
//pie data transformer (finds angles)
var pie = d3.pie() //pie sorts the data by default
.sort(null) //Don't sort (sorts by default which is not needed since sorting is done manually
// in order to be able to sort also the legend labels!)
.value(function(d) { return d[CKEYS.measObs]; })(pieObservations);
//create the svg that will contain the pie elements
var pieSvg = d3.select("#pieDiv")
.classed("bgr_vlgray", true)
.append("svg")
.attr("width", pieWidth + margin.left + margin.right)
.attr("height", pieHeight + margin.top +margin.bottom);
//Create the svg that will contain the legend elements