-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathplot.js
More file actions
3178 lines (2839 loc) · 150 KB
/
plot.js
File metadata and controls
3178 lines (2839 loc) · 150 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
/**
* @fileOverview
* @author <a href="https://www.labkey.org">LabKey</a> (<a href="mailto:info@labkey.com">info@labkey.com</a>)
* @license Copyright (c) 2012-2019 LabKey Corporation
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* <p/>
*/
/**
* @name LABKEY.vis.Plot
* @class Plot which allows a user to programmatically create a plot/visualization.
* @description
* @param {Object} config An object that contains the following properties.
* @param {String} config.renderTo The id of the div/span to insert the svg element into.
* @param {Number} config.width The plot width in pixels. This is the width of the entire plot, including margins, the
* legend, and labels.
* @param {Number} config.height The plot height in pixels. This is the height of the entire plot, including margins and
* labels.
* @param {Array} [config.data] (Optional) The array of data used while rendering the plot. This array will be used in
* layers that do not have any data specified. <em>Note:</em> While config.data is optional, if it is not present
* in the Plot object it must be defined within each {@link LABKEY.vis.Layer}. Data must be array based, with each
* row of data being an item in the array. The format of each row does not matter, you define how the data is
* accessed within the <strong>config.aes</strong> object.
* @param {Object} [config.aes] (Optional) An object containing all of the requested aesthetic mappings. Like
* <em>config.data</em>, config.aes is optional at the plot level because it can be defined at the layer level as
* well, however, if config.aes is not present at the plot level it must be defined within each
* {@link LABKEY.vis.Layer}}. The aesthetic mappings required depend entirely on the {@link LABKEY.vis.Geom}s being
* used in the plot. The only maps required are <strong><em>config.aes.x</em></strong> and
* <em><strong>config.aes.y</strong> (or alternatively yLeft or yRight)</em>. To find out the available aesthetic
* mappings for your plot, please see the documentation for each Geom you are using.
* @param {Array} config.layers An array of {@link LABKEY.vis.Layer} objects.
* @param {Object} [config.scales] (Optional) An object that describes the scales needed for each axis or dimension. If
* not defined by the user we do our best to create a default scale determined by the data given, however in some
* cases we will not be able to construct a scale, and we will display or throw an error. The possible scales are
* <strong>x</strong>, <strong>y (or yLeft)</strong>, <strong>yRight</strong>, <strong>color</strong>,
* <strong>shape</strong>, and <strong>size</strong>. Each scale object will have the following properties:
* <ul>
* <li><strong>scaleType:</strong> possible values "continuous" or "discrete".</li>
* <li><strong>trans:</strong> with values "linear" or "log". Controls the transformation of the data on
* the grid.</li>
* <li><strong>min:</strong> (<em>deprecated, use domain</em>) the minimum expected input value. Used to control what is visible on the grid.</li>
* <li><strong>max:</strong> (<em>deprecated, use domain</em>) the maximum expected input value. Used to control what is visible on the grid.</li>
* <li><strong>domain:</strong> For continuous scales it is an array of [min, max]. For discrete scales
* it is an an array of all possible input values to the scale.</li>
* <li><strong>range:</strong> An array of values that all input values (the domain) will be mapped to. Not
* used for any axis scales. For continuous color scales it is an array[min, max] hex values.</li>
* <li><strong>sortFn:</strong> If scaleType is "discrete", the sortFn can be used to order the values of the domain</li>
* <li><strong>tickFormat:</strong> Add axis label formatting.</li>
* <li><strong>tickValues:</strong> Define the axis tick values. Array of values.</li>
* <li><strong>tickDigits:</strong> Convert axis tick to exponential form if equal or greater than number of digits</li>
* <li><strong>tickMax:</strong> Maximum number of tick marks to show for an axis.</li>
* <li><strong>tickLabelMax:</strong> Maximum number of tick labels to show for a categorical axis.</li>
* <li><strong>tickHoverText:</strong>: Adds hover text for axis labels.</li>
* <li><strong>tickCls:</strong> Add class to axis label.</li>
* <li><strong>tickRectCls:</strong> Add class to mouse area rectangle around axis label.</li>
* <li><strong>tickRectHeightOffset:</strong> Set axis mouse area rect width. Offset beyond label text width.</li>
* <li><strong>tickRectWidthOffset:</strong> Set axis mouse area rect height. Offset beyond label text height.</li>
* <li><strong>tickClick:</strong> Handler for axis label click. Binds to mouse area rect around label.</li>
* <li><strong>tickMouseOver:</strong> Handler for axis label mouse over. Binds to mouse area rect around label.</li>
* <li><strong>tickMouseOut:</strong> Handler for axis label mouse out. Binds to mouse area rect around label.</li>
* </ul>
* @param {Object} [config.labels] (Optional) An object with the following properties: main, subtitle, x, y (or yLeft), yRight.
* Each property can have a {String} value, {Boolean} lookClickable, {Object} listeners, and other properties listed below.
* The value is the text that will appear on the label, lookClickable toggles if the label will appear clickable, and the
* listeners property allows the user to specify listeners on the labels such as click, hover, etc, as well as the functions to
* execute when the events occur. Each label will be an object that has the following properties:
* <ul>
* <li>
* <strong>value:</strong> The string value of the label (i.e. "Weight Over Time").
* </li>
* <li>
* <strong>fontSize:</strong> The font-size in pixels.
* </li>
* <li>
* <strong>position:</strong> The number of pixels from the edge to render the label.
* </li>
* <li>
* <strong>lookClickable:</strong> If true it styles the label so that it appears to be clickable. Defaults
* to false.
* </li>
* <li>
* <strong>visibility:</strong> The initial visibility state for the label. Defaults to normal.
* </li>
* <li>
* <strong>cls:</strong> Class added to label element.
* </li>
* <li>
* <strong>listeners:</strong> An object with properties for each listener the user wants attached
* to the label. The value of each property is the function to be called when the event occurs. The
* available listeners are: click, dblclick, hover, mousedown, mouseup, mousemove, mouseout, mouseover,
* touchcancel, touchend, touchmove, and touchstart.
* </li>
* </ul>
* @param {Object} [config.margins] (Optional) Margin sizes in pixels. It can be useful to set the margins if the tick
* marks on an axis are overlapping with your axis labels. Defaults to top: 75px, right: 75px, bottom: 50px, and
* left: 75px. The right side may have a margin of 150px if a legend is needed. Custom define margin size for a
* legend that exceeds 150px.
* The object may contain any of the following properties:
* <ul>
* <li><strong>top:</strong> Size of top margin in pixels.</li>
* <li><strong>bottom:</strong> Size of bottom margin in pixels.</li>
* <li><strong>left:</strong> Size of left margin in pixels.</li>
* <li><strong>right:</strong> Size of right margin in pixels.</li>
* </ul>
* @param {String} [config.legendPos] (Optional) Used to specify where the legend will render. Currently only supports
* "none" to disable the rendering of the legend. There are future plans to support "left" and "right" as well.
* Defaults to "right".
* @param {Boolean} [config.legendNoWrap] (Optional) True to force legend text in a single line.
* Defaults to false.
* @param {String} [config.bgColor] (Optional) The string representation of the background color. Defaults to white.
* @param {String} [config.gridColor] (Optional) The string representation of the grid color. Defaults to white.
* @param {String} [config.gridLineColor] (Optional) The string representation of the line colors used as part of the grid.
* Defaults to grey (#dddddd).
* @param {Boolean} [config.clipRect] (Optional) Used to toggle the use of a clipRect, which prevents values that appear
* outside of the specified grid area from being visible. Use of clipRect can negatively affect performance, do not
* use if there is a large amount of elements on the grid. Defaults to false.
* @param {String} [config.fontFamily] (Optional) Font-family to use for plot text (labels, legend, etc.).
* @param {Boolean} [config.throwErrors] (Optional) Used to toggle between the plot throwing errors or displaying errors.
* If true the plot will throw an error instead of displaying an error when necessary and possible. Defaults to
* false.
*
* @param {Boolean} [config.requireYLogGutter] (Optional) Used to indicate that the plot has non-positive data on x dimension
* that should be displayed in y log gutter in log scale.
* @param {Boolean} [config.requireXLogGutter] (Optional) Used to indicate that the plot has non-positive data on y dimension
* that should be displayed in x log gutter in log scale.
* @param {Boolean} [config.isMainPlot] (Optional) Used in combination with requireYLogGutter and requireXLogGutter to
* shift the main plot's axis position in order to show log gutters.
* @param {Boolean} [config.isShowYAxis] (Optional) Used to draw the Y axis to separate positive and negative values
* for log scale plot in the undefined X gutter plot.
* @param {Boolean} [config.isShowXAxis] (Optional) Used to draw the X axis to separate positive and negative values
* for log scale plot in the undefined Y gutter plot.
* @param {Float} [config.minXPositiveValue] (Optional) Used to adjust domains with non-positive lower bound and generate x axis
* log scale wrapper for plots that contain <= 0 x value.
* @param {Float} [config.minYPositiveValue] (Optional) Used to adjust domains with non-positive lower bound and generate y axis
* log scale wrapper for plots that contain <= 0 y value.
* @param {Object} [config.brushing] (Optional) Configuration for brushing events on the plot.
* The object may contain any of the following properties:
* <ul>
* <li><strong>brush:</strong> Callback function during the brush event.</li>
* <li><strong>brushclear:</strong> Callback function for when the brush event is cleared.</li>
* <li><strong>brushend:</strong> Callback function for when the brush event ends.</li>
* <li><strong>brushstart:</strong> Callback function for when the brush event starts.</li>
* </ul>
* @param {Array} [config.legendData] (Optional) An array of objects to be used for the plot legend. Each object can
* include the legend item text, color, and shape.
* @param {Object} [config.disableAxis] (Optional) Object indicating which plot axes to disable. Options include
* xTop, xBottom, yLeft, and yRight.
* @param {String} [config.gridLinesVisible] (Optional) String indicating if only the 'x' or 'y' axis grid lines
* should be shown for this plot. Default, without this property, is to show both x and y grid lines.
* @param {String} [config.tickColor] (Optional) The string representation of the color to use for the tick marks on
* the x and y axes. Defaults to black.
* @param {String} [config.borderColor] (Optional) The string representation of the color to use for the border (axes).
* Defaults to black.
* @param {String} [config.tickTextColor] (Optional) The string representation of the color to use for the x and y
* axis tick labels. Defaults to black.
* @param {Integer} [config.tickLength] (Optional) The length, in pixels for the x and y axis tick marks. Defaults to 8.
* @param {Integer} [config.tickWidth] (Optional) The x and y axis tick line width. Defaults to 1.
* @param {Integer} [config.tickOverlapRotation] (Optional) The degree of rotation for overlapping x axis tick labels.
* Defaults to 35 degrees.
* @param {Integer} [config.gridLineWidth] (Optional) The line width for the grid lines of the plot. Defaults to 1.
* @param {Integer} [config.borderWidth] (Optional) The border line width with the x and y axis. Defaults to 1.
*
@example
In this example we will create a simple scatter plot.
<div id='plot'>
</div id='plot'>
<script type="text/javascript">
var scatterData = [];
// Here we're creating some fake data to create a plot with.
for(var i = 0; i < 1000; i++){
var point = {
x: {value: parseInt((Math.random()*(150)))},
y: Math.random() * 1500
};
scatterData.push(point);
}
// Create a new layer object.
var pointLayer = new LABKEY.vis.Layer({
geom: new LABKEY.vis.Geom.Point()
});
// Create a new plot object.
var scatterPlot = new LABKEY.vis.Plot({
renderTo: 'plot',
width: 900,
height: 700,
data: scatterData,
layers: [pointLayer],
aes: {
// Aesthetic mappings can be functions or strings.
x: function(row){return row.x.value},
y: 'y'
}
});
scatterPlot.render();
</script>
@example
In this example we create a simple box plot.
<div id='plot'>
</div id='plot'>
<script type="text/javascript">
// First let's create some data.
var boxPlotData = [];
for(var i = 0; i < 6; i++){
var group = "Group "+(i+1);
for(var j = 0; j < 25; j++){
boxPlotData.push({
group: group,
//Compute a random age between 25 and 55
age: parseInt(25+(Math.random()*(55-25))),
gender: parseInt((Math.random()*2)) === 0 ? 'male' : 'female'
});
}
for(j = 0; j < 3; j++){
boxPlotData.push({
group: group,
//Compute a random age between 75 and 95
age: parseInt(75+(Math.random()*(95-75))),
gender: parseInt((Math.random()*2)) === 0 ? 'male' : 'female'
});
}
for(j = 0; j < 3; j++){
boxPlotData.push({
group: group,
//Compute a random age between 1 and 16
age: parseInt(1+(Math.random()*(16-1))),
gender: parseInt((Math.random()*2)) === 0 ? 'male' : 'female'
});
}
}
// Now we create the Layer.
var boxLayer = new LABKEY.vis.Layer({
geom: new LABKEY.vis.Geom.Boxplot({
// Customize the Boxplot Geom to fit our needs.
position: 'jitter',
outlierOpacity: '1',
outlierFill: 'red',
showOutliers: true,
opacity: '.5',
outlierColor: 'red'
}),
aes: {
hoverText: function(x, stats){
return x + ':\nMin: ' + stats.min + '\nMax: ' + stats.max + '\nQ1: ' +
stats.Q1 + '\nQ2: ' + stats.Q2 + '\nQ3: ' + stats.Q3;
},
outlierHoverText: function(row){
return "Group: " + row.group + ", Age: " + row.age;
},
outlierShape: function(row){return row.gender;}
}
});
// Create a new Plot object.
var boxPlot = new LABKEY.vis.Plot({
renderTo: 'plot',
width: 900,
height: 300,
labels: {
main: {value: 'Example Box Plot'},
yLeft: {value: 'Age'},
x: {value: 'Groups of People'}
},
data: boxPlotData,
layers: [boxLayer],
aes: {
yLeft: 'age',
x: 'group'
},
scales: {
x: {
scaleType: 'discrete'
},
yLeft: {
scaleType: 'continuous',
trans: 'linear'
}
},
margins: {
bottom: 75
}
});
boxPlot.render();
</script>
*/
(function(){
var initMargins = function(userMargins, legendPos, allAes, scales, labels){
var margins = {}, top = 75, right = 75, bottom = 50, left = 75; // Defaults.
var foundLegendScale = false, foundYRight = false;
for (var i = 0; i < allAes.length; i++){
var aes = allAes[i];
if (!foundLegendScale && (aes.shape || (aes.color && (!scales.color || (scales.color && scales.color.scaleType === 'discrete'))) || aes.outlierColor || aes.outlierShape || aes.pathColor) && legendPos !== 'none'){
foundLegendScale = true;
}
if (!foundYRight && aes.yRight){
foundYRight = true;
right = right + 25;
}
}
if (foundLegendScale) {
if (!legendPos || legendPos === 'right') {
right = right + 150;
} else if (legendPos === 'bottom') {
// The goal here is to net us space to render one item per color of our discrete color scale (8 items)
bottom = bottom += 170;
}
}
if(!userMargins){
userMargins = {};
}
if (typeof userMargins.top === 'undefined'){
margins.top = top + (labels && labels.subtitle ? 20 : 0);
} else {
margins.top = userMargins.top;
}
if (typeof userMargins.right === 'undefined'){
margins.right = right;
} else {
margins.right = userMargins.right;
}
if (typeof userMargins.bottom === 'undefined'){
margins.bottom = bottom;
} else {
margins.bottom = userMargins.bottom;
}
if (typeof userMargins.left === 'undefined'){
margins.left = left;
} else {
margins.left = userMargins.left;
}
return margins;
};
var initGridDimensions = function(grid, margins) {
grid.leftEdge = margins.left;
grid.rightEdge = grid.width - margins.right + 10;
grid.topEdge = margins.top;
grid.bottomEdge = grid.height - margins.bottom;
return grid;
};
var copyUserScales = function(origScales) {
// This copies the user's scales, but not the max/min because we don't want to over-write that, so we store the original
// scales separately (this.originalScales).
var scales = {}, newScaleName, origScale, newScale;
for (var scaleName in origScales) {
if (origScales.hasOwnProperty(scaleName)) {
if(scaleName == 'y'){
origScales.yLeft = origScales.y;
newScaleName = (scaleName == 'y') ? 'yLeft' : scaleName;
} else {
newScaleName = scaleName;
}
newScale = {};
origScale = origScales[scaleName];
newScale.scaleType = origScale.scaleType ? origScale.scaleType : 'continuous';
newScale.sortFn = origScale.sortFn ? origScale.sortFn : null;
newScale.trans = origScale.trans ? origScale.trans : 'linear';
newScale.tickValues = origScale.tickValues ? origScale.tickValues : null;
newScale.tickFormat = origScale.tickFormat ? origScale.tickFormat : null;
newScale.tickDigits = origScale.tickDigits ? origScale.tickDigits : null;
newScale.tickMax = origScale.tickMax ? origScale.tickMax : null;
newScale.tickLabelMax = origScale.tickLabelMax ? origScale.tickLabelMax : null;
newScale.tickHoverText = origScale.tickHoverText ? origScale.tickHoverText : null;
newScale.tickCls = origScale.tickCls ? origScale.tickCls : null;
newScale.tickRectCls = origScale.tickRectCls ? origScale.tickRectCls : null;
newScale.tickRectHeightOffset = origScale.tickRectHeightOffset ? origScale.tickRectHeightOffset : null;
newScale.tickRectWidthOffset = origScale.tickRectWidthOffset ? origScale.tickRectWidthOffset : null;
newScale.domain = origScale.domain ? origScale.domain : null;
newScale.range = origScale.range ? origScale.range : null;
newScale.fontSize = origScale.fontSize ? origScale.fontSize : null;
newScale.colorType = origScale.colorType ? origScale.colorType : null;
newScale.tickClick = origScale.tickClick ? origScale.tickClick : null;
newScale.tickMouseOver = origScale.tickMouseOver ? origScale.tickMouseOver : null;
newScale.tickMouseOut = origScale.tickMouseOut ? origScale.tickMouseOut : null;
if (!origScale.domain &&((origScale.hasOwnProperty('min') && LABKEY.vis.isValid(origScale.min)) ||
(origScale.hasOwnProperty('max') && LABKEY.vis.isValid(origScale.max)))) {
console.log('scale.min and scale.max are deprecated. Please use scale.domain.');
newScale.domain = [origScale.min, origScale.max];
origScale.domain = [origScale.min, origScale.max];
}
if (newScale.scaleType == 'ordinal' || newScale.scaleType == 'categorical') {
newScale.scaleType = 'discrete';
}
scales[newScaleName] = newScale;
}
}
return scales;
};
var setupDefaultScales = function(scales, aes) {
for (var aesthetic in aes) {
if (aes.hasOwnProperty(aesthetic)) {
if(!scales[aesthetic]){
// Not all aesthetics get a scale (like hoverText), so we have to be pretty specific.
if(aesthetic === 'x' || aesthetic === 'xTop' || aesthetic === 'xSub' || aesthetic === 'yLeft'
|| aesthetic === 'yRight' || aesthetic === 'size'){
scales[aesthetic] = {scaleType: 'continuous', trans: 'linear'};
} else if (aesthetic == 'color' || aesthetic == 'outlierColor' || aesthetic == 'pathColor') {
scales['color'] = {scaleType: 'discrete'};
} else if(aesthetic == 'shape' || aesthetic == 'outlierShape'){
scales['shape'] = {scaleType: 'discrete'};
}
}
}
}
};
var getDiscreteAxisDomain = function(data, acc) {
// If any axis is discrete we need to know the domain before rendering so we render the grid correctly.
var domain = [], uniques = {}, i, value;
for (i = 0; i < data.length; i++) {
value = acc(data[i]);
if (value != undefined)
uniques[value] = true;
}
for (value in uniques) {
if(uniques.hasOwnProperty(value)) {
domain.push(value);
}
}
return domain;
};
var getContinuousDomain = function(aesName, userScale, data, acc, errorAes) {
var userMin, userMax, min, max, minAcc, maxAcc;
if (userScale && userScale.domain) {
userMin = userScale.domain[0];
userMax = userScale.domain[1];
}
if (LABKEY.vis.isValid(userMin)) {
min = userMin;
} else {
if ((aesName == 'yLeft' || aesName == 'yRight') && errorAes) {
minAcc = function(d) {
if (LABKEY.vis.isValid(acc(d))) {
return acc(d) - errorAes.getValue(d);
}
else {
return null;
}
};
} else {
minAcc = acc;
}
min = d3.min(data, minAcc);
}
if (LABKEY.vis.isValid(userMax)) {
max = userMax;
} else {
if ((aesName == 'yLeft' || aesName == 'yRight') && errorAes) {
maxAcc = function(d) {
return acc(d) + errorAes.getValue(d);
}
} else {
maxAcc = acc;
}
max = d3.max(data, maxAcc);
}
if (min == max ) {
// use *2 and /2 so that we won't end up with <= 0 value for log scale
if (userScale && userScale.trans && userScale.trans === 'log') {
max = max * 2;
min = min / 2;
}
else {
max = max + 1;
min = min - 1;
}
}
// Keep time charts from getting in a bad state.
// They currently rely on us rendering an empty grid when there is an invalid x-axis.
if (isNaN(min) && isNaN(max)) {
return [0,0];
}
return [min, max];
};
var getDomain = function(aesName, userScale, scale, data, acc, errorAes) {
var tempDomain, curDomain = scale.domain, domain = [];
if (scale.scaleType == 'discrete') {
tempDomain = getDiscreteAxisDomain(data, acc);
if (scale.sortFn) {
tempDomain.sort(scale.sortFn);
}
if (!curDomain) {
return tempDomain;
}
for (var i = 0; i < tempDomain.length; i++) {
if (curDomain.indexOf(tempDomain[i]) == -1) {
curDomain.push(tempDomain[i]);
}
}
if (scale.sortFn) {
curDomain.sort(scale.sortFn);
}
return curDomain;
} else {
tempDomain = getContinuousDomain(aesName, userScale, data, acc, errorAes);
if (!curDomain) {
return tempDomain;
}
if (!LABKEY.vis.isValid(curDomain[0]) || tempDomain[0] < curDomain[0]) {
domain[0] = tempDomain[0];
} else {
domain[0] = curDomain[0];
}
if (!LABKEY.vis.isValid(curDomain[1]) || tempDomain[1] > curDomain[1]) {
domain[1] = tempDomain[1];
} else {
domain[1] = curDomain[1];
}
}
return domain;
};
var requiresDomain = function(name, colorScale) {
if (name == 'yLeft' || name == 'yRight' || name == 'x' || name == 'xTop' || name == 'xSub' || name == 'size') {
return true;
}
// We only need the domain of the a color scale if it's a continuous one.
return (name == 'color' || name == 'outlierColor') && colorScale && colorScale.scaleType == 'continuous';
};
var calculateDomains = function(userScales, scales, allAes, allData) {
var i, aesName, scale, userScale;
for (i = 0; i < allAes.length; i++) {
for (aesName in allAes[i]) {
if (allAes[i].hasOwnProperty(aesName) && requiresDomain(aesName, scales.color)) {
if (aesName == 'outlierColor') {
scale = scales.color;
userScale = userScales.color;
} else {
scale = scales[aesName];
userScale = userScales[aesName];
}
scale.domain = getDomain(aesName, userScale, scale, allData[i], allAes[i][aesName].getValue, allAes[i].error);
}
}
}
};
var getDefaultRange = function(scaleName, scale, userScale) {
if (scaleName == 'color' && scale.scaleType == 'continuous') {
return ['#222222', '#EEEEEE'];
}
if (scaleName == 'color' && scale.scaleType == 'discrete') {
var colorType = (userScale ? userScale.colorType : null) || scale.colorType;
if (LABKEY.vis.Scale[colorType])
return LABKEY.vis.Scale[colorType]();
else
return LABKEY.vis.Scale.ColorDiscrete();
}
if (scaleName == 'shape') {
return LABKEY.vis.Scale.Shape();
}
if (scaleName == 'size') {
return [1, 5];
}
return null;
};
var calculateAxisScaleRanges = function(scales, grid, margins) {
var yRange = [grid.bottomEdge, grid.topEdge];
if (scales.yRight) {
scales.yRight.range = yRange;
}
if (scales.yLeft) {
scales.yLeft.range = yRange;
}
var setXAxisRange = function(scale) {
if (scale.scaleType == 'continuous') {
scale.range = [margins.left, grid.width - margins.right];
}
else {
// We don't need extra padding in the discrete case because we use rangeBands which take care of that.
scale.range = [grid.leftEdge, grid.rightEdge];
}
};
if (scales.x) {
setXAxisRange(scales.x);
}
if (scales.xTop) {
setXAxisRange(scales.xTop);
}
if (scales.xSub) {
setXAxisRange(scales.xSub);
}
};
var getLogScale = function (domain, range, minPositiveValue) {
var scale, scaleWrapper, increment = 0;
// Issue 24727: adjust domain range to compensate for log scale fitting error margin
// With log scale, log transformation is applied before the mapping (fitting) to result range
// Javascript has binary floating points calculation issues. Use a small error constant to compensate.
var scaleRoundingEpsilon = 0.0001 * 0.5; // divide by half so that <= 0 value can be distinguished from > 0 value
if (minPositiveValue) {
scaleRoundingEpsilon = minPositiveValue * getLogDomainLowerBoundRatio(domain, range, minPositiveValue);
}
// domain must not include or cross zero
if (domain[0] <= scaleRoundingEpsilon) {
// Issue 24967: incrementing domain is causing issue with brushing extent
// Ideally we'd increment as little as possible
increment = scaleRoundingEpsilon - domain[0];
domain[0] = domain[0] + increment;
domain[1] = domain[1] + increment;
}
else {
domain[0] = domain[0] - scaleRoundingEpsilon;
domain[1] = domain[1] + scaleRoundingEpsilon;
}
scale = d3.scale.log().domain(domain).range(range);
scaleWrapper = function(val) {
if(val != null) {
if (increment > 0 && val <= scaleRoundingEpsilon) {
// <= 0 points are now part of the main plot, it's illegal to pass negative value to a log scale with positive domain.
// Since we don't care about the relative values of those gutter data, we can use domain's lower bound for all <=0 as a mock
return scale(scaleRoundingEpsilon);
}
// use the original value to calculate the scaled value for all > 0 data
return scale(val);
}
return null;
};
scaleWrapper.domain = scale.domain;
scaleWrapper.range = scale.range;
scaleWrapper.invert = scale.invert;
scaleWrapper.base = scale.base;
scaleWrapper.clamp = scale.clamp;
scaleWrapper.ticks = function(){
var allTicks = scale.ticks();
var ticksToShow = [];
if (allTicks.length < 2) {
//make sure that at least 2 tick marks are shown for reference
// skip rounding down if rounds down to 0, which is not allowed for log
return [Math.ceil(scale.domain()[0]), Math.abs(scale.domain()[1]) < 1 ? scale.domain()[1] : Math.floor(scale.domain()[1])];
}
else if(allTicks.length < 10){
return allTicks;
}
else {
for(var i = 0; i < allTicks.length; i++){
if(i % 9 == 0){
ticksToShow.push(allTicks[i]);
}
}
return ticksToShow;
}
};
return scaleWrapper;
};
// The lower domain bound need to adjusted to so that enough space is reserved for log gutter.
// The calculation takes into account the available plot size (range), max and min values (domain) in the plot.
var getLogDomainLowerBoundRatio = function(domain, range, minPositiveValue) {
// use 0.5 as a base ratio, so that plot distributions on edge grids are not skewed
var ratio = 0.5, logGutterSize = 30;
var gridNum = Math.ceil(Math.log(domain[1] / minPositiveValue)); // the number of axis ticks, equals order of magnitude diff of positive domain range
var rangeOrder = Math.floor(Math.abs(range[1] - range[0]) / logGutterSize) + 1; // calculate max allowed grid number, assuming each grid is at least log gutter size
if (gridNum > rangeOrder) {
for (var i = 0; i < gridNum - rangeOrder; i++) {
ratio *= 0.5;
}
}
else{
var gridSize = Math.abs(range[1] - range[0]) / gridNum; // the actual grid size of each grid
// adjust ratio so that positive data won't fall into log gutter area
if (gridSize/2 < logGutterSize){
ratio = 1 - logGutterSize/gridSize;
}
}
return ratio;
};
var instantiateScales = function(plot, margins) {
var userScales = plot.originalScales, scales = plot.scales, grid = plot.grid, isMainPlot = plot.isMainPlot,
xLogGutter = plot.xLogGutter, yLogGutter = plot.yLogGutter, minXPositiveValue = plot.minXPositiveValue, minYPositiveValue = plot.minYPositiveValue;
var scaleName, scale, userScale;
calculateAxisScaleRanges(scales, grid, margins);
if (isMainPlot) {
// adjust the plot range to reserve space for log gutter
var mainPlotRangeAdjustment = 30;
if (xLogGutter) {
if (scales.yLeft && Ext.isArray(scales.yLeft.range)) {
scales.yLeft.range = [scales.yLeft.range[0] + mainPlotRangeAdjustment, scales.yLeft.range[1]];
}
}
if (yLogGutter) {
if (scales.x && Ext.isArray(scales.x.range)) {
scales.x.range = [scales.x.range[0] - mainPlotRangeAdjustment, scales.x.range[1]];
}
}
}
for (scaleName in scales) {
if (scales.hasOwnProperty(scaleName)) {
scale = scales[scaleName];
userScale = userScales[scaleName];
if (scale.scaleType == 'discrete') {
if (scaleName == 'x' || scaleName == 'xTop' || scaleName == 'xSub' || scaleName == 'yLeft' || scaleName == 'yRight'){
// Setup scale with domain (user provided or calculated) and compute range based off grid dimensions.
scale.scale = d3.scale.ordinal().domain(scale.domain).rangeBands(scale.range, 1);
} else {
// Setup scales with user provided range or default range.
if (userScale && userScale.scale) {
scale.scale = userScale.scale;
}
else {
scale.scale = d3.scale.ordinal();
}
if (scale.domain) {
scale.scale.domain(scale.domain);
}
if (!scale.range) {
scale.range = getDefaultRange(scaleName, scale, userScale);
}
if (scale.scale.range) {
scale.scale.range(scale.range);
}
}
} else {
if ((scaleName == 'color' || scaleName == 'size') && !scale.range) {
scale.range = getDefaultRange(scaleName, scale, userScale);
}
if (scale.range && scale.domain && LABKEY.vis.isValid(scale.domain[0]) && LABKEY.vis.isValid(scale.domain[1])) {
if (scale.trans == 'linear') {
scale.scale = d3.scale.linear().domain(scale.domain).range(scale.range);
} else {
if (scaleName == 'x' || scaleName == 'xTop') {
scale.scale = getLogScale(scale.domain, scale.range, minXPositiveValue);
}
else {
scale.scale = getLogScale(scale.domain, scale.range, minYPositiveValue);
}
}
}
}
}
}
};
var initializeScales = function(plot, allAes, allData, margins, errorFn) {
var userScales = plot.originalScales, scales = plot.scales;
for (var i = 0; i < allAes.length; i++) {
setupDefaultScales(scales, allAes[i]);
}
for (var scaleName in scales) {
if(scales.hasOwnProperty(scaleName)) {
if (scales[scaleName].scale) {
delete scales[scaleName].scale;
}
if (scales[scaleName].domain && (userScales[scaleName] && !userScales[scaleName].domain)) {
delete scales[scaleName].domain;
}
if (scales[scaleName].range && (userScales[scaleName] && !userScales[scaleName].range)) {
delete scales[scaleName].range;
}
}
}
calculateDomains(userScales, scales, allAes, allData);
instantiateScales(plot, margins);
if ((scales.x && !scales.x.scale) || (scales.xTop && !scales.xTop.scale)) {
errorFn('Unable to create an x scale, rendering aborted.');
return false;
}
if((!scales.yLeft || !scales.yLeft.scale) && (!scales.yRight ||!scales.yRight.scale)){
errorFn('Unable to create a y scale, rendering aborted.');
return false;
}
return true;
};
var compareDomains = function(domain1, domain2){
if(domain1.length != domain2.length){
return false;
}
domain1.sort();
domain2.sort();
for(var i = 0; i < domain1.length; i++){
if(domain1[i] != domain2[i]) {
return false;
}
}
return true;
};
var generateLegendData = function(legendData, domain, colorFn, shapeFn){
for(var i = 0; i < domain.length; i++) {
legendData.push({
text: domain[i],
color: colorFn != null ? colorFn(domain[i]) : null,
shape: shapeFn != null ? shapeFn(domain[i]) : null
});
}
};
LABKEY.vis.Plot = function(config){
this.yLogGutter = config.requireYLogGutter ? true : false;
this.xLogGutter = config.requireXLogGutter ? true : false;
this.isMainPlot = config.isMainPlot ? true : false;
this.isShowYAxisGutter = config.isShowYAxis ? true : false;
this.isShowXAxisGutter = config.isShowXAxis ? true : false;
this.minXPositiveValue = config.minXPositiveValue;
this.minYPositiveValue = config.minYPositiveValue;
this.renderer = new LABKEY.vis.internal.D3Renderer(this);
var error = function(msg){
if (this.throwErrors){
throw new Error(msg);
} else {
console.error(msg);
if(console.trace){
console.trace();
}
this.renderer.renderError(msg);
}
};
this.renderTo = config.renderTo ? config.renderTo : null; // The id of the DOM element to render the plot to, required.
this.grid = {
width: config.hasOwnProperty('width') ? config.width : null, // height of the grid where shapes/lines/etc gets plotted.
height: config.hasOwnProperty('height') ? config.height: null // widht of the grid.
};
this.originalScales = config.scales ? config.scales : {}; // The scales specified by the user.
this.scales = copyUserScales(this.originalScales); // The scales used internally.
this.originalAes = config.aes ? config.aes : null; // The original aesthetic specified by the user.
this.aes = LABKEY.vis.convertAes(this.originalAes); // The aesthetic object used internally.
this.labels = config.labels ? config.labels : {};
this.data = config.data ? config.data : null; // An array of rows, required. Each row could have several pieces of data. (e.g. {subjectId: '249534596', hemoglobin: '350', CD4:'1400', day:'120'})
this.layers = config.layers ? config.layers : []; // An array of layers, required. (e.g. a layer for a CD4 line chart over time, and a layer for a Hemoglobin line chart over time).
this.clipRect = config.clipRect ? config.clipRect : false;
this.legendPos = config.legendPos ?? 'right';
this.legendNoWrap = config.legendNoWrap;
this.throwErrors = config.throwErrors || false; // Allows the configuration to specify whether chart errors should be thrown or logged (default).
this.brushing = ('brushing' in config && config.brushing != null && config.brushing != undefined) ? config.brushing : null;
this.legendData = config.legendData ? config.legendData : null; // An array of rows for the legend text/color/etc. Optional.
this.disableAxis = config.disableAxis ? config.disableAxis : {xTop: false, xBottom: false, yLeft: false, yRight: false};
this.bgColor = config.bgColor ? config.bgColor : null;
this.gridColor = config.gridColor ? config.gridColor : null;
this.gridLineColor = config.gridLineColor ? config.gridLineColor : null;
this.gridLinesVisible = config.gridLinesVisible ? config.gridLinesVisible : null;
this.fontFamily = config.fontFamily ? config.fontFamily : null;
this.tickColor = config.tickColor ? config.tickColor : null;
this.borderColor = config.borderColor ? config.borderColor : null;
this.tickTextColor = config.tickTextColor ? config.tickTextColor : null;
this.tickLength = config.hasOwnProperty('tickLength') ? config.tickLength : null;
this.tickWidth = config.hasOwnProperty('tickWidth') ? config.tickWidth : null;
this.tickOverlapRotation = config.hasOwnProperty('tickOverlapRotation') ? config.tickOverlapRotation : null;
this.gridLineWidth = config.hasOwnProperty('gridLineWidth') ? config.gridLineWidth : null;
this.borderWidth = config.hasOwnProperty('borderWidth') ? config.borderWidth : null;
// Stash the user's margins so when we re-configure margins during re-renders or setAes we don't forget the user's settings.
var allAes = [], margins = {}, userMargins = config.margins ? config.margins : {};
allAes.push(this.aes);
for(var i = 0; i < this.layers.length; i++){
if(this.layers[i].aes){
allAes.push(this.layers[i].aes);
}
}
if(this.labels.y){
this.labels.yLeft = this.labels.y;
this.labels.y = null;
}
if(this.grid.width == null){
error.call(this, "Unable to create plot, width not specified");
return;
}
if(this.grid.height == null){
error.call(this, "Unable to create plot, height not specified");
return;
}
if(this.renderTo == null){
error.call(this, "Unable to create plot, renderTo not specified");
return;
}
for(var aesthetic in this.aes){
if (this.aes.hasOwnProperty(aesthetic)) {
LABKEY.vis.createGetter(this.aes[aesthetic]);
}
}
this.getLegendData = function(){
var legendData = [];
if ((this.scales.color && this.scales.color.scaleType === 'discrete') && this.scales.shape) {
if(compareDomains(this.scales.color.scale.domain(), this.scales.shape.scale.domain())){
// The color and shape domains are the same. Merge them in the legend.
generateLegendData(legendData, this.scales.color.scale.domain(), this.scales.color.scale, this.scales.shape.scale);
} else {
// The color and shape domains are different.
generateLegendData(legendData, this.scales.color.scale.domain(), this.scales.color.scale, null);
generateLegendData(legendData, this.scales.shape.scale.domain(), null, this.scales.shape.scale);
}
} else if(this.scales.color && this.scales.color.scaleType === 'discrete') {
generateLegendData(legendData, this.scales.color.scale.domain(), this.scales.color.scale, null);