-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsafetyDeltaDelta.js
1851 lines (1633 loc) · 65.1 KB
/
safetyDeltaDelta.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
(function(global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
? (module.exports = factory(require('d3'), require('webcharts')))
: typeof define === 'function' && define.amd
? define(['d3', 'webcharts'], factory)
: ((global = global || self),
(global.safetyDeltaDelta = factory(global.d3, global.webCharts)));
})(this, function(d3, webcharts) {
'use strict';
if (typeof Object.assign != 'function') {
Object.defineProperty(Object, 'assign', {
value: function assign(target, varArgs) {
if (target == null) {
// TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource != null) {
// Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function value(predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, 'length')).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, � kValue, k, O �)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
// 7. Return undefined.
return undefined;
}
});
}
if (!Array.prototype.findIndex) {
Object.defineProperty(Array.prototype, 'findIndex', {
value: function value(predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, � kValue, k, O �)).
// d. If testResult is true, return k.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return k;
}
// e. Increase k by 1.
k++;
}
// 7. Return -1.
return -1;
}
});
}
Math.log10 = Math.log10 =
Math.log10 ||
function(x) {
return Math.log(x) * Math.LOG10E;
};
// https://github.com/wbkd/d3-extended
d3.selection.prototype.moveToFront = function() {
return this.each(function() {
this.parentNode.appendChild(this);
});
};
d3.selection.prototype.moveToBack = function() {
return this.each(function() {
var firstChild = this.parentNode.firstChild;
if (firstChild) {
this.parentNode.insertBefore(this, firstChild);
}
});
};
function rendererSettings() {
return {
id_col: 'USUBJID',
visit_col: 'VISIT',
visitn_col: 'VISITNUM',
measure_col: 'TEST',
value_col: 'STRESN',
filters: null,
details: null,
measure: {
x: null,
y: null
},
visits: {
baseline: [],
comparison: [],
stat: 'mean'
},
add_regression_line: true
};
}
function webchartsSettings() {
return {
x: {
column: null,
type: 'linear',
label: 'x delta',
format: '0.2f'
},
y: {
column: null,
type: 'linear',
label: 'y delta',
behavior: 'flex',
format: '0.2f'
},
marks: [
{
type: 'circle',
per: null,
radius: 4,
attributes: {
'stroke-width': 0.5,
'fill-opacity': 0.8
},
tooltip:
'Subject ID: [key]\nX Delta: [delta_x_rounded]\nY Delta: [delta_y_rounded]'
}
],
gridlines: 'xy',
resizable: false,
margin: { right: 25, top: 25 },
aspect: 1,
width: 400
};
}
function syncSettings(settings) {
//handle a string argument to filters
if (!(settings.filters instanceof Array))
settings.filters = typeof settings.filters === 'string' ? [settings.filters] : [];
//handle a string argument to details
if (!(settings.details instanceof Array))
settings.details = typeof settings.details === 'string' ? [settings.details] : [];
//Define default details.
var defaultDetails = [{ value_col: settings.id_col, label: 'Participant ID' }];
if (Array.isArray(settings.filters))
settings.filters
.filter(function(filter) {
return filter.value_col !== settings.id_col;
})
.forEach(function(filter) {
return defaultDetails.push({
value_col: filter.value_col ? filter.value_col : filter,
label: filter.label
? filter.label
: filter.value_col
? filter.value_col
: filter
});
});
//If [settings.details] is not specified:
if (!settings.details) settings.details = defaultDetails;
else {
//If [settings.details] is specified:
//Allow user to specify an array of columns or an array of objects with a column property
//and optionally a column label.
settings.details.forEach(function(detail) {
if (
defaultDetails
.map(function(d) {
return d.value_col;
})
.indexOf(detail.value_col ? detail.value_col : detail) === -1
)
defaultDetails.push({
value_col: detail.value_col ? detail.value_col : detail,
label: detail.label
? detail.label
: detail.value_col
? detail.value_col
: detail
});
});
settings.details = defaultDetails;
}
return settings;
}
function controlInputs() {
return [
{
type: 'dropdown',
values: [],
label: 'Baseline visit(s)',
option: 'visits.baseline',
require: true,
multiple: true
},
{
type: 'dropdown',
values: [],
label: 'Comparison visit(s)',
option: 'visits.comparison',
require: true,
multiple: true
},
{
type: 'dropdown',
values: [],
label: 'X Measure',
option: 'measure.x',
require: true
},
{
type: 'dropdown',
values: [],
label: 'Y Measure',
option: 'measure.y',
require: true
}
];
}
function syncControlInputs(controlInputs, settings) {
//Add filters to default controls.
if (Array.isArray(settings.filters) && settings.filters.length > 0) {
settings.filters.forEach(function(filter) {
var filterObj = {
type: 'subsetter',
value_col: filter.value_col || filter,
label: filter.label || filter.value_col || filter
};
controlInputs.push(filterObj);
});
} else delete settings.filters;
return controlInputs;
}
function listingSettings() {
return {
cols: ['key', 'spark', 'delta'],
headers: ['Measure', '', 'Change over Time'],
searchable: false,
sortable: false,
pagination: false,
exportable: false
};
}
var configuration = {
rendererSettings: rendererSettings,
webchartsSettings: webchartsSettings,
settings: Object.assign({}, rendererSettings(), webchartsSettings()),
syncSettings: syncSettings,
controlInputs: controlInputs,
syncControlInputs: syncControlInputs,
listingSettings: listingSettings
};
function cleanData() {
var _this = this;
//Remove missing and non-numeric data.
var preclean = this.raw_data;
var clean = this.raw_data.filter(function(d) {
return /^-?[0-9.]+$/.test(d[_this.config.value_col]);
});
var nPreclean = preclean.length;
var nClean = clean.length;
var nRemoved = nPreclean - nClean;
//Warn user of removed records.
if (nRemoved > 0)
console.warn(
nRemoved +
' missing or non-numeric result' +
(nRemoved > 1 ? 's have' : ' has') +
' been removed.'
);
//Preserve cleaned data.
this.initial_data = clean;
}
function trimMeasures() {
var _this = this;
this.initial_data.forEach(function(d) {
d[_this.config.measure_col] = d[_this.config.measure_col].trim();
});
}
function checkFilters() {
var _this = this;
if (this.config.filters)
this.config.filters = this.config.filters.filter(function(filter) {
var variableExists = _this.raw_data[0].hasOwnProperty(filter.value_col);
var nLevels = d3
.set(
_this.raw_data.map(function(d) {
return d[filter.value_col];
})
)
.values().length;
if (!variableExists)
console.warn(
' The [ ' +
filter.label +
' ] filter has been removed because the variable does not exist.'
);
else if (nLevels < 2)
console.warn(
'The [ ' +
filter.label +
' ] filter has been removed because the variable has only one level.'
);
return variableExists && nLevels > 1;
});
}
function getMeasures() {
var _this = this;
this.measures = d3
.set(
this.initial_data.map(function(d) {
return d[_this.config.measure_col];
})
)
.values()
.sort();
}
function getVisits() {
var _this = this;
if (this.config.visitn_col && this.initial_data[0].hasOwnProperty(this.config.visitn_col))
this.visits = d3
.set(
this.initial_data.map(function(d) {
return d[_this.config.visit_col] + '||' + d[_this.config.visitn_col];
})
)
.values()
.sort(function(a, b) {
var aSplit = a.split('||');
var aVisit = aSplit[0];
var aOrder = aSplit[1];
var bSplit = b.split('||');
var bVisit = bSplit[0];
var bOrder = bSplit[1];
var diff = aOrder - bOrder;
return diff
? diff
: aOrder < bOrder
? -1
: aOrder > bOrder
? 1
: aVisit < bVisit
? -1
: 1;
})
.map(function(visit) {
return visit.split('||')[0];
});
else
this.visits = d3
.set(
this.initial_data.map(function(d) {
return d[_this.config.visit_col];
})
)
.values()
.sort();
}
function updateControlInputs() {
var x_control = this.controls.config.inputs.find(function(input) {
return input.option === 'measure.x';
});
x_control.values = this.measures;
x_control.start = this.config.measure.x;
var y_control = this.controls.config.inputs.find(function(input) {
return input.option === 'measure.y';
});
y_control.values = this.measures;
y_control.start = this.config.measure.y;
var baseline_control = this.controls.config.inputs.find(function(input) {
return input.option === 'visits.baseline';
});
baseline_control.values = this.visits;
baseline_control.start = this.config.visits.baseline;
var comparison_control = this.controls.config.inputs.find(function(input) {
return input.option === 'visits.comparison';
});
comparison_control.values = this.visits;
comparison_control.start = this.config.visits.comprarison;
}
function initCustomEvents() {
var chart = this;
chart.participantsSelected = [];
chart.events.participantsSelected = new CustomEvent('participantsSelected');
}
function initSettings() {
//Set initial measures.
this.config.measure.x = this.config.measure.x || this.measures[0];
// this.config.x.column = this.config.measure.x;
this.config.measure.y = this.config.measure.y || this.measures[1];
//Set baseline and comparison visits.
this.config.visits.baseline =
this.config.visits.baseline.length > 0 ? this.config.visits.baseline : [this.visits[0]];
this.config.visits.comparison =
this.config.visits.comparison.length > 0
? this.config.visits.comparison
: [this.visits[this.visits.length - 1]];
}
function onInit() {
// 1. Remove invalid data.
cleanData.call(this);
// 2. trim measures.
trimMeasures.call(this);
// 3a Check filters against data.
checkFilters.call(this);
// 3b Get list of measures.
getMeasures.call(this);
// 3c Get list of visits.
getVisits.call(this);
//4a. Initialize the delta-delta settings & Update control inputs.
initSettings.call(this);
updateControlInputs.call(this);
//initialize custom events
initCustomEvents.call(this);
}
function initNotes() {
//Add footnote element.
this.wrap
.insert('p', ':first-child')
.attr('class', 'record-note')
.style('text-align', 'center')
.style('font-weight', 'bold')
.text('Click a point to see details.');
//Add header element in which to list visits at which measure is captured.
this.wrap.append('p', 'svg').attr('class', 'possible-visits');
//Add element for participant counts.
this.controls.wrap
.append('em')
.classed('annote', true)
.style('display', 'block');
}
function updateVisitControls() {
var _this = this;
var config = this.config;
var baselineSelect = this.controls.wrap
.selectAll('.control-group')
.filter(function(f) {
return f.option === 'visits.baseline';
})
.select('select');
baselineSelect
.selectAll('option')
.filter(function(f) {
return _this.config.visits.baseline.indexOf(f) > -1;
})
.attr('selected', 'selected');
var comparisonSelect = this.controls.wrap
.selectAll('.control-group')
.filter(function(f) {
return f.option === 'visits.comparison';
})
.select('select');
comparisonSelect
.selectAll('option')
.filter(function(f) {
return _this.config.visits.comparison.indexOf(f) > -1;
})
.attr('selected', 'selected');
}
function onLayout() {
initNotes.call(this);
updateVisitControls.call(this);
}
function addParticipantLevelMetadata(d, participant_obj) {
var varList = [];
if (this.config.filters) {
var filterVars = this.config.filters.map(function(d) {
return d.hasOwnProperty('value_col') ? d.value_col : d;
});
varList = d3.merge([varList, filterVars]);
}
if (this.config.group_cols) {
var groupVars = this.config.group_cols.map(function(d) {
return d.hasOwnProperty('value_col') ? d.value_col : d;
});
varList = d3.merge([varList, groupVars]);
}
if (this.config.details) {
var detailVars = this.config.details.map(function(d) {
return d.hasOwnProperty('value_col') ? d.value_col : d;
});
varList = d3.merge([varList, detailVars]);
}
varList.forEach(function(v) {
participant_obj[v] = '' + d[0][v];
});
}
function getMeasureDetails(pt_data) {
var config = this.config;
var measure_details = d3
.nest()
.key(function(d) {
return d[config.measure_col];
})
.rollup(function(di) {
var measure_obj = {};
measure_obj.key = di[0][config.measure_col];
measure_obj.spark = 'sparkline placeholder';
measure_obj.toggle = '+';
measure_obj.raw = di;
measure_obj.axisFlag =
measure_obj.key == config.measure.x
? 'X'
: measure_obj.key == config.measure.y
? 'Y'
: '';
measure_obj.raw.forEach(function(dii) {
dii.baseline = config.visits.baseline.indexOf(dii[config.visit_col]) > -1;
dii.comparison = config.visits.comparison.indexOf(dii[config.visit_col]) > -1;
dii.color = dii.baseline ? 'blue' : dii.comparison ? 'orange' : '#999';
});
['baseline', 'comparison'].forEach(function(t) {
measure_obj[t + '_records'] = di.filter(function(f) {
return config.visits[t].indexOf(f[config.visit_col]) > -1;
});
measure_obj[t + '_value'] = d3.mean(measure_obj[t + '_records'], function(d) {
return d[config.value_col];
});
});
measure_obj['delta'] = measure_obj.comparison_value - measure_obj.baseline_value;
return measure_obj;
})
.entries(pt_data);
measure_details = measure_details
.map(function(m) {
return m.values;
})
.sort(function(a, b) {
if (a.axisFlag == 'X') return -1;
else if (b.axisFlag == 'X') return 1;
else if (a.axisFlag == 'Y') return -1;
else if (b.axisFlag == 'Y') return 1;
else if (a.key < b.key) return -1;
else if (b.key > a.key) return 1;
else return 0;
});
return measure_details;
}
function flattenData(rawData) {
var _this = this;
var nested = d3
.nest()
.key(function(d) {
return d[_this.config.id_col];
})
.rollup(function(d) {
var obj = {};
obj.key = d[0][_this.config.id_col];
obj.raw = d;
obj.measures = getMeasureDetails.call(_this, d);
obj.x_details = obj.measures.find(function(f) {
return f.key == _this.config.measure.x;
});
obj.delta_x = obj.x_details ? obj.x_details.delta : null;
obj.delta_x_rounded = obj.x_details ? d3.format('0.2f')(obj.delta_x) : '';
obj.y_details = obj.measures.find(function(f) {
return f.key == _this.config.measure.y;
});
obj.delta_y = obj.y_details ? obj.y_details.delta : null;
obj.delta_y_rounded = obj.y_details ? d3.format('0.2f')(obj.delta_y) : '';
addParticipantLevelMetadata.call(_this, d, obj);
return obj;
})
.entries(rawData);
return nested.map(function(m) {
return m.values;
});
}
function updateAxisSettings() {
var config = this.config;
//set config properties here since they aren't available in onInit
config.x.column = 'delta_x';
config.y.column = 'delta_y';
config.marks[0].per = ['key'];
config.x.label = 'Change in ' + config.measure.x;
config.y.label = 'Change in ' + config.measure.y;
}
function onPreprocess() {
updateAxisSettings.call(this);
this.raw_data = flattenData.call(this, this.initial_data);
}
function onDatatransform() {}
/*------------------------------------------------------------------------------------------------\
Annotate number of participants based on current filters, number of participants in all, and
the corresponding percentage.
Inputs:
chart - a webcharts chart object
id_unit - a text string to label the units in the annotation (default = 'participants')
selector - css selector for the annotation
\------------------------------------------------------------------------------------------------*/
function updateParticipantCount(chart, selector, id_unit) {
//count the number of unique ids in the data set
var totalObs = d3
.set(
chart.initial_data.map(function(d) {
return d[chart.config.id_col];
})
)
.values().length;
//count the number of unique ids in the current chart and calculate the percentage
var currentObs = chart.filtered_data.filter(function(f) {
return (
!isNaN(f.delta_x) && f.delta_x !== null && !isNaN(f.delta_y) && f.delta_y !== null
);
}).length; // TODO: remove these records as part of the data flow
var percentage = d3.format('0.1%')(currentObs / totalObs);
//clear the annotation
var annotation = d3.select(selector);
annotation.selectAll('*').remove();
//update the annotation
var units = id_unit ? ' ' + id_unit : ' participant(s)';
annotation.text(currentObs + ' of ' + totalObs + units + ' shown (' + percentage + ')');
}
function reset() {
this.svg.selectAll('g.boxplot').remove();
this.svg
.selectAll('g.point')
.classed('selected', false)
.select('circle')
.style('fill', this.config.colors[0]);
this.wrap
.select('.record-note')
.style('text-align', 'center')
.text('Click a point to see details.');
this.listing.draw([]);
this.listing.wrap.style('display', 'none');
}
function onDraw() {
//Annotate selected and total number of participants.
updateParticipantCount(this, '.annote');
//Reset things.
reset.call(this);
}
function drawBoxPlot(
svg,
results,
height,
width,
domain,
boxPlotWidth,
boxColor,
boxInsideColor,
fmt,
horizontal
) {
//set default orientation to "horizontal"
var horizontal = horizontal == undefined ? true : horizontal;
//make the results numeric and sort
var results = results
.map(function(d) {
return +d;
})
.sort(d3.ascending);
//set up scales
var y = d3.scale.linear().range([height, 0]);
var x = d3.scale.linear().range([0, width]);
if (horizontal) {
y.domain(domain);
} else {
x.domain(domain);
}
var probs = [0.05, 0.25, 0.5, 0.75, 0.95];
for (var i = 0; i < probs.length; i++) {
probs[i] = d3.quantile(results, probs[i]);
}
var boxplot = svg
.append('g')
.attr('class', 'boxplot')
.datum({ values: results, probs: probs });
//draw rectangle from q1 to q3
var box_x = horizontal ? x(0.5 - boxPlotWidth / 2) : x(probs[1]);
var box_width = horizontal
? x(0.5 + boxPlotWidth / 2) - x(0.5 - boxPlotWidth / 2)
: x(probs[3]) - x(probs[1]);
var box_y = horizontal ? y(probs[3]) : y(0.5 + boxPlotWidth / 2);
var box_height = horizontal
? -y(probs[3]) + y(probs[1])
: y(0.5 - boxPlotWidth / 2) - y(0.5 + boxPlotWidth / 2);
boxplot
.append('rect')
.attr('class', 'boxplot fill')
.attr('x', box_x)
.attr('width', box_width)
.attr('y', box_y)
.attr('height', box_height)
.style('fill', boxColor);
//draw dividing lines at median, 95% and 5%
var iS = [0, 2, 4];
var iSclass = ['', 'median', ''];
var iSColor = [boxColor, boxInsideColor, boxColor];
for (var i = 0; i < iS.length; i++) {
boxplot
.append('line')
.attr('class', 'boxplot ' + iSclass[i])
.attr('x1', horizontal ? x(0.5 - boxPlotWidth / 2) : x(probs[iS[i]]))
.attr('x2', horizontal ? x(0.5 + boxPlotWidth / 2) : x(probs[iS[i]]))
.attr('y1', horizontal ? y(probs[iS[i]]) : y(0.5 - boxPlotWidth / 2))
.attr('y2', horizontal ? y(probs[iS[i]]) : y(0.5 + boxPlotWidth / 2))
.style('fill', iSColor[i])
.style('stroke', iSColor[i]);
}
//draw lines from 5% to 25% and from 75% to 95%
var iS = [[0, 1], [3, 4]];
for (var i = 0; i < iS.length; i++) {
boxplot
.append('line')
.attr('class', 'boxplot')
.attr('x1', horizontal ? x(0.5) : x(probs[iS[i][0]]))
.attr('x2', horizontal ? x(0.5) : x(probs[iS[i][1]]))
.attr('y1', horizontal ? y(probs[iS[i][0]]) : y(0.5))
.attr('y2', horizontal ? y(probs[iS[i][1]]) : y(0.5))
.style('stroke', boxColor);
}
boxplot
.append('circle')
.attr('class', 'boxplot mean')
.attr('cx', horizontal ? x(0.5) : x(d3.mean(results)))
.attr('cy', horizontal ? y(d3.mean(results)) : y(0.5))
.attr('r', horizontal ? x(boxPlotWidth / 3) : y(1 - boxPlotWidth / 3))
.style('fill', boxInsideColor)
.style('stroke', boxColor);
boxplot
.append('circle')
.attr('class', 'boxplot mean')
.attr('cx', horizontal ? x(0.5) : x(d3.mean(results)))
.attr('cy', horizontal ? y(d3.mean(results)) : y(0.5))
.attr('r', horizontal ? x(boxPlotWidth / 6) : y(1 - boxPlotWidth / 6))
.style('fill', boxColor)
.style('stroke', 'None');
var formatx = fmt ? d3.format(fmt) : d3.format('.2f');
boxplot
.selectAll('.boxplot')
.append('title')
.text(function(d) {
return (
'N = ' +
d.values.length +
'\n' +
'Min = ' +
d3.min(d.values) +
'\n' +
'5th % = ' +
formatx(d3.quantile(d.values, 0.05)) +
'\n' +
'Q1 = ' +
formatx(d3.quantile(d.values, 0.25)) +
'\n' +
'Median = ' +
formatx(d3.median(d.values)) +
'\n' +
'Q3 = ' +
formatx(d3.quantile(d.values, 0.75)) +
'\n' +
'95th % = ' +
formatx(d3.quantile(d.values, 0.95)) +
'\n' +
'Max = ' +
d3.max(d.values) +
'\n' +
'Mean = ' +
formatx(d3.mean(d.values)) +
'\n' +
'StDev = ' +
formatx(d3.deviation(d.values))
);
});
}
function addBoxPlots() {
// Y-axis box plot
var yValues = this.current_data.map(function(d) {
return d.values.y;
});
var ybox = this.svg.append('g').attr('class', 'yMargin');
drawBoxPlot(ybox, yValues, this.plot_height, 1, this.y_dom, 10, '#bbb', 'white');
ybox.select('g.boxplot').attr(
'transform',
'translate(' + (this.plot_width + this.config.margin.right / 2) + ',0)'
);
//X-axis box plot
var xValues = this.current_data.map(function(d) {
return d.values.x;
});
var xbox = this.svg.append('g').attr('class', 'xMargin');
drawBoxPlot(
xbox, //svg element
xValues, //values
1, //height
this.plot_width, //width
this.x_dom, //domain
10, //box plot width
'#bbb', //box color
'white', //detail color
'0.2f', //format
false // horizontal?
);
xbox.select('g.boxplot').attr(
'transform',
'translate(0,' + -(this.config.margin.top / 2) + ')'
);
}
function updateClipPath() {
//embiggen clip-path so points aren't clipped
var radius = this.config.marks.find(function(mark) {
return mark.type === 'circle';
}).radius;
this.svg
.select('.plotting-area')
.attr('width', this.plot_width + radius * 2 + 2) // plot width + circle radius * 2 + circle stroke width * 2
.attr('height', this.plot_height + radius * 2 + 2) // plot height + circle radius * 2 + circle stroke width * 2
.attr(
'transform',
'translate(-' +
(radius + 1) + // translate left circle radius + circle stroke width
',-' +
(radius + 1) + // translate up circle radius + circle stroke width
')'
);
}
function addSparkLines(d) {
var chart = this.chart;
var config = this.chart.config;
if (this.data.raw.length > 0) {
//don't try to draw sparklines if the table is empty
this.tbody
.selectAll('tr')
.style('background', 'none')
.style('border-bottom', '.5px solid black')
.each(function(row_d) {
//Spark line cell
var cell = d3
.select(this)
.select('td.spark')