Debian Codegraph @

bqplot/js/src/Boxplot.ts

raw
1 /* Copyright 2015 Bloomberg Finance L.P.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 import * as d3 from 'd3';
17 import { d3GetEvent } from './utils';
18 import * as _ from 'underscore';
19 import { Mark } from './Mark';
20 import { BoxplotModel } from './BoxplotModel';
21 import { applyStyles } from './utils';
22
23 interface BoxPlotData {
24 whiskerMax: number;
25 whiskerMin: number;
26 x: number;
27 boxUpper: number;
28 boxLower: number;
29 boxMedian: number;
30 dataDict: {
31 x: number;
32 q1: number;
33 q3: number;
34 median: number;
35 };
36 }
37
38 interface PointType {
39 x: number;
40 y: number;
41 }
42
43 export class Boxplot extends Mark {
44 async render() {
45 const base_creation_promise = super.render.apply(this);
46
47 this.selected_style = this.model.get('selected_style');
48 this.unselected_style = this.model.get('unselected_style');
49
50 this.display_el_classes = ['box'];
51
52 this.displayed.then(() => {
53 this.parent.tooltip_div.node().appendChild(this.tooltip_div.node());
54 this.create_tooltip();
55 });
56
57 await base_creation_promise;
58
59 this.event_listeners = {};
60 this.create_listeners();
61 this.process_interactions();
62 this.draw();
63 }
64
65 set_ranges() {
66 const xScale = this.scales.x;
67 if (xScale) {
68 xScale.set_range(this.parent.padded_range('x', xScale.model));
69 }
70
71 const yScale = this.scales.y;
72 if (yScale) {
73 yScale.set_range(this.parent.padded_range('y', yScale.model));
74 }
75 }
76
77 set_positional_scales() {
78 const x_scale = this.scales.x;
79 this.listenTo(x_scale, 'domain_changed', function () {
80 if (!this.model.dirty) {
81 this.draw();
82 }
83 });
84
85 const y_scale = this.scales.y;
86 this.listenTo(y_scale, 'domain_changed', function () {
87 if (!this.model.dirty) {
88 this.draw();
89 }
90 });
91 }
92
93 create_listeners() {
94 super.create_listeners.apply(this);
95
96 this.listenTo(this.model, 'change:tooltip', this.create_tooltip);
97 this.listenTo(this.model, 'change:stroke', this.updateStroke);
98 this.listenTo(this.model, 'change:opacities', this.updateOpacities);
99 this.listenTo(
100 this.model,
101 'change:outlier_fill_color',
102 this.updateOutlierFillColor
103 );
104 this.listenTo(this.model, 'change:box_fill_color', this.updateBoxFillColor);
105 this.listenTo(this.model, 'data_updated', this.draw);
106 this.listenTo(this.model, 'change:box_width', this.updateBoxWidth);
107 this.listenTo(this.model, 'change:selected', this.updateSelected);
108 this.listenTo(this.model, 'change:interactions', this.process_interactions);
109 this.listenTo(this.parent, 'bg_clicked', () => {
110 this.event_dispatcher('parent_clicked');
111 });
112 }
113
114 private updateStroke() {
115 const stroke = this.model.get('stroke');
116
117 this.d3el
118 .selectAll('.boxplot')
119 .selectAll('path, rect')
120 .style('stroke', stroke);
121
122 this.d3el.selectAll('.outlier').style('stroke', stroke);
123
124 if (this.legendEl) {
125 this.legendEl.selectAll('path').attr('stroke', stroke);
126 this.legendEl.selectAll('text').style('fill', stroke);
127 }
128 }
129
130 private updateOutlierFillColor() {
131 this.d3el
132 .selectAll('.outlier')
133 .style('fill', this.model.get('outlier_fill_color'));
134 }
135
136 private updateBoxFillColor() {
137 this.d3el.selectAll('.box').style('fill', this.model.get('box_fill_color'));
138 }
139
140 private updateOpacities() {
141 this.d3el
142 .selectAll('.boxplot')
143 .style('opacity', (d, i: number) => this.get_mark_opacity(d, i));
144
145 if (this.legendEl) {
146 this.legendEl
147 .selectAll('path')
148 .attr('opacity', (d, i: number) => this.get_mark_opacity(d, i));
149 }
150 }
151
152 private getBoxWidth() {
153 let width = this.model.get('box_width');
154
155 // null box_width means auto calculated box width
156 if (!width) {
157 const plotWidth = this.parent.plotarea_width;
158 const maxWidth = plotWidth / 10.0;
159 width = plotWidth / (this.model.mark_data.length + 1) / 1.5;
160 width = Math.min(width, maxWidth);
161 }
162
163 return width;
164 }
165
166 compute_view_padding() {
167 //This function sets the padding for the view through the constiables
168 //xPadding and y_padding which are view specific paddings in pixel
169 const xPadding = this.getBoxWidth() / 2.0 + 1;
170 if (xPadding !== this.xPadding) {
171 this.xPadding = xPadding;
172 this.trigger('mark_padding_updated');
173 }
174 }
175
176 private updateBoxWidth() {
177 this.compute_view_padding();
178 this.draw();
179 }
180
181 set_style_on_elements(style, indices) {
182 if (indices === undefined || indices.length === 0) {
183 return;
184 }
185 let elements = this.d3el.selectAll('.box');
186 elements = elements.filter((data, index) => {
187 return indices.indexOf(index) != -1;
188 });
189 applyStyles(elements, style);
190 }
191
192 set_default_style(indices) {
193 // For all the elements with index in the list indices, the default
194 // style is applied.
195 this.updateOutlierFillColor();
196 this.updateBoxFillColor();
197 this.updateStroke();
198 this.updateOpacities();
199 }
200
201 clear_style(style_dict, indices) {
202 let elements = this.d3el.selectAll('.boxplot');
203 if (indices !== undefined) {
204 elements = elements.filter((d, index) => {
205 return indices.indexOf(index) != -1;
206 });
207 }
208
209 const clearingStyle = {};
210 for (const key in style_dict) {
211 clearingStyle[key] = null;
212 }
213
214 applyStyles(elements, clearingStyle);
215 }
216
217 style_updated(new_style, indices) {
218 this.set_default_style(indices);
219 this.set_style_on_elements(new_style, indices);
220 }
221
222 selected_style_updated(model, style) {
223 this.selected_style = style;
224 this.style_updated(style, this.selected_indices);
225 }
226
227 unselected_style_updated(model, style) {
228 this.unselected_style = style;
229
230 const unselectedIndices = this.selected_indices
231 ? _.range(this.model.mark_data.length).filter((index) => {
232 return this.selected_indices.indexOf(index) == -1;
233 })
234 : [];
235 this.style_updated(style, unselectedIndices);
236 }
237
238 //FIXME: should use the selected_style logic
239 private updateSelectedColors(selected_indices) {
240 this.d3el.selectAll('.boxplot').style('stroke', this.model.get('stroke'));
241 }
242
243 selector_changed(point_selector, rect_selector) {
244 if (point_selector === undefined) {
245 this.model.set('selected', null);
246 this.touch();
247 this.updateSelectedColors([]);
248 return [];
249 }
250
251 const indices = new Uint32Array(_.range(this.pixelCoords.length));
252 const selected = indices.filter((index) =>
253 rect_selector(this.pixelCoords[index])
254 );
255 this.updateSelectedColors(selected);
256 this.model.set('selected', selected);
257 this.touch();
258 }
259
260 invert_point(pixel) {
261 if (pixel === undefined) {
262 this.updateSelectedColors([]);
263 this.model.set('selected', null);
264 this.touch();
265 return;
266 }
267
268 const absDiff = this.xPixels.map((elem) => {
269 return Math.abs(elem - pixel);
270 });
271 const selIndex = absDiff.indexOf(d3.min(absDiff));
272
273 this.model.set('selected', new Uint32Array([selIndex]));
274 this.updateSelectedColors([selIndex]);
275 this.touch();
276 return selIndex;
277 }
278
279 private prepareBoxPlots() {
280 // Sets plot data on this.plotData and this.outlierData
281 const autoDetectOutliers = this.model.get('auto_detect_outliers') !== false;
282
283 // convert the domain data to the boxes to be drawn on the screen
284 // find the quantiles, min/max and outliers for the box plot
285 this.plotData = [];
286 this.outlierData = [];
287 for (let i = 0; i < this.model.mark_data.length; ++i) {
288 const values = this.model.mark_data[i];
289
290 const dataDict = {
291 x: values[0],
292 q1: d3.quantile(values[1], 0.25),
293 q3: d3.quantile(values[1], 0.75),
294 median: d3.quantile(values[1], 0.5),
295 };
296
297 const x = this.scales.x.scale(dataDict.x);
298 const boxUpper = this.scales.y.scale(dataDict.q3);
299 const boxLower = this.scales.y.scale(dataDict.q1);
300 const boxMedian = this.scales.y.scale(dataDict.median);
301
302 // The domain Y to screen Y is an inverse scale, so be aware of that
303 // The max from the domain Y becomes min on the screen (display) scale
304 const iqr = boxLower - boxUpper;
305 const lowerBound = boxLower + 1.5 * iqr;
306 const upperBound = boxUpper - 1.5 * iqr;
307
308 let whiskerMax = Number.MAX_VALUE;
309 let whiskerMin = Number.MIN_VALUE;
310
311 for (let j = 0; j < values[1].length; ++j) {
312 const plotY = this.scales.y.scale(values[1][j]);
313
314 // Find the outlier
315 if (autoDetectOutliers && (plotY > lowerBound || plotY < upperBound)) {
316 this.outlierData.push({
317 x: this.scales.x.scale(values[0]),
318 y: plotY,
319 });
320 } else {
321 // Find the whisker points max and min from normal data.
322 // ( exclude the outliers )
323 if (plotY > whiskerMin) {
324 whiskerMin = plotY;
325 }
326
327 if (plotY < whiskerMax) {
328 whiskerMax = plotY;
329 }
330 }
331 }
332
333 this.plotData.push({
334 x,
335 boxLower,
336 boxMedian,
337 boxUpper,
338 whiskerMin,
339 whiskerMax,
340 dataDict,
341 });
342 }
343 }
344
345 process_click(interaction: string) {
346 super.process_click(interaction);
347
348 if (interaction === 'select') {
349 this.event_listeners.parent_clicked = this.resetSelection;
350 this.event_listeners.element_clicked = this.boxClickHandler;
351 }
352 }
353
354 private boxClickHandler(args) {
355 const index = args.index;
356 const that = this;
357 const idx = this.model.get('selected') || [];
358 let selected: number[] = Array.from(idx);
359 // index of box i. Checking if it is already present in the list.
360 const elem_index = selected.indexOf(index);
361 // Replacement for "Accel" modifier.
362 const accelKey = d3GetEvent().ctrlKey || d3GetEvent().metaKey;
363 if (elem_index > -1 && accelKey) {
364 // if the index is already selected and if accel key is
365 // pressed, remove the element from the list
366 selected.splice(elem_index, 1);
367 } else {
368 if (d3GetEvent().shiftKey) {
369 //If shift is pressed and the element is already
370 //selected, do not do anything
371 if (elem_index > -1) {
372 return;
373 }
374 //Add elements before or after the index of the current
375 //box which has been clicked
376 const min_index = selected.length !== 0 ? d3.min(selected) : -1;
377 const max_index =
378 selected.length !== 0
379 ? d3.max(selected)
380 : that.model.mark_data.length;
381 if (index > max_index) {
382 _.range(max_index + 1, index + 1).forEach((i) => {
383 selected.push(i);
384 });
385 } else if (index < min_index) {
386 _.range(index, min_index).forEach((i) => {
387 selected.push(i);
388 });
389 }
390 } else if (accelKey) {
391 //If accel is pressed and the box is not already selected
392 //add the box to the list of selected boxes.
393 selected.push(index);
394 }
395 // updating the array containing the box indexes selected
396 // and updating the style
397 else {
398 //if accel is not pressed, then clear the selected ones
399 //and set the current element to the selected
400 selected = [];
401 selected.push(index);
402 }
403 }
404 this.model.set(
405 'selected',
406 selected.length === 0 ? null : new Uint32Array(selected),
407 { updated_view: this }
408 );
409 this.touch();
410 const e = d3GetEvent();
411 if (e.cancelBubble !== undefined) {
412 // IE
413 e.cancelBubble = true;
414 }
415 if (e.stopPropagation) {
416 e.stopPropagation();
417 }
418 e.preventDefault();
419 }
420
421 private resetSelection() {
422 this.model.set('selected', null);
423 this.selected_indices = null;
424 this.touch();
425 }
426
427 private updateSelected(model, value) {
428 this.selected_indices = value;
429 this.apply_styles();
430 }
431
432 draw() {
433 this.set_ranges();
434 // get the visual representation of boxplots, set as state
435 this.prepareBoxPlots();
436
437 // Draw the visual elements with data which was bound
438 this.drawMarkPaths('.boxplot', this.d3el);
439 // Keep the pixel coordinates of the boxes, for interactions.
440 this.xPixels = this.model.mark_data.map(
441 (el) => this.scales.x.scale(el[0]) + this.scales.x.offset
442 );
443
444 const width = this.getBoxWidth() / 2;
445 this.pixelCoords = this.plotData.map((d) => {
446 return [
447 [d.x - width, d.x + width],
448 [d.boxLower, d.boxUpper],
449 ];
450 });
451 }
452
453 private drawMarkPaths(parentClass, selector) {
454 const color = this.model.get('color');
455 const boxplot = this.d3el.selectAll(parentClass).data(this.plotData);
456
457 const fillcolor = this.model.get('box_fill_color');
458 // Create new
459 const newBoxplots = boxplot
460 .enter()
461 .append('g')
462 .attr('class', 'boxplot')
463 .attr('id', (d, i) => {
464 return 'boxplot' + i;
465 });
466
467 ///////////////////////////////////////////////////////////////////
468 //
469 // We translate the whole element of 'boxplot' to the x location
470 // and then scale each of these elements with Y scale.
471 //
472 // ( ) <--- outliers (as circles)
473 // ( )
474 //
475 // ------- <--- whisker_max_end (path as the max)
476 // |
477 // | <--- whisker_max (path from top of the box to max)
478 // |
479 // ---------
480 // | |
481 // | |
482 // | | <--- box (as a rect)
483 // | |
484 // | |
485 // ---------
486 // |
487 // | <--- whisker_min (path from bottom of the box to min)
488 // |
489 // ------- <--- whisker_min_end (path at min value)
490 //
491 ///////////////////////////////////////////////////////////////////
492
493 newBoxplots.append('path').attr('class', 'whisker_max');
494 newBoxplots.append('path').attr('class', 'whisker_max_end');
495 newBoxplots.append('path').attr('class', 'whisker_min');
496 newBoxplots.append('path').attr('class', 'whisker_min_end');
497 newBoxplots.append('rect').attr('class', 'box');
498 newBoxplots.append('path').attr('class', 'median_line');
499 newBoxplots.append('g').attr('class', 'outliers');
500
501 const scaleX = this.scales.x;
502 const xOffset =
503 scaleX.model.type === 'ordinal' ? scaleX.scale.bandwidth() / 2 : 0;
504
505 selector
506 .selectAll('.boxplot')
507 .data(this.plotData)
508 .style('stroke', this.model.get('stroke'))
509 .style('opacity', color)
510 .attr('transform', (d, i) => {
511 return 'translate(' + (d.x + xOffset) + ', 0)';
512 });
513
514 //Box
515 const width = this.getBoxWidth();
516
517 selector
518 .selectAll('.box')
519 .data(this.plotData)
520 .style('fill', fillcolor)
521 .attr('x', -width / 2)
522 .attr('width', width)
523 .attr('y', (d: BoxPlotData) => d.boxUpper)
524 .attr('height', (d: BoxPlotData) => d.boxLower - d.boxUpper)
525 .on('click', (d: BoxPlotData, i: number) => {
526 return this.event_dispatcher('element_clicked', { data: d, index: i });
527 })
528 .on('mouseover', (d: BoxPlotData, i: number) => {
529 return this.event_dispatcher('mouse_over', { data: d, index: i });
530 })
531 .on('mousemove', (d: BoxPlotData, i: number) => {
532 return this.event_dispatcher('mouse_move');
533 })
534 .on('mouseout', (d: BoxPlotData, i: number) => {
535 return this.event_dispatcher('mouse_out');
536 });
537
538 //Median line
539 selector
540 .selectAll('.median_line')
541 .data(this.plotData)
542 .style('stroke-width', 2)
543 .attr('d', (d: BoxPlotData) => {
544 const x = 0;
545 const medianY = d.boxMedian;
546
547 return (
548 'M' +
549 (x - width / 2) +
550 ',' +
551 medianY +
552 ' L' +
553 (x + width / 2) +
554 ',' +
555 medianY
556 );
557 });
558
559 //Max and Min Whiskers
560 //Max to top of the Box
561 selector
562 .selectAll('.whisker_max')
563 .data(this.plotData)
564 .attr('d', (d: BoxPlotData) => {
565 const x = 0;
566 // The price points are sorted so the last element is the max
567 const maxY = d.whiskerMax;
568 const boxY = d.boxUpper;
569
570 return 'M' + x + ',' + maxY + ' L' + x + ',' + boxY;
571 })
572 .attr('stroke-dasharray', () => '5,5');
573
574 selector
575 .selectAll('.whisker_max_end')
576 .data(this.plotData)
577 .attr('d', (d: BoxPlotData) => {
578 const x = 0;
579 // The price points are sorted, so 1st element is min
580 const maxY = d.whiskerMax;
581
582 return (
583 'M' +
584 (x - width / 2) +
585 ',' +
586 maxY +
587 ' L' +
588 (x + width / 2) +
589 ',' +
590 maxY
591 );
592 });
593
594 //Min to the bottom of the box
595 //Max to top of the Box
596 selector
597 .selectAll('.whisker_min')
598 .data(this.plotData)
599 .attr('d', (d: BoxPlotData) => {
600 const x = 0;
601 // The price points are sorted, so 1st element is min
602 const minY = d.whiskerMin;
603 const boxY = d.boxLower;
604
605 return 'M' + x + ',' + minY + ' L' + x + ',' + boxY;
606 })
607 .attr('stroke-dasharray', () => '5,5');
608
609 selector
610 .selectAll('.whisker_min_end')
611 .data(this.plotData)
612 .attr('d', (d: BoxPlotData) => {
613 const x = 0;
614 // The price points are sorted, so 1st element is min
615 const minY = d.whiskerMin;
616
617 return (
618 'M' +
619 (x - width / 2) +
620 ',' +
621 minY +
622 ' L' +
623 (x + width / 2) +
624 ',' +
625 minY
626 );
627 });
628
629 boxplot.exit().remove();
630
631 // Add the outliers group
632 const outliers = selector.selectAll('.outlier').data(this.outlierData);
633
634 // Add/remove elements as needed
635 outliers.enter().append('circle').attr('class', 'outlier');
636 outliers.exit().remove();
637
638 // Set outlier data
639 selector
640 .selectAll('.outlier')
641 .data(this.outlierData)
642 .style('fill', this.model.get('outlier_fill_color'))
643 .attr('cx', (d: PointType) => d.x + xOffset)
644 .attr('r', 3)
645 .attr('cy', (d: PointType) => d.y);
646
647 this.apply_styles(this.selected_indices);
648 }
649
650 relayout() {
651 this.set_ranges();
652 this.compute_view_padding();
653
654 // We have to redraw every time that we relayout
655 this.draw();
656 }
657
658 draw_legend(elem, x_disp, y_disp, inter_x_disp, inter_y_disp) {
659 const stroke = this.model.get('stroke');
660 this.rectDim = inter_y_disp * 0.8;
661
662 this.legendEl = elem
663 .selectAll('.legend' + this.uuid)
664 .data([this.model.mark_data]);
665
666 const leg = this.legendEl
667 .enter()
668 .append('g')
669 .attr('transform', (d, i) => {
670 return 'translate(0, ' + (i * inter_y_disp + y_disp) + ')';
671 })
672 .attr('class', 'legend' + this.uuid)
673 .on('mouseover', _.bind(this.highlight_axes, this))
674 .on('mouseout', _.bind(this.unhighlight_axes, this));
675
676 // Add stroke color and set position
677 leg
678 .selectAll('path')
679 .attr('stroke', stroke)
680 .attr('transform', 'translate(' + this.rectDim / 2 + ',0)');
681
682 // Draw icon and text
683 // this.draw_legend_icon(that.rectDim, leg);
684 this.legendEl
685 .append('text')
686 .attr('class', 'legendtext')
687 .attr('x', this.rectDim * 1.2)
688 .attr('y', this.rectDim / 2)
689 .attr('dy', '0.35em')
690 .text((d, i: number) => this.model.get('labels')[i])
691 .style('fill', stroke);
692
693 this.legendEl = leg.merge(this.legendEl);
694
695 const max_length = d3.max(this.model.get('labels'), (d: any[]) => {
696 return d.length;
697 });
698
699 this.legendEl.exit().remove();
700
701 return [1, max_length];
702 }
703
704 private xPixels: number[];
705 private legendEl: d3.Selection<any, any, any, any>;
706 private outlierData: PointType[];
707 private pixelCoords: [[number, number], [number, number]][];
708 private plotData: BoxPlotData[];
709 private rectDim: number;
710
711 model: BoxplotModel;
712 }