-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathchart-lib.js
1282 lines (1155 loc) · 43 KB
/
chart-lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
({
requires: [
{ 'import-type': 'builtin', 'name': 'image-lib' },
],
nativeRequires: [
'pyret-base/js/js-numbers',
'google-charts',
],
provides: {
values: {
'pie-chart': "tany",
'bar-chart': "tany",
'multi-bar-chart': "tany",
'histogram': "tany",
'box-plot': "tany",
'plot': "tany",
'geochart': "tany"
}
},
theModule: function (RUNTIME, NAMESPACE, uri, IMAGELIB, jsnums , google) {
'use strict';
// Load google library via editor.html to avoid loading issues
//const google = _google.google;
const isTrue = RUNTIME.isPyretTrue;
const get = RUNTIME.getField;
const toFixnum = jsnums.toFixnum;
const cases = RUNTIME.ffi.cases;
var IMAGE = get(IMAGELIB, "internal");
const ann = function(name, pred) {
return RUNTIME.makePrimitiveAnn(name, pred);
};
var checkListWith = function(checker) {
return function(val) {
if (!RUNTIME.ffi.isList(val)) return false;
var cur = val;
var gf = RUNTIME.getField;
while (RUNTIME.unwrap(RUNTIME.ffi.isLink(cur))) {
var f = gf(cur, "first");
if (!checker(f)) {
return false;
}
cur = gf(cur, "rest");
}
return true;
}
}
var checkOptionWith = function(checker) {
return function(val) {
if (!(RUNTIME.ffi.isNone(val) || RUNTIME.ffi.isSome(val))) return false;
var gf = RUNTIME.getField;
if (RUNTIME.unwrap(RUNTIME.ffi.isSome(val))) {
var f = gf(val, "value");
if (!checker(f)) {
return false;
}
}
return true;
}
}
google.charts.load('current', {'packages' : ['corechart', 'geochart']});
//////////////////////////////////////////////////////////////////////////////
function getPrettyNumToStringDigits(d) {
// this accepts Pyret num
return n =>
jsnums.toStringDigits(n, d, RUNTIME.NumberErrbacks).replace(/\.?0*$/, '');
}
const prettyNumToStringDigits5 = getPrettyNumToStringDigits(5);
function convertColor(v) {
function p(pred, name) {
return val => {
RUNTIME.makeCheckType(pred, name)(val);
return val;
};
}
const colorDb = IMAGE.colorDb;
const _checkColor = p(IMAGE.isColorOrColorString, 'Color');
function checkColor(val) {
let aColor = _checkColor(val);
if (colorDb.get(aColor)) {
aColor = colorDb.get(aColor);
}
return aColor;
}
function rgb2hex(rgb){
// From http://jsfiddle.net/Mottie/xcqpF/1/light/
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
return rgb2hex(IMAGE.colorString(checkColor(v)));
}
function convertPointer(p) {
return {v: toFixnum(get(p, 'value')) , f: get(p, 'label')}
}
//////////////////////////////////////////////////////////////////////////////
function getNewWindow(xMinC, xMaxC, yMinC, yMaxC, numSamplesC) {
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(xMinC.val()), {
none: function () {
xMinC.addClass('error-bg');
xMinC.removeClass('ok-bg');
return null;
},
some: function (xMinVal) {
xMinC.removeClass('error-bg');
xMinC.addClass('ok-bg');
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(xMaxC.val()), {
none: function () {
xMaxC.addClass('error-bg');
xMaxC.removeClass('ok-bg');
return null;
},
some: function (xMaxVal) {
xMaxC.removeClass('error-bg');
xMaxC.addClass('ok-bg');
if (jsnums.greaterThanOrEqual(xMinVal, xMaxVal,
RUNTIME.NumberErrbacks)) {
xMinC.addClass('error-bg');
xMaxC.addClass('error-bg');
xMinC.removeClass('ok-bg');
xMaxC.removeClass('ok-bg');
return null;
}
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(yMinC.val()), {
none: function () {
yMinC.addClass('error-bg');
yMinC.removeClass('ok-bg');
return null;
},
some: function (yMinVal) {
yMinC.removeClass('error-bg');
yMinC.addClass('ok-bg');
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(yMaxC.val()), {
none: function () {
yMaxC.addClass('error-bg');
yMaxC.removeClass('ok-bg');
return null;
},
some: function (yMaxVal) {
yMaxC.removeClass('error-bg');
yMaxC.addClass('ok-bg');
if (jsnums.greaterThanOrEqual(xMinVal, xMaxVal,
RUNTIME.NumberErrbacks)) {
yMinC.addClass('error-bg');
yMaxC.addClass('error-bg');
yMinC.removeClass('ok-bg');
yMaxC.removeClass('ok-bg');
return null;
}
return cases(RUNTIME.ffi.isOption, 'Option',
RUNTIME.string_to_number(numSamplesC.val()), {
none: function () {
numSamplesC.addClass('error-bg');
numSamplesC.removeClass('ok-bg');
return null;
},
some: function (numSamplesVal) {
numSamplesC.removeClass('error-bg');
numSamplesC.addClass('ok-bg');
if (!isTrue(RUNTIME.num_is_integer(numSamplesVal)) ||
jsnums.lessThanOrEqual(numSamplesVal, 1,
RUNTIME.NumberErrbacks)) {
numSamplesC.addClass('error-bg');
numSamplesC.removeClass('ok-bg');
return null;
}
return {
'x-min': RUNTIME.ffi.makeSome(xMinVal),
'x-max': RUNTIME.ffi.makeSome(xMaxVal),
'y-min': RUNTIME.ffi.makeSome(yMinVal),
'y-max': RUNTIME.ffi.makeSome(yMaxVal),
'num-samples': numSamplesVal
};
}
});
}
});
}
});
}
});
}
});
}
//////////////////////////////////////////////////////////////////////////////
/**
* Adds multiple columns with the given properties and values after data
* columns
*
* For example, if given:
* colProperties:
* {type: 'string', role: 'style'}
* colValues:
* [
* [['red', 'black'], ['white', 'blue'], ['green', 'purple']],
* []
* ]
* addNSpecialColumns will add 2 style columns after the first data column
* and no columns after the second data column.
*
* The number of columns added after a particular data column do not have to
* agree. It is possible to add one special value on one row and two
* special values on another row.
*
* https://jsfiddle.net/eyanje/u83kaf92/
*
* @param {DataTable} table a table to expand
* @param {object} colProperties an object specifying column properties
* @param {Array<Array<*>>>} colValues rows of groups of values to insert
*/
function addNSpecialColumns(table, colProperties, colValues) {
let dataColNums = [];
let nDataCols;
let groupWidths;
for (let i = 1; i < table.getNumberOfColumns(); i++) {
const role = table.getColumnRole(i);
if (role === '' || role === 'data') {
dataColNums.push(i);
}
}
nDataCols = dataColNums.length;
// Check column count
// Should never run -- Pyret checks all column counts properly
// This should be somewhat caught in the try-catch around setup(restarter),
// unless it's been moved
colValues.forEach((row, rowN) => {
if (row.length !== nDataCols) {
throw new Error(`Incorrect column count in row ${rowN}.`
+ ` Expected ${nDataCols}, given ${row.length}.`);
}
});
// Tally columns needed for each group
groupWidths = dataColNums.map(() => 0);
colValues.forEach(row => {
row.forEach((group, groupN) => {
groupWidths[groupN] = Math.max(group.length, groupWidths[groupN]);
});
});
// Add columns in reverse order
for (let groupIndex = nDataCols - 1; groupIndex >= 0; groupIndex--) {
for (let i = 0; i < groupWidths[groupIndex]; i++) {
table.insertColumn(dataColNums[groupIndex] + 1, colProperties);
}
}
// Adjust dataColNums to match expanded table
let sum = 0;
dataColNums.forEach((dataColNum, i) => {
dataColNums[i] += sum;
sum += groupWidths[i];
});
// Add columns in reverse order to avoid extra calculations
colValues.forEach((row, rowN) => {
row.forEach((group, groupN) => {
group.forEach((val, i) => {
table.setValue(rowN, dataColNums[groupN] + i + 1, val);
});
})
});
}
/**
* Adds columns with the given properties and values after data columns
*
* For example, you may use this function to add columns with properties
* {type: 'string', role: 'style'} and values
* [['red', 'black'] ['white', 'blue'], ['green', 'purple']], to add
* two style columns to a table with 3 rows and 2 columns.
*
* @param {DataTable} table a table to expand
* @param {object} colProperties an object specifying column properties
* @param {Array<Array<*>>>} colValues rows of values to insert
*/
function addSpecialColumns(table, colProperties, colValues) {
addNSpecialColumns(table, colProperties,
colValues.map(r => r.map(c => [c])));
}
function addAnnotations(table, rawData) {
const rawAnnotations = get(rawData, 'annotations').map(row =>
row.map(col =>
cases(RUNTIME.ffi.isOption, 'Option', col, {
none: function () {},
some: function (annotation) { return annotation; }
})
)
);
const colProperties = { type: 'string', role: 'annotation' };
addSpecialColumns(table, colProperties, rawAnnotations);
}
function addIntervals(table, rawData) {
const colProperties = {type: 'number', role: 'interval'};
addNSpecialColumns(table, colProperties, get(rawData, 'intervals'));
}
function axesNameMutator(options, globalOptions, _) {
const hAxis = ('hAxis' in options) ? options.hAxis : {};
const vAxis = ('vAxis' in options) ? options.vAxis : {};
hAxis.title = get(globalOptions, 'x-axis');
vAxis.title = get(globalOptions, 'y-axis');
$.extend(options, {hAxis: hAxis, vAxis: vAxis});
}
function gridlinesMutator(options, globalOptions, _) {
const hAxis = ('hAxis' in options) ? options.hAxis : {};
const vAxis = ('vAxis' in options) ? options.vAxis : {};
hAxis.gridlines = {color: '#aaa'};
vAxis.gridlines = {color: '#aaa'};
if (get(globalOptions, 'show-minor-grid-lines')) {
hAxis.minorGridlines = {color: '#ddd', minSpacing: 10};
vAxis.minorGridlines = {color: '#ddd', minSpacing: 10};
} else {
hAxis.minorGridlines = {count: 0};
vAxis.minorGridlines = {count: 0};
}
$.extend(options, {hAxis: hAxis, vAxis: vAxis});
}
function yAxisRangeMutator(options, globalOptions, _) {
const vAxis = ('vAxis' in options) ? options.vAxis : {};
const viewWindow = ('viewWindow' in vAxis) ? vAxis.viewWindow : {};
cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'y-min'), {
none: function () {},
some: function (minValue) {
const v = toFixnum(minValue);
vAxis.minValue = v;
viewWindow.min = v;
}
});
cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'y-max'), {
none: function () {},
some: function (maxValue) {
const v = toFixnum(maxValue);
vAxis.maxValue = v;
viewWindow.max = v;
}
});
vAxis.viewWindow = viewWindow;
$.extend(options, {vAxis: vAxis});
}
function xAxisRangeMutator(options, globalOptions, _) {
const hAxis = ('hAxis' in options) ? options.hAxis : {};
const viewWindow = ('viewWindow' in hAxis) ? hAxis.viewWindow : {};
const minValue = get(globalOptions, 'x-min');
const maxValue = get(globalOptions, 'x-max');
cases(RUNTIME.ffi.isOption, 'Option', minValue, {
none: function () {},
some: function (realMinValue) {
hAxis.minValue = toFixnum(realMinValue);
viewWindow.min = toFixnum(realMinValue);
}
});
cases(RUNTIME.ffi.isOption, 'Option', maxValue, {
none: function () {},
some: function (realMaxValue) {
hAxis.maxValue = toFixnum(realMaxValue);
viewWindow.max = toFixnum(realMaxValue);
}
});
hAxis.viewWindow = viewWindow;
$.extend(options, {hAxis: hAxis});
}
//////////////////////////////////////////////////////////////////////////////
function pieChart(globalOptions, rawData) {
const table = get(rawData, 'tab');
const data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addRows(table.map(row => [row[0], toFixnum(row[1])]));
return {
data: data,
options: {
slices: table.map(row => ({offset: toFixnum(row[2])})),
legend: {
alignment: 'end'
}
},
chartType: google.visualization.PieChart,
onExit: defaultImageReturn,
};
}
//////////// Bar Chart Getter Functions /////////////////
function get_colors_list(rawData) {
// Sets up the color list [Each Bar Colored Individually]
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'colors'), {
none: function () {
return [];
},
some: function (colors) {
return colors.map(convertColor);
}
});
}
function get_default_color(rawData) {
// Sets up the default color [Default Bar Color if not specified in color_list]
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'color'), {
none: function () {
return "";
},
some: function (color) {
return convertColor(color);
}
});
}
function get_pointers_list(rawData) {
// Sets up the pointers list [Coloring each group memeber/stack]
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'pointers'), {
none: function () {
return [];
},
some: function (pointers) {
return pointers.map(convertPointer);
}
});
}
function get_pointer_color(rawData) {
// Sets up the pointer color
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'pointer-color'), {
none: function () {
return 'black';
},
some: function (color) {
return convertColor(color);
}
});
}
function get_axis(rawData) {
// Sets up the calculated axis properties/data
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'axisdata'), {
none: function () {
return undefined;
},
some: function (axisdata) {
return {
top : toFixnum(get(axisdata, 'axisTop')),
bottom : toFixnum(get(axisdata, 'axisBottom')),
ticks : get(axisdata, 'ticks').map(convertPointer)
};
}
});
}
function get_interval_color(rawData) {
// Sets up the default interval color
return cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'default-interval-color'), {
none: function () {
return 'black';
},
some: function (color) {
return convertColor(color);
}
});
}
/////////////////////////////////////////////////////////
function barChart(globalOptions, rawData) {
// Variables and constants
const table = get(rawData, 'tab');
const horizontal = get(rawData, 'horizontal');
const axisloc = horizontal ? 'hAxes' : 'vAxes';
const data = new google.visualization.DataTable();
const colors_list = get_colors_list(rawData);
const default_color = get_default_color(rawData);
const pointers_list = get_pointers_list(rawData);
const pointer_color = get_pointer_color(rawData);
const axis = get_axis(rawData);
const interval_color = get_interval_color(rawData);
const colors_list_length = colors_list.length;
// Initializes the Columns of the data
data.addColumn('string', 'Label');
data.addColumn('number', 'Values');
data.addColumn({type: 'string', role: 'style'});
// Adds each row of bar data and bar_color data
table.forEach(function (row, idx) {
const bar_color = idx < colors_list_length ? colors_list[idx] : default_color;
data.addRow([row[0], toFixnum(row[1]), bar_color]);
});
addAnnotations(data, rawData);
addIntervals(data, rawData);
let options = {
legend: {
position: 'none'
},
intervals: {
color : interval_color,
}
};
options[axisloc] = {
0: {
viewWindow: { max: axis.top, min: axis.bottom },
ticks: axis.ticks
}
};
/* NOTE(John & Edward, Dec 2020):
Our goal for the part below was to add pointers (Specific Named Ticks) on another VAxis.
The Current Chart library necessitates that we assign at least one stack/bar to the
second axis in order for it to show up, and we have to fix the min/max of each axis
manually to make sure that both are consistent with each other rather than being relative
to the data. There is also a problem: When the pointers are too close to each other, one or
both of them disappear!
*/
if (pointers_list.length > 0) {
// Add and Attach Empty Data Stack/bar to 2nd axis + Color it
data.addColumn('number', 'Pointers');
options['series'] = { 1: { color: pointer_color, targetAxisIndex: 1 } };
// Update Options to include the new axis ticks consistent with the first axis
options[axisloc][1] = {
viewWindow: {
max: axis.top,
min: axis.bottom
},
gridlines: { color: pointer_color },
ticks: pointers_list,
textStyle: { color: pointer_color }
};
}
return {
data: data,
options: options,
chartType: horizontal ? google.visualization.BarChart : google.visualization.ColumnChart,
onExit: defaultImageReturn,
mutators: [axesNameMutator, yAxisRangeMutator],
};
}
function multiBarChart(globalOptions, rawData) {
// Variables and Constants
const table = get(rawData, 'tab');
const legends = get(rawData, 'legends');
const horizontal = get(rawData, 'horizontal');
const axisloc = horizontal ? 'hAxes' : 'vAxes';
const data = new google.visualization.DataTable();
const pointers_list = get_pointers_list(rawData);
const pointer_color = get_pointer_color(rawData);
const axis = get_axis(rawData);
const interval_color = get_interval_color(rawData);
const default_colors = ['#3366CC', '#DC3912', '#FF9900', '#109618', '#990099',
'#3B3EAC', '#0099C6', '#DD4477', '#66AA00', '#B82E2E',
'#316395', '#994499', '#22AA99', '#AAAA11', '#6633CC',
'#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC']
var colors_list = get_colors_list(rawData);
if (colors_list.length < default_colors.length) {
default_colors.splice(0, colors_list.length, ...colors_list);
colors_list = default_colors;
colors_list = colors_list.slice(0, legends.length);
}
// Initializes the Columns of the data
data.addColumn('string', 'Label');
legends.forEach(legend => data.addColumn('number', legend));
// Adds each row of bar data
data.addRows(table.map(row => [row[0]].concat(row[1].map(n => toFixnum(n)))));
addAnnotations(data, rawData);
addIntervals(data, rawData);
let options = {
isStacked: get(rawData, 'is-stacked'),
series: colors_list.map(c => ({color: c, targetAxisIndex: 0})),
legend: {
position: horizontal ? 'right' : 'top',
maxLines: data.getNumberOfColumns() - 1
},
intervals: {
color : interval_color,
}
};
options[axisloc] = {
0: {
viewWindow: { max: axis.top, min: axis.bottom },
ticks: axis.ticks
}
};
/* NOTE(John & Edward, Dec 2020):
Our goal for the part below was to add pointers (Specific Named Ticks) on another VAxis.
The Current Chart library necessitates that we assign at least one stack/bar to the
second axis in order for it to show up, and we have to fix the min/max of each axis
manually to make sure that both are consistent with each other rather than being relative
to the data. There is also a problem: When the pointers are too close to each other, one or
both of them disappear!
*/
if (pointers_list.length > 0) {
colors_list = colors_list.slice(0, legends.length);
// Add and Attach Empty Data Stack/bar to 2nd axis + Color it
data.addColumn('number', 'Pointers')
for (let i = 0; i < data.getNumberOfColumns() - 1; i++) {
if (options['series'][i] == null) {
options['series'][i] = {color: pointer_color, targetAxisIndex: 1};
}
}
// Update Options to include the new axis ticks consistent with the first axis
options[axisloc][1] = {
viewWindow: {
max: axis.top,
min: axis.bottom
},
gridlines: { color: pointer_color },
ticks: pointers_list,
textStyle: { color: pointer_color }
};
} else {
for (let i = 0; i < data.getNumberOfColumns() - 1; i++) {
if (options['series'][i] == null) {
options['series'][i] = {color: 'black', targetAxisIndex: 0};
}
}
}
return {
data: data,
options: options,
chartType: horizontal ? google.visualization.BarChart : google.visualization.ColumnChart,
onExit: defaultImageReturn,
mutatorgraphs: [axesNameMutator, yAxisRangeMutator],
};
}
function boxPlot(globalOptions, rawData) {
let table = get(rawData, 'tab');
const dimension = toFixnum(get(rawData, 'height'));
// TODO: are these two supposed to be on ChartWindow or DataSeries?
const horizontal = get(rawData, 'horizontal');
const showOutliers = get(rawData, 'show-outliers');
const axisName = horizontal ? 'hAxis' : 'vAxis';
const chartType = horizontal ? google.visualization.BarChart : google.visualization.ColumnChart;
const data = new google.visualization.DataTable();
const intervalOptions = {
lowNonOutlier: {
style: 'bars',
fillOpacity: 1,
color: '#777'
},
highNonOutlier: {
style: 'bars',
fillOpacity: 1,
color: '#777'
}
};
data.addColumn('string', 'Label');
data.addColumn('number', 'Total');
data.addColumn({id: 'firstQuartile', type: 'number', role: 'interval'});
data.addColumn({id: 'median', type: 'number', role: 'interval'});
data.addColumn({id: 'thirdQuartile', type: 'number', role: 'interval'});
data.addColumn({id: 'highNonOutlier', type: 'number', role: 'interval'});
data.addColumn({id: 'lowNonOutlier', type: 'number', role: 'interval'});
data.addColumn({type: 'string', role: 'tooltip', 'p': {'html': true}});
// NOTE(joe & emmanuel, Aug 2019): With the current chart library, it seems
// like we can only get outliers to work as a variable-length row if we
// have a single row of data. It's an explicit error to mix row lengths.
// Since the main use case where outliers matter is for single-column
// box-plots, this maintains existing behavior (if anyone was relying on
// multiple series), while adding the ability to render outliers for BS:DS.
if(table.length === 1 && showOutliers) {
var extraCols = table[0][8].length + table[0][9].length;
for(var i = 0; i < extraCols; i += 1) {
data.addColumn({id: 'outlier', type: 'number', role: 'interval'});
}
intervalOptions['outlier'] = { 'style':'points', 'color':'grey', 'pointSize': 10, 'lineWidth': 0, 'fillOpacity': 0.3 };
}
else {
// NOTE(joe & emmanuel, Aug 2019 cont.): This forces the low and high
// whiskers to be equal to the min/max when there are multiple rows since we
// won't be able to render the outliers, and the whiskers need to cover
// the whole span of data.
table = table.map(function(row) {
row = row.slice(0, row.length);
// force whisker to be max/min
row[7] = row[2];
row[6] = row[1];
// empty outliers
row[9] = [];
row[8] = [];
return row;
});
}
const rowsToAdd = table.map(row => {
const summaryValues = row.slice(3, 8).map(n => toFixnum(n));
let tooltip = `<p><b>${row[0]}</b></p>
<p>minimum: <b>${row[2]}</b></p>
<p>maximum: <b>${row[1]}</b></p>
<p>first quartile: <b>${summaryValues[0]}</b></p>
<p>median: <b>${summaryValues[1]}</b></p>
<p>third quartile: <b>${summaryValues[2]}</b></p>`;
// ONLY if we're showing outliers, add whiskers to the tooltip
// (otherwise, the min/max ARE the bottom/top whiskers)
if(table.length == 1 && showOutliers) {
tooltip +=
` <p>bottom whisker: <b>${summaryValues[4]}</b></p>
<p>top whisker: <b>${summaryValues[3]}</b></p>`;
}
return [row[0], toFixnum(dimension)]
.concat(summaryValues)
.concat([tooltip])
.concat(row[9]).concat(row[8]);
});
data.addRows(rowsToAdd);
const options = {
tooltip: {isHtml: true},
legend: {position: 'none'},
lineWidth: 0,
intervals: {
barWidth: 0.25,
boxWidth: 0.8,
lineWidth: 2,
style: 'boxes'
},
interval: intervalOptions,
dataOpacity: 0,
};
/* NOTE(Oak): manually set the default max to coincide with bar charts' height
* so that the bar charts are concealed (the automatic value from Google
* is likely to screw this up)
*/
const axisOpts = {
maxValue: dimension,
viewWindow: {
max: dimension
},
};
/* NOTE(Emmanuel): if min and max are set, override these defaults
*
*/
cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'min'), {
none: function () {},
some: function (min) {
axisOpts.viewWindow.min = toFixnum(min);
}
});
cases(RUNTIME.ffi.isOption, 'Option', get(globalOptions, 'max'), {
none: function () {},
some: function (max) {
axisOpts.viewWindow.max = toFixnum(max);
}
});
options[axisName] = axisOpts;
return {
data: data,
options: options,
chartType: chartType,
onExit: defaultImageReturn,
mutators: [axesNameMutator],
};
}
function histogram(globalOptions, rawData) {
const table = get(rawData, 'tab');
const data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', '');
var max, min;
var val = null;
var hasAtLeastTwoValues = false;
data.addRows(table.map(row => {
var valfix = toFixnum(row[1]);
if(val !== null && val !== valfix) { hasAtLeastTwoValues = true; }
if(val === null) { val = valfix; }
if(max === undefined) { max = valfix; }
if(min === undefined) { min = valfix; }
if(valfix > max) { max = valfix; }
if(valfix < min) { min = valfix; }
return [row[0], valfix];
}));
// set legend to none because there's only one data set
const options = {legend: {position: 'none'}, histogram: {}};
cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'bin-width'), {
none: function () {},
some: function (binWidth) {
// NOTE(joe, aug 2019): The chart library has a bug for histograms with
// a single unique value (https://jsfiddle.net/L0y64fbo/2/), so thisi
// hackaround makes it so this case can't come up.
if(hasAtLeastTwoValues) {
options.histogram.bucketSize = toFixnum(binWidth);
}
}
});
cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'max-num-bins'), {
none: function () {},
some: function (maxNumBins) {
options.histogram.maxNumBuckets = toFixnum(maxNumBins);
}
});
cases(RUNTIME.ffi.isOption, 'Option', get(rawData, 'min-num-bins'), {
none: function () {
if(options.histogram.bucketSize !== undefined) {
options.histogram.minNumBuckets = Math.floor((max - min) / options.histogram.bucketSize) + 1;
}
},
some: function (minNumBins) {
options.histogram.minNumBuckets = toFixnum(minNumBins);
}
});
/*
The main reason to use `x-min`, `x-max` is so that students can compare
different histogram agaisnt each other. Setting `x-min`, `x-max` on `hAxis`
is more accurate than setting it to `histogram`
const xMin = toFixnum(get(globalOptions, 'x-min'));
const xMax = toFixnum(get(globalOptions, 'x-max'));
if (xMin < xMax) {
options.histogram.minValue = xMin;
options.histogram.maxValue = xMax;
}
*/
return {
data: data,
options: options,
chartType: google.visualization.Histogram,
onExit: defaultImageReturn,
mutators: [axesNameMutator, yAxisRangeMutator, xAxisRangeMutator],
};
}
function geoChart(globalOptions, rawData) {
const table = get(rawData, 'tab');
const data = new google.visualization.DataTable();
const region = get(rawData, 'region');
data.addColumn('string', 'Region');
data.addColumn('number', "Value");
data.addRows(table.map(row => [row[0], toFixnum(row[1])]));
console.log("test123");
console.log(region);
const options = {region: region};
return {
data: data,
options: options,
chartType: google.visualization.GeoChart,
onExit: defaultImageReturn,
};
}
function plot(globalOptions, rawData) {
const scatters = get(rawData, 'scatters');
const lines = get(rawData, 'lines');
const data = new google.visualization.DataTable();
data.addColumn('number', 'X');
const combined = scatters.concat(lines);
const legends = [];
let cnt = 1;
const legendEnabled = combined.length > 1;
combined.forEach(p => {
let legend = get(p, 'legend');
if (legend === '') {
legend = `Plot ${cnt}`;
cnt++;
}
legends.push(legend);
data.addColumn('number', legend);
data.addColumn({type: 'string', role: 'tooltip', 'p': {'html': true}});
});
combined.forEach((p, i) => {
/*
x | n n n | y | n n n n n n n n n n n n
i combined.length - i - 1
*/
const prefix = new Array(2 * i).fill(null);
const suffix = new Array(2 * (combined.length - i - 1)).fill(null);
const rowTemplate = [0].concat(prefix).concat([null, null]).concat(suffix);
data.addRows(get(p, 'ps').map(row => {
const currentRow = rowTemplate.slice();
if (row.length != 0) {
currentRow[0] = toFixnum(row[0]);
currentRow[2*i + 1] = toFixnum(row[1]);
let labelRow = null;
if (row.length >= 3 && row[2] !== '') {
labelRow = `<p>label: <b>${row[2]}</b></p>`;
} else {
labelRow = '';
}
currentRow[2*i + 2] = `<p>${legends[i]}</p>
<p>x: <b>${currentRow[0]}</b></p>
<p>y: <b>${currentRow[2*i + 1]}</b></p>
${labelRow}`;
}
return currentRow;
}));
});
// ASSERT: if we're using custom images, *every* series will have idx 3 defined
const hasImage = combined.every(p => get(p, 'ps').filter(p => p[3]).length > 0);
const options = {
tooltip: {isHtml: true},
series: combined.map((p, i) => {
// scatters and then lines
const seriesOptions = {};
cases(RUNTIME.ffi.isOption, 'Option', get(p, 'color'), {
none: function () {},
some: function (color) {
seriesOptions.color = convertColor(color);
}
});
// If we have our own image, make the point small and transparent
if (i < scatters.length) {
$.extend(seriesOptions, {
pointSize: hasImage ? 1 : toFixnum(get(p, 'point-size')),
lineWidth: 0,
dataOpacity: hasImage ? 0 : 1,
});
}
return seriesOptions;
}),
legend: {position: legendEnabled ? 'bottom' : 'none'},
crosshair: {trigger: 'selection'}
};
if (isTrue(get(globalOptions, 'interact'))) {
$.extend(options, {
chartArea: {
left: '12%',
width: '56%',
}
});
}
return {
data: data,
options: options,
chartType: google.visualization.LineChart,
onExit: (restarter, result) => {
let svg = result.chart.container.querySelector('svg');