Debian Codegraph @

bqplot/js/src/Hist.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 _ from 'underscore';
17 import * as d3 from 'd3';
18 import { d3GetEvent } from './utils';
19 import * as utils from './utils';
20 import { Mark } from './Mark';
21 import { HistModel, BinData } from './HistModel';
22 import { applyStyles } from './utils';
23
24 export class Hist extends Mark {
25 async render() {
26 const base_creation_promise = super.render();
27
28 this.selected_indices = this.dataIndexToBarIndex(
29 this.model.get('selected')
30 );
31 this.selected_style = this.model.get('selected_style');
32 this.unselected_style = this.model.get('unselected_style');
33
34 this.display_el_classes = ['rect', 'legendtext'];
35
36 this.displayed.then(() => {
37 this.parent.tooltip_div.node().appendChild(this.tooltip_div.node());
38 this.create_tooltip();
39 });
40
41 await base_creation_promise;
42
43 this.event_listeners = {};
44 this.process_interactions();
45 this.create_listeners();
46 this.draw();
47 this.update_selected(this.model, this.model.get('selected'));
48 }
49
50 set_ranges() {
51 const x_scale = this.scales.sample;
52 if (x_scale) {
53 x_scale.set_range(this.parent.padded_range('x', x_scale.model));
54 }
55 const y_scale = this.scales.count;
56 if (y_scale) {
57 y_scale.set_range(this.parent.padded_range('y', y_scale.model));
58 }
59 }
60
61 set_positional_scales() {
62 // In the case of Hist, a change in the "sample" scale triggers
63 // a full "update_data" instead of a simple redraw.
64 const x_scale = this.scales.sample,
65 y_scale = this.scales.count;
66 this.listenTo(x_scale, 'domain_changed', function () {
67 if (!this.model.dirty) {
68 this.model.update_data();
69 }
70 });
71 this.listenTo(y_scale, 'domain_changed', function () {
72 if (!this.model.dirty) {
73 this.draw();
74 }
75 });
76 }
77
78 create_listeners() {
79 super.create_listeners();
80 this.d3el
81 .on('mouseover', () => {
82 this.event_dispatcher('mouse_over');
83 })
84 .on('mousemove', () => {
85 this.event_dispatcher('mouse_move');
86 })
87 .on('mouseout', () => {
88 this.event_dispatcher('mouse_out');
89 });
90
91 this.listenTo(this.model, 'change:tooltip', this.create_tooltip);
92 this.listenTo(this.model, 'data_updated', this.draw);
93 this.listenTo(this.model, 'change:colors', this.updateColors);
94 this.model.on_some_change(
95 ['stroke', 'opacities'],
96 this.updateStrokeAndOpacities,
97 this
98 );
99 this.listenTo(this.model, 'change:selected', this.update_selected);
100 this.listenTo(this.model, 'change:interactions', this.process_interactions);
101 this.listenTo(this.parent, 'bg_clicked', function () {
102 this.event_dispatcher('parent_clicked');
103 });
104 }
105
106 process_click(interaction) {
107 super.process_click(interaction);
108 if (interaction === 'select') {
109 this.event_listeners.parent_clicked = this.resetSelection;
110 this.event_listeners.element_clicked = this.barClickHandler;
111 }
112 }
113
114 private updateColors() {
115 this.d3el
116 .selectAll('.bargroup')
117 .selectAll('rect')
118 .style('fill', (d: BinData) => {
119 return this.get_colors(d.index);
120 });
121 if (this.model.get('labels')) {
122 this.d3el
123 .selectAll('.bargroup')
124 .selectAll('text')
125 .style('fill', (d: BinData) => {
126 return this.get_colors(d.index);
127 });
128 }
129 if (this.legend_el) {
130 this.legend_el.selectAll('rect').style('fill', (d: BinData) => {
131 return this.get_colors(d.index);
132 });
133 this.legend_el.selectAll('text').style('fill', (d: BinData) => {
134 return this.get_colors(d.index);
135 });
136 }
137 }
138
139 private updateStrokeAndOpacities() {
140 const stroke = this.model.get('stroke');
141 const opacities = this.model.get('opacities');
142 this.d3el
143 .selectAll('.rect')
144 .style('stroke', stroke)
145 .style('opacity', (d: BinData) => {
146 return opacities[d.index];
147 });
148 }
149
150 private computeBarWidth() {
151 const xScale = this.scales.sample;
152 let width =
153 (xScale.scale(this.model.maxX) - xScale.scale(this.model.minX)) /
154 this.model.bins;
155
156 if (width >= 10) {
157 width -= 2;
158 }
159
160 return width;
161 }
162
163 relayout() {
164 this.set_ranges();
165
166 const x_scale = this.scales.sample,
167 y_scale = this.scales.count;
168 this.d3el
169 .selectAll('.bargroup')
170 .attr('transform', (d: BinData, i: number) => {
171 return (
172 'translate(' +
173 x_scale.scale(d.bin.x0) +
174 ',' +
175 y_scale.scale(this.model.count[i]) +
176 ')'
177 );
178 });
179 const bar_width = this.computeBarWidth();
180 this.d3el
181 .selectAll('.bargroup')
182 .select('rect')
183 .transition('relayout')
184 .duration(this.parent.model.get('animation_duration'))
185 .attr('x', 2)
186 .attr('width', bar_width)
187 .attr('height', (d: BinData, i: number) => {
188 return y_scale.scale(0) - y_scale.scale(this.model.count[i]);
189 });
190 }
191
192 draw() {
193 this.set_ranges();
194
195 const x_scale = this.scales.sample,
196 y_scale = this.scales.count;
197 const bar_width = this.computeBarWidth();
198 let bar_groups: d3.Selection<any, any, any, any> = this.d3el
199 .selectAll('.bargroup')
200 .data(this.model.mark_data);
201
202 bar_groups.exit().remove();
203
204 const bars_added = bar_groups.enter().append('g').attr('class', 'bargroup');
205
206 // initial values for width and height are set for animation
207 bars_added
208 .append('rect')
209 .attr('class', 'rect')
210 .attr('x', 2)
211 .attr('width', 0)
212 .attr('height', 0);
213
214 bar_groups = bars_added.merge(bar_groups);
215
216 bar_groups.attr('transform', (d: BinData, i: number) => {
217 return (
218 'translate(' +
219 x_scale.scale(d.bin.x0) +
220 ',' +
221 y_scale.scale(this.model.count[i]) +
222 ')'
223 );
224 });
225
226 bar_groups
227 .select('.rect')
228 .style('fill', (d: BinData, i) => {
229 return this.get_colors(d.index);
230 })
231 .on('click', (d, i) => {
232 return this.event_dispatcher('element_clicked', {
233 data: d,
234 index: d.index,
235 });
236 })
237 .attr('id', (d, i) => {
238 return 'rect' + i;
239 })
240 .transition('draw')
241 .duration(this.parent.model.get('animation_duration'))
242 .attr('width', bar_width)
243 .attr('height', (d: BinData, i: number) => {
244 return y_scale.scale(0) - y_scale.scale(this.model.count[i]);
245 });
246
247 //bin_pixels contains the pixel values of the start points of each
248 //of the bins and the end point of the last bin.
249 this.bin_pixels = this.model.xBins.map((el) => {
250 return x_scale.scale(el) + x_scale.offset;
251 });
252 // pixel coords contains the [x0, x1] and [y0, y1] of each bin
253 this.pixel_coords = this.model.mark_data.map((d, i) => {
254 const x: number = x_scale.scale(d.bin.x0);
255 const y0: number = y_scale.scale(0);
256 const y1: number = y_scale.scale(this.model.count[i]);
257 return [
258 [x, x + bar_width],
259 [y0, y1],
260 ];
261 });
262 this.updateStrokeAndOpacities();
263 }
264
265 private barClickHandler(args) {
266 const index = args.index;
267 //code repeated from bars. We should unify the two.
268 const idx = this.selected_indices;
269 let selected: number[] = idx ? utils.deepCopy(idx) : [];
270 // index of bar i. Checking if it is already present in the list.
271 const elem_index = selected.indexOf(index);
272 // Replacement for "Accel" modifier.
273 const accelKey = d3GetEvent().ctrlKey || d3GetEvent().metaKey;
274 if (elem_index > -1 && accelKey) {
275 // if the index is already selected and if accel key is
276 // pressed, remove the element from the list
277 selected.splice(elem_index, 1);
278 } else {
279 if (d3GetEvent().shiftKey) {
280 //If shift is pressed and the element is already
281 //selected, do not do anything
282 if (elem_index > -1) {
283 return;
284 }
285 //Add elements before or after the index of the current
286 //bar which has been clicked
287 const min_index = selected.length !== 0 ? d3.min(selected) : -1;
288 const max_index =
289 selected.length !== 0
290 ? d3.max(selected)
291 : this.model.mark_data.length;
292 if (index > max_index) {
293 _.range(max_index + 1, index + 1).forEach((i) => {
294 selected.push(i);
295 });
296 } else if (index < min_index) {
297 _.range(index, min_index).forEach((i) => {
298 selected.push(i);
299 });
300 }
301 } else if (accelKey) {
302 //If accel is pressed and the bar is not already selected
303 //add the bar to the list of selected bars.
304 selected.push(index);
305 }
306 // updating the array containing the bar indexes selected
307 // and updating the style
308 else {
309 //if accel is not pressed, then clear the selected ones
310 //and set the current element to the selected
311 selected = [];
312 selected.push(index);
313 }
314 }
315 this.selected_indices = selected;
316 this.model.set(
317 'selected',
318 selected.length === 0 ? null : this.computeDataIndices(selected),
319 { updated_view: this }
320 );
321 this.touch();
322 const e = d3GetEvent();
323 if (e.cancelBubble !== undefined) {
324 // IE
325 e.cancelBubble = true;
326 }
327 if (e.stopPropagation) {
328 e.stopPropagation();
329 }
330 e.preventDefault();
331 }
332
333 draw_legend(elem, x_disp, y_disp, inter_x_disp, inter_y_disp) {
334 this.legend_el = elem
335 .selectAll('.legend' + this.uuid)
336 .data([this.model.mark_data[0]]);
337
338 const rect_dim = inter_y_disp * 0.8;
339 const new_legend = this.legend_el
340 .enter()
341 .append('g')
342 .attr('class', 'legend' + this.uuid)
343 .attr('transform', (d, i) => {
344 return 'translate(0, ' + (i * inter_y_disp + y_disp) + ')';
345 })
346 .on('mouseover', () => {
347 this.event_dispatcher('legend_mouse_over');
348 })
349 .on('mouseout', () => {
350 this.event_dispatcher('legend_mouse_out');
351 })
352 .on('click', () => {
353 this.event_dispatcher('legend_clicked');
354 });
355
356 new_legend
357 .append('rect')
358 .style('fill', (d, i) => {
359 return this.get_colors(i);
360 })
361 .attr('x', 0)
362 .attr('y', 0)
363 .attr('width', rect_dim)
364 .attr('height', rect_dim);
365
366 new_legend
367 .append('text')
368 .attr('class', 'legendtext')
369 .attr('x', rect_dim * 1.2)
370 .attr('y', rect_dim / 2)
371 .attr('dy', '0.35em')
372 .text((d, i) => {
373 return this.model.get('labels')[i];
374 })
375 .style('fill', (d, i) => {
376 return this.get_colors(i);
377 });
378
379 this.legend_el = new_legend.merge(this.legend_el);
380
381 const max_length = d3.max(this.model.get('labels'), (d: any[]) => {
382 return d.length;
383 });
384
385 this.legend_el.exit().remove();
386 return [1, max_length];
387 }
388
389 update_selected(model, value) {
390 this.selected_indices = this.dataIndexToBarIndex(value);
391 this.apply_styles();
392 }
393
394 clear_style(style_dict, indices?) {
395 let elements = this.d3el.selectAll('.bargroup');
396 if (indices) {
397 elements = elements.filter((d, index) => {
398 return indices.indexOf(index) !== -1;
399 });
400 }
401 const clearing_style = {};
402 for (const key in style_dict) {
403 clearing_style[key] = null;
404 }
405 applyStyles(elements.selectAll('.bar'), clearing_style);
406 }
407
408 set_default_style(indices, elements?) {
409 this.updateColors();
410 this.updateStrokeAndOpacities();
411 }
412
413 set_style_on_elements(style, indices) {
414 // If the index array is undefined or of length=0, exit the
415 // function without doing anything
416 if (indices === undefined || indices === null || indices.length === 0) {
417 return;
418 }
419 // Also, return if the style object itself is blank
420 if (Object.keys(style).length === 0) {
421 return;
422 }
423 let elements = this.d3el.selectAll('.bargroup');
424 elements = elements.filter((data, index) => {
425 return indices.indexOf(index) !== -1;
426 });
427 applyStyles(elements.selectAll('.rect'), style);
428 }
429
430 invert_point(pixel) {
431 // Sets the selected to the data contained in the bin closest
432 // to the value of the pixel.
433 // Used by Index Selector.
434 if (pixel === undefined) {
435 this.model.set('selected', null);
436 this.touch();
437 return;
438 }
439
440 const bar_width = this.computeBarWidth();
441
442 //adding "bar_width / 2.0" to bin_pixels as we need to select the
443 //bar whose center is closest to the current location of the mouse.
444 const abs_diff = this.bin_pixels.map((elem) => {
445 return Math.abs(elem + bar_width / 2.0 - pixel);
446 });
447 const sel_index = abs_diff.indexOf(d3.min(abs_diff));
448 this.model.set('selected', this.computeDataIndices([sel_index]));
449 this.touch();
450 }
451
452 selector_changed(point_selector, rect_selector) {
453 if (point_selector === undefined) {
454 this.model.set('selected', null);
455 this.touch();
456 return [];
457 }
458 const pixels = this.pixel_coords;
459 const indices = new Uint32Array(_.range(pixels.length));
460 const selected_bins = indices.filter((index) => {
461 return rect_selector(pixels[index]);
462 });
463 this.model.set('selected', this.computeDataIndices(selected_bins));
464 this.touch();
465 }
466
467 private computeDataIndices(indices) {
468 //input is a list of indices corresponding to the bars. Output is
469 //the list of indices in the data
470 const intervals = this.reduceIntervals(indices);
471 if (intervals.length === 0) {
472 return [];
473 }
474
475 const x_data = this.model.get('sample');
476 const num_intervals = intervals.length;
477 const indices_data = new Uint32Array(_.range(x_data.length));
478 const selected = indices_data.filter((index) => {
479 const elem = x_data[index];
480 for (let iter = 0; iter < num_intervals; iter++) {
481 if (elem <= intervals[iter][1] && elem >= intervals[iter][0]) {
482 return true;
483 }
484 }
485 return false;
486 });
487 return selected;
488 }
489
490 private reduceIntervals(indices: number[]) {
491 //for a series of indices, reduces them to the minimum possible
492 //intervals on which the search can be performed.
493 //return value is an array of arrays containing the start and end
494 //points of the intervals represented by the indices.
495 const intervals = [];
496 const nBins = this.model.bins;
497 const barWidth = (this.model.maxX - this.model.minX) / this.model.bins;
498
499 if (indices.length !== 0) {
500 indices.sort();
501 let start = indices[0];
502 let end = indices[0];
503 for (let iter = 1; iter < indices.length; iter++) {
504 if (indices[iter] === end + 1) {
505 end++;
506 } else {
507 intervals.push([
508 this.model.xBins[start],
509 end + 1 == nBins
510 ? this.model.xBins[nBins - 1] + barWidth
511 : this.model.xBins[end + 1],
512 ]);
513 start = end = indices[iter];
514 }
515 }
516 intervals.push([
517 this.model.xBins[start],
518 end + 1 == nBins
519 ? this.model.xBins[nBins - 1] + barWidth
520 : this.model.xBins[end + 1],
521 ]);
522 }
523 return intervals;
524 }
525
526 private dataIndexToBarIndex(selected) {
527 //function to calculate bar indices for a given list of data
528 //indices
529 if (selected === null) {
530 return null;
531 }
532
533 const x_data = this.model.get('sample');
534 const data = Array.from(selected).map((idx: number) => {
535 return x_data[idx];
536 });
537 let bar_indices = [];
538 for (let iter = 0; iter < data.length; iter++) {
539 //xBins is of length num_bars+1. So if the max element is
540 //selected, we get a bar index which is equal to num_bars.
541 let index = Math.min(
542 _.indexOf(this.model.xBins, data[iter], true),
543 this.model.xBins.length - 2
544 );
545 //if the data point is not one of the bins, then find the index
546 //where it is to be inserted.
547 if (index === -1) {
548 index = _.sortedIndex(this.model.xBins, data[iter]) - 1;
549 }
550 bar_indices.push(index);
551 }
552 bar_indices.sort();
553 bar_indices = _.uniq(bar_indices, true);
554 return bar_indices;
555 }
556
557 private resetSelection() {
558 this.selected_indices = [];
559 this.model.set('selected', null);
560 this.touch();
561 }
562
563 compute_view_padding() {}
564
565 selected_indices: number[];
566 legend_el: d3.Selection<SVGGElement, any, any, any>;
567 bin_pixels: number[];
568 pixel_coords: [number[], number[]][];
569
570 model: HistModel;
571 }