Debian Codegraph @

bqplot/js/src/Axis.ts

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
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 { WidgetView } from '@jupyter-widgets/base';
17 import * as d3 from 'd3';
18 // const d3 =Object.assign({}, require("d3-axis"), require("d3-format"), require("d3-selection"), require("d3-selection-multi"), require("d3-time"), require("d3-time-format"));
19 import * as utils from './utils';
20 import * as _ from 'underscore';
21 import { applyAttrs, applyStyles } from './utils';
22 import { Figure } from './Figure';
23 import { Scale } from './Scale';
24 import { isOrdinalScale } from './OrdinalScale';
25 import { isDateScale } from './DateScale';
26 import { isLogScale } from './LogScale';
27 import { isLinearScale } from './LinearScale';
28 import { isDateColorScale } from './DateColorScale';
29 import { isColorScale } from './ColorScale';
30
31 // Polyfill for Math.log10 in IE11
32 Math.log10 =
33 Math.log10 ||
34 function (x) {
35 return Math.log(x) / Math.LN10;
36 };
37
38 const DATESCALE_WIDTH_THRESHOLD = 500;
39 const UNITS_ARRAY = ['em', 'ex', 'px'];
40
41 export class Axis extends WidgetView {
42 initialize() {
43 this.setElement(
44 document.createElementNS(d3.namespaces.svg, 'g') as HTMLElement
45 );
46 this.d3el = d3.select(this.el);
47 super.initialize.apply(this, arguments);
48 }
49
50 render() {
51 this.d3el.style('display', this.model.get('visible') ? 'inline' : 'none');
52 this.parent = this.options.parent;
53
54 const scale_promise = this.set_scale_promise(this.model.get('scale'));
55 const offset_promise = this.get_offset_promise();
56
57 Promise.all([scale_promise, offset_promise]).then(() => {
58 this.create_listeners();
59 this.create_axis();
60 this.set_scales_range();
61 this.update_scales();
62 this.set_tick_values();
63 this.tickformat_changed();
64 this.append_axis();
65 });
66 }
67 create_listeners() {
68 // Creates all event listeners
69
70 this.listenTo(this.model, 'change:scale', (model, value) => {
71 this.update_scale(model.previous('scale'), value);
72 // TODO: rescale_axis does too many things. Decompose
73 this.axis.scale(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>); // TODO: this is in redraw_axisline
74 this.rescale_axis();
75 });
76
77 // Tick attributes
78 this.listenTo(this.model, 'change:tick_values', this.set_tick_values);
79 this.listenTo(this.model, 'change:tick_format', this.tickformat_changed);
80 this.listenTo(this.model, 'change:tick_labels', this.tick_labels_changed);
81 this.listenTo(this.model, 'change:num_ticks', this.set_tick_values);
82 this.listenTo(this.model, 'change:tick_rotate', this.apply_tick_styling);
83 this.listenTo(this.model, 'change:tick_style', this.apply_tick_styling);
84
85 // Label attributes
86 this.model.on_some_change(
87 ['label', 'label_color'],
88 this.update_label,
89 this
90 );
91
92 // Axis attributes
93 this.listenTo(this.model, 'change:color', this.update_color);
94 this.model.on_some_change(
95 ['grid_color', 'grid_lines'],
96 this.update_grid_lines,
97 this
98 );
99 this.listenTo(
100 this.model,
101 'change:label_location',
102 this.update_label_location
103 );
104 this.listenTo(this.model, 'change:label_offset', this.update_label_offset);
105 this.listenTo(this.model, 'change:visible', this.update_visibility);
106 this.model.on_some_change(
107 ['side', 'orientation'],
108 this.update_display,
109 this
110 );
111 this.listenTo(this.model, 'change:offset', this.update_offset);
112 this.listenTo(this.parent, 'margin_updated', this.parent_margin_updated);
113 }
114
115 update_offset() {
116 const offset_creation_promise = this.get_offset_promise();
117 offset_creation_promise.then(() => {
118 this.set_scales_range();
119 this.update_offset_scale_domain();
120 this.g_axisline.attr('transform', this.get_axis_transform());
121 this.update_grid_lines();
122 });
123 }
124
125 update_display() {
126 this.g_axisline.remove();
127 this.create_axis();
128 this.set_tick_values();
129 this.set_scales_range();
130 this.tickformat_changed();
131 this.append_axis();
132 }
133
134 set_tick_values(animate?: boolean) {
135 // Sets specific tick values from "tick_values" parameter
136
137 let useticks = [];
138 const tick_values = this.model.get('tick_values');
139 const num_ticks = this.model.get('num_ticks');
140
141 if (
142 tick_values !== undefined &&
143 tick_values !== null &&
144 tick_values.length > 0
145 ) {
146 this.axis.tickValues(this.get_ticks_from_array_or_length(tick_values));
147 } else if (num_ticks !== undefined && num_ticks !== null) {
148 this.axis.tickValues(this.get_ticks_from_array_or_length());
149 } else {
150 if (isDateScale(this.axis_scale)) {
151 // Reduce number of suggested ticks if figure width is below the
152 // threshold. Note: "undefined" will result in the D3 default
153 // setting
154 const numDateTicks =
155 this.width < DATESCALE_WIDTH_THRESHOLD ? 5 : undefined;
156 const scale = this.axis_scale.scale;
157 this.axis.tickValues(scale.ticks(numDateTicks));
158 } else if (isOrdinalScale(this.axis_scale)) {
159 this.axis.tickValues(this.axis_scale.scale.domain());
160 } else if (isLogScale(this.axis_scale)) {
161 let i, r;
162 const scale = this.axis_scale.scale;
163 const allticks = scale.ticks();
164 const oom = Math.abs(Math.log10(scale.domain()[1] / scale.domain()[0]));
165 if (oom < 2) {
166 this.axis.tickValues(allticks);
167 } else if (oom < 7) {
168 useticks = [];
169 for (i = 0; i < allticks.length; i++) {
170 r = Math.abs(Math.log10(allticks[i]) % 1);
171 if (
172 Math.abs(r) < 0.001 ||
173 Math.abs(r - 1) < 0.001 ||
174 Math.abs(r - 0.30103) < 0.001 ||
175 Math.abs(r - 0.69897) < 0.001
176 ) {
177 useticks.push(allticks[i]);
178 }
179 }
180 this.axis.tickValues(useticks);
181 } else {
182 useticks = [];
183 const s = Math.round(oom / 10);
184 for (i = 0; i < allticks.length; i++) {
185 r = Math.abs(Math.log10(allticks[i]) % s);
186 if (Math.abs(r) < 0.001 || Math.abs(r - s) < 0.001) {
187 useticks.push(allticks[i]);
188 }
189 }
190 this.axis.tickValues(useticks);
191 }
192 } else if (
193 isLinearScale(this.axis_scale) ||
194 isColorScale(this.axis_scale)
195 ) {
196 this.axis.tickValues(this.axis_scale.scale.ticks());
197 }
198 }
199 if (this.g_axisline) {
200 this.g_axisline
201 .transition('set_tick_values')
202 .duration(
203 animate === true ? this.parent.model.get('animation_duration') : 0
204 )
205 .call(this.axis);
206
207 this.apply_tick_styling();
208 }
209 }
210
211 tickformat_changed() {
212 this.tick_format = this.generate_tick_formatter();
213 this.axis.tickFormat(this.tick_format);
214 if (this.g_axisline) {
215 this.g_axisline.call(this.axis);
216 }
217 this.apply_tick_styling();
218 }
219
220 tick_labels_changed() {
221 this.tickformat_changed();
222 }
223
224 apply_tick_styling() {
225 // Applies current tick styling to all displayed ticks
226 if (this.g_axisline) {
227 const tickText = this.g_axisline.selectAll('.tick text');
228 applyStyles(tickText, this.model.get('tick_style'));
229 tickText.attr('transform', this.get_tick_transforms());
230 }
231 }
232
233 get_tick_transforms() {
234 // parses object and returns a string that can be passed to a D3 as a
235 // set of options
236 // Note: Currently, only the `tick_rotate` attribute uses .transform()
237
238 const rotation = this.model.get('tick_rotate');
239 return `rotate(${rotation})`;
240 }
241
242 update_scales() {
243 // Updates the domains of both scales
244
245 this.update_scale_domain();
246 this.update_offset_scale_domain();
247 }
248
249 update_scale_domain() {
250 // Sets the scale domain (Range of input values)
251
252 const is_vertical = this.model.get('orientation') === 'vertical';
253
254 const initial_range = is_vertical
255 ? this.parent.padded_range('y', this.axis_scale.model)
256 : this.parent.padded_range('x', this.axis_scale.model);
257
258 const target_range = is_vertical
259 ? this.parent.range('y')
260 : this.parent.range('x');
261
262 this.axis_scale.expand_domain(initial_range, target_range);
263 this.axis.scale(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>);
264 }
265
266 update_offset_scale_domain() {
267 // Sets the domain (range of input values) of the offset scale
268
269 const is_vertical = this.model.get('orientation') === 'vertical';
270
271 if (this.offset_scale) {
272 const initial_range = !is_vertical
273 ? this.parent.padded_range('y', this.offset_scale.model)
274 : this.parent.padded_range('x', this.offset_scale.model);
275
276 const target_range = !is_vertical
277 ? this.parent.range('y')
278 : this.parent.range('x');
279
280 this.offset_scale.expand_domain(initial_range, target_range);
281 }
282 }
283
284 generate_tick_formatter() {
285 const default_formatter = this.generate_default_tick_formatter();
286 const tickLabels = this.model.get('tick_labels');
287 if (tickLabels && Object.keys(tickLabels).length > 0) {
288 const formatter = (data) => {
289 let value = tickLabels[data];
290 if (value === undefined) {
291 return default_formatter(data);
292 } else {
293 return value;
294 }
295 };
296 return formatter;
297 } else {
298 return default_formatter;
299 }
300 }
301
302 generate_default_tick_formatter() {
303 if (isDateScale(this.axis_scale) || isDateColorScale(this.axis_scale)) {
304 if (this.model.get('tick_format')) {
305 return d3.utcFormat(this.model.get('tick_format'));
306 } else {
307 return this.guess_tick_format();
308 }
309 } else if (isOrdinalScale(this.axis_scale)) {
310 const tick_format = this.model.get('tick_format');
311 if (tick_format) {
312 //TODO: This may not be the best way to do this. We can
313 //check the instance of the elements in the domain and
314 //apply the format depending on that.
315 if (utils.is_valid_time_format(tick_format)) {
316 return d3.utcFormat(tick_format);
317 } else {
318 return d3.format(tick_format);
319 }
320 }
321 return (d) => {
322 return d;
323 };
324 } else {
325 // linear or log scale
326 if (this.model.get('tick_format')) {
327 return d3.format(this.model.get('tick_format'));
328 }
329 return this.guess_tick_format();
330 }
331 }
332
333 set_scales_range() {
334 const is_vertical = this.model.get('orientation') === 'vertical';
335
336 this.axis_scale.set_range(is_vertical ? [this.height, 0] : [0, this.width]);
337 if (this.offset_scale) {
338 this.offset_scale.set_range(
339 is_vertical ? [0, this.width] : [this.height, 0]
340 );
341 }
342 }
343
344 create_axis() {
345 // Creates the initial D3 axis and sets it on this.axis
346
347 const is_vertical = this.model.get('orientation') === 'vertical';
348 const side = this.model.get('side');
349
350 if (is_vertical) {
351 this.axis =
352 side === 'right'
353 ? d3.axisRight(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>)
354 : d3.axisLeft(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>);
355 } else {
356 this.axis =
357 side === 'top'
358 ? d3.axisTop(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>)
359 : d3.axisBottom(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>);
360 }
361 }
362
363 append_axis() {
364 this.update_scales();
365
366 // Create initial SVG element
367 this.g_axisline = this.d3el
368 .append('g')
369 .attr('class', 'axis')
370 .attr('transform', this.get_axis_transform())
371 .call(this.axis);
372
373 // Create element for axis label
374 const lineText = this.g_axisline
375 .append('text')
376 .attr('class', 'axislabel')
377 .text(this.model.get('label'));
378 applyStyles(lineText, this.get_text_styling());
379 applyAttrs(lineText, this.get_label_attributes());
380
381 // Apply custom settings
382 this.update_grid_lines();
383 this.update_color();
384 this.apply_tick_styling();
385 this.update_label();
386 }
387
388 get_offset_promise() {
389 /*
390 * The offset may require the creation of a Scale, which is async
391 * Hence, get_offset_promise returns a promise.
392 */
393 let return_promise = Promise.resolve();
394 const offset = this.model.get('offset');
395 const is_vertical = this.model.get('orientation') === 'vertical';
396
397 if (offset.value !== undefined && offset.value !== null) {
398 //If scale is undefined but, the value is defined, then we have
399 //to
400 if (offset.scale === undefined) {
401 this.offset_scale = is_vertical
402 ? this.parent.scale_x
403 : this.parent.scale_y;
404 } else {
405 return_promise = this.create_child_view(offset.scale).then((view) => {
406 this.offset_scale = view as WidgetView as Scale;
407 if (
408 isLinearScale(this.offset_scale) ||
409 isDateScale(this.offset_scale) ||
410 isLogScale(this.offset_scale)
411 ) {
412 this.offset_scale.scale.clamp(true);
413 }
414 this.offset_scale.on('domain_changed', () => {
415 this.update_offset_scale_domain();
416 this.g_axisline.attr('transform', this.get_axis_transform());
417 this.update_grid_lines();
418 });
419 });
420 }
421 this.offset_value = offset.value;
422 } else {
423 //required if the offset has been changed from a valid value
424 //to null
425 this.offset_scale = this.offset_value = undefined;
426 }
427 return return_promise;
428 }
429
430 highlight() {
431 this.g_axisline.classed('axisbold', true);
432 }
433
434 unhighlight() {
435 this.g_axisline.classed('axisbold', false);
436 }
437
438 get_basic_transform() {
439 const is_vertical = this.model.get('orientation') === 'vertical';
440 const side = this.model.get('side');
441
442 if (is_vertical) {
443 return side === 'right' ? this.width : 0;
444 } else {
445 return side === 'top' ? 0 : this.height;
446 }
447 }
448
449 get_axis_transform() {
450 const is_vertical = this.model.get('orientation') === 'vertical';
451 if (is_vertical) {
452 return 'translate(' + this.process_offset() + ', 0)';
453 } else {
454 return 'translate(0, ' + this.process_offset() + ')';
455 }
456 }
457
458 process_offset() {
459 if (this.offset_scale === undefined || this.offset_scale === null) {
460 return this.get_basic_transform();
461 } else {
462 let value = this.offset_scale.scale(this.offset_value);
463 //The null check is required for two reasons. Value may be null
464 //or the scale is ordinal which does not include the value in
465 //its domain.
466 value = value === undefined ? this.get_basic_transform() : value;
467 return this.offset_scale.offset + value;
468 }
469 }
470
471 get_label_attributes() {
472 // Returns an object based on values of "label_location" and "label_offset"
473
474 let label_x = 0;
475 const label_location = this.model.get('label_location');
476 const label_offset = this.calculate_label_offset();
477 const is_vertical = this.model.get('orientation') === 'vertical';
478 const side = this.model.get('side');
479
480 if (is_vertical) {
481 if (label_location === 'start') {
482 label_x = -this.height;
483 } else if (label_location === 'middle') {
484 label_x = -this.height / 2;
485 }
486 if (side === 'right') {
487 return {
488 transform: 'rotate(-90)',
489 x: label_x,
490 y: label_offset,
491 dy: '1ex',
492 dx: '0em',
493 };
494 } else {
495 return {
496 transform: 'rotate(-90)',
497 x: label_x,
498 y: label_offset,
499 dy: '0em',
500 dx: '0em',
501 };
502 }
503 } else {
504 if (label_location === 'middle') {
505 label_x = this.width / 2;
506 } else if (label_location === 'end') {
507 label_x = this.width;
508 }
509 if (side === 'top') {
510 return {
511 x: label_x,
512 y: label_offset,
513 dy: '0.75ex',
514 dx: '0em',
515 transform: '',
516 };
517 } else {
518 return {
519 x: label_x,
520 y: label_offset,
521 dy: '0.25ex',
522 dx: '0em',
523 transform: '',
524 };
525 }
526 }
527 }
528
529 get_text_styling() {
530 // This function returns the text styling based on the attributes
531 // of the axis. As of now, only the text-anchor attribute is set.
532 // More can be added :)
533 const label_location = this.model.get('label_location');
534 if (label_location === 'start') {
535 return { 'text-anchor': 'start' };
536 } else if (label_location === 'end') {
537 return { 'text-anchor': 'end' };
538 } else {
539 return { 'text-anchor': 'middle' };
540 }
541 }
542
543 update_label() {
544 this.g_axisline.select('text.axislabel').text(this.model.get('label'));
545 this.d3el.selectAll('.axislabel').selectAll('text');
546 if (
547 this.model.get('label_color') !== '' &&
548 this.model.get('label_color') !== null
549 ) {
550 this.g_axisline
551 .select('text.axislabel')
552 .style('fill', this.model.get('label_color'));
553 this.d3el
554 .selectAll('.axislabel')
555 .selectAll('text')
556 .style('fill', this.model.get('label_color'));
557 }
558 }
559
560 update_label_location() {
561 const axisLabel = this.g_axisline.select('text.axislabel');
562 applyStyles(axisLabel, this.get_text_styling());
563 applyAttrs(axisLabel, this.get_label_attributes());
564 }
565
566 update_label_offset(model, offset) {
567 this.label_offset = this.calculate_label_offset();
568 this.g_axisline.select('text.axislabel').attr('y', this.label_offset);
569 }
570
571 calculate_label_offset() {
572 // If the label offset is not defined, depending on the orientation
573 // of the axis, an offset is set.
574
575 let label_offset = this.model.get('label_offset');
576 const is_vertical = this.model.get('orientation') === 'vertical';
577 const side = this.model.get('side');
578
579 if (!label_offset) {
580 if (!is_vertical) {
581 label_offset = '2em';
582 } else {
583 label_offset = '4ex';
584 }
585 }
586 // Label_offset is a signed distance from the axis line. Positive
587 // is away from the figure and negative is towards the figure. The
588 // notion of away and towards is different for left/right and
589 // top/bottom axis.
590 let index = -1;
591 for (let i = 0; i < UNITS_ARRAY.length && index === -1; i++) {
592 index = label_offset.indexOf(UNITS_ARRAY[i]);
593 }
594
595 if (index === -1) {
596 return label_offset;
597 }
598
599 if (side === 'top' || side === 'left') {
600 const num = -1 * parseInt(label_offset.substring(0, index));
601 label_offset = num + label_offset.substring(index);
602 }
603 return label_offset;
604 }
605
606 update_grid_lines(animate?: boolean) {
607 const grid_type = this.model.get('grid_lines');
608 const side = this.model.get('side');
609 const orientation = this.model.get('orientation');
610 const is_x = orientation !== 'vertical';
611 const animation_duration =
612 animate === true ? this.parent.model.get('animation_duration') : 0;
613
614 let tickSize = orientation === 'vertical' ? -this.width : -this.height;
615 let tickOffset = 0;
616
617 //apply offsets if applicable
618 if (this.offset_scale) {
619 const offset = this.offset_scale.scale(this.offset_value);
620
621 if (side === 'bottom' || side == 'right') {
622 tickSize = -offset;
623 tickOffset = is_x ? this.height - offset : this.width - offset;
624 } else {
625 tickSize += offset;
626 tickOffset = -offset;
627 }
628 }
629
630 if (grid_type !== 'none') {
631 this.axis.tickSizeInner(tickSize).tickSizeOuter(6);
632 } else {
633 this.axis.tickSize(6);
634 }
635
636 this.g_axisline.selectAll('.tick').classed('short', grid_type === 'none');
637
638 this.g_axisline
639 .transition('update_grid_lines')
640 .duration(animation_duration)
641 .call(this.axis)
642 .selectAll('.tick line')
643 .attr(
644 is_x ? 'y1' : 'x1',
645 this.offset_scale && grid_type !== 'none' ? tickOffset : null
646 )
647 .style('stroke-dasharray', grid_type === 'dashed' ? '5, 5' : null);
648
649 this.apply_tick_styling();
650
651 if (this.model.get('grid_color')) {
652 this.g_axisline
653 .selectAll('.tick line')
654 .style('stroke', this.model.get('grid_color'));
655 }
656 }
657
658 update_color() {
659 if (this.model.get('color')) {
660 this.d3el
661 .selectAll('.tick')
662 .selectAll('text')
663 .style('fill', this.model.get('color'));
664 this.d3el.selectAll('.domain').style('stroke', this.model.get('color'));
665 }
666 }
667
668 redraw_axisline() {
669 // TODO: This call might not be necessary
670 // TODO: Doesn't do what it states.
671 // Has to redraw from a clean slate
672 this.update_scales();
673
674 //animate axis and grid lines on domain changes
675 const animate = true;
676 this.set_tick_values(animate);
677 this.tickformat_changed();
678 this.update_grid_lines(animate);
679 }
680
681 rescale_axis() {
682 //function to be called when the range of the axis has been updated
683 //or the axis has to be repositioned.
684 this.set_scales_range();
685 //The following calls to update domains are made as the domain
686 //of the axis scale needs to be recalculated as the expansion due
687 //to the padding depends on the size of the canvas because of the
688 //presence of fixed pixel padding for the bounding box.
689 this.update_axis_domain();
690 this.update_scales();
691 this.g_axisline.attr('transform', this.get_axis_transform());
692 this.g_axisline.call(this.axis);
693 const axisLabel = this.g_axisline.select('text.axislabel');
694 applyAttrs(axisLabel, this.get_label_attributes());
695 applyStyles(axisLabel, this.get_text_styling());
696 // TODO: what follows is currently part of redraw_axisline
697 this.set_tick_values();
698 this.update_grid_lines();
699 this.apply_tick_styling();
700 }
701
702 update_axis_domain() {
703 const initial_range = this.vertical
704 ? this.parent.padded_range('y', this.axis_scale.model)
705 : this.parent.padded_range('x', this.axis_scale.model);
706 const target_range = this.vertical
707 ? this.parent.range('y')
708 : this.parent.range('x');
709 this.axis_scale.expand_domain(initial_range, target_range);
710 this.axis.scale(this.axis_scale.scale as d3.AxisScale<d3.AxisDomain>);
711 }
712
713 parent_margin_updated() {
714 // sets the new dimensions of the g element for the axis.
715 this.rescale_axis();
716 }
717
718 update_visibility(model, visible) {
719 this.d3el.style('display', visible ? 'inline' : 'none');
720 }
721
722 get_ticks_from_array_or_length(data_array?: any[]) {
723 // This function is to be called when the ticks are passed explicitly
724 // or the number of ticks to be drawn.
725 // Have to do different things based on the type of the scale.
726 // If an array is passed, then just scale and return equally spaced
727 // points in the array. This is the way it is done for ordinal
728 // scales.
729 let step, max;
730 const num_ticks = this.model.get('num_ticks');
731
732 if (isOrdinalScale(this.axis_scale)) {
733 data_array = this.axis_scale.scale.domain();
734 }
735 if (num_ticks !== undefined && num_ticks !== null && num_ticks < 2) {
736 return [];
737 }
738 if (data_array) {
739 if (
740 num_ticks == undefined ||
741 num_ticks == null ||
742 data_array.length <= num_ticks
743 ) {
744 return data_array;
745 } else {
746 step = Math.floor(data_array.length / (num_ticks - 1));
747 const indices = _.range(0, data_array.length, step);
748 return indices.map((index) => {
749 return data_array[index];
750 });
751 }
752 }
753 const scale_range = this.axis_scale.scale.domain();
754 const max_index = this.axis_scale.scale.domain().length - 1;
755 step =
756 ((scale_range[max_index] as any) - (scale_range[0] as any)) /
757 (num_ticks - 1);
758 if (isDateScale(this.axis_scale) || isDateColorScale(this.axis_scale)) {
759 //For date scale, the dates have to be converted into milliseconds
760 //since epoch time and then back.
761 scale_range[0] = (scale_range[0] as Date).getTime();
762 scale_range[max_index] = (scale_range[max_index] as Date).getTime();
763 max = (scale_range[max_index] as any) + step * 0.5;
764 const range_in_times = _.range(scale_range[0] as any, max, step);
765 return range_in_times.map((elem) => {
766 return new Date(elem);
767 });
768 } else {
769 max = (scale_range[max_index] as any) + step * 0.5;
770 return _.range(scale_range[0] as any, max, step);
771 }
772 }
773
774 set_scale_promise(model) {
775 // Sets the child scale
776 if (this.axis_scale) {
777 this.axis_scale.remove();
778 }
779 return this.create_child_view(model).then((view) => {
780 // Trigger the displayed event of the child view.
781 this.displayed.then(() => {
782 view.trigger('displayed');
783 });
784 this.axis_scale = view as WidgetView as Scale;
785 this.axis_scale.on('domain_changed', this.redraw_axisline, this);
786 this.axis_scale.on('highlight_axis', this.highlight, this);
787 this.axis_scale.on('unhighlight_axis', this.unhighlight, this);
788 });
789 }
790
791 update_scale(old, scale) {
792 // Called when the child scale changes
793 this.axis_scale.off();
794 this.set_scale_promise(scale);
795 }
796
797 _get_digits(number) {
798 return number === 0 ? 1 : Math.floor(Math.log10(Math.abs(number))) + 1;
799 }
800
801 _replace_trailing_zeros(str) {
802 //regex to replace the trailing
803 //zeros after the decimal point.
804 //Handles the case of exponentially formatted string
805 //TODO: Should be done in a single regex
806 const e_index = str.search('e');
807 if (e_index != -1) {
808 return (
809 str
810 .substring(0, e_index)
811 .replace(/(\.[0-9]*?)0+$/gi, '$1')
812 .replace(/\.$/, '') + str.substring(e_index)
813 );
814 } else {
815 return str.replace(/(\.[0-9]*?)0+$/gi, '$1').replace(/\.$/, '');
816 }
817 }
818
819 get_format_func(prec: number) {
820 if (prec === 0) {
821 // format this as an integer
822 return (number) => {
823 return d3.format('d')(Math.round(number));
824 };
825 }
826 //if it is -1, then it is a generic format
827 const fmt_string = prec == -1 ? '' : '.' + prec;
828 return (number) => {
829 const str = d3.format(fmt_string + 'g')(number);
830 const reg_str = str.replace(/-|\.|e/gi, '');
831 if (reg_str.length < 6) {
832 return this._replace_trailing_zeros(str);
833 } else {
834 //if length is more than 6, format it exponentially
835 if (fmt_string === '') {
836 //if fmt_string is "", then the number o/p can be
837 //arbitrarily large
838 let new_str = d3.format(fmt_string + 'e')(number);
839 if (new_str.length >= 7) {
840 //in the case of a round off error, setting the max
841 //limit to be 6
842 new_str = d3.format('.6e')(number);
843 }
844 return this._replace_trailing_zeros(new_str);
845 } else {
846 //Format with the precision required
847 return this._replace_trailing_zeros(
848 d3.format(fmt_string + 'e')(number)
849 );
850 }
851 }
852 };
853 }
854
855 _linear_scale_precision(): number {
856 if (!(isLinearScale(this.axis_scale) || isColorScale(this.axis_scale))) {
857 return -1;
858 }
859 let ticks: any[] = this.axis.tickValues();
860 // Case where all data is concentrated into one point.
861 if (ticks.length === 1) {
862 return 1;
863 }
864 const diff = Math.abs(ticks[1] - ticks[0]);
865 const max = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
866
867 const max_digits = this._get_digits(max);
868 // number of digits in the max
869 const diff_digits = this._get_digits(diff);
870 // number of digits in the min
871
872 const precision = Math.abs(max_digits - diff_digits);
873 // difference in the number of digits. The number of digits we have
874 // to display is the diff above + 1.
875 if (max_digits >= 0 && diff_digits > 0) {
876 if (max_digits <= 6) {
877 // format the number as an integer
878 return 0;
879 } else {
880 // precision plus 1 is returned here as they are the number of
881 // digits to be displayed. Capped at 6
882 return Math.min(precision, 6) + 1;
883 }
884 } else if (diff_digits <= 0) {
885 // return math.abs(diff_digits) + max_digits + 1. Capped at 6.
886 return Math.min(Math.abs(diff_digits) + max_digits, 6) + 1;
887 }
888 }
889
890 linear_sc_format() {
891 return this.get_format_func(this._linear_scale_precision());
892 }
893
894 date_sc_format() {
895 // assumes that scale is a linear date scale
896 if (!isDateScale(this.axis_scale)) {
897 return;
898 }
899 let ticks: any[] = this.axis.tickValues();
900 // diff is the difference between ticks in milliseconds
901 const diff = Math.abs(ticks[1] - ticks[0]);
902
903 const format_millisecond = d3.utcFormat('.%L'),
904 format_second = d3.utcFormat(':%S'),
905 format_minute = d3.utcFormat('%I:%M'),
906 format_hour = d3.utcFormat('%I %p'),
907 format_day = d3.utcFormat('%b %d'),
908 format_month = d3.utcFormat('%b %Y'),
909 format_year = d3.utcFormat('%Y');
910
911 return (date) => {
912 let div = 1000;
913 if (Math.floor(diff / div) === 0) {
914 //diff is less than a second
915 if (d3.utcSecond(date) < date) {
916 return format_millisecond(date);
917 } else if (d3.utcMinute(date) < date) {
918 return format_second(date);
919 } else {
920 return format_minute(date);
921 }
922 } else if (Math.floor(diff / (div *= 60)) === 0) {
923 //diff is less than a minute
924 if (d3.utcMinute(date) < date) {
925 return format_second(date);
926 } else {
927 return format_minute(date);
928 }
929 } else if (Math.floor(diff / (div *= 60)) === 0) {
930 // diff is less than an hour
931 if (d3.utcHour(date) < date) {
932 return format_minute(date);
933 } else {
934 return format_hour(date);
935 }
936 } else if (Math.floor(diff / (div *= 24)) === 0) {
937 //diff is less than a day
938 if (d3.utcDay(date) < date) {
939 return format_hour(date);
940 } else {
941 return format_day(date);
942 }
943 } else if (Math.floor(diff / (div *= 27)) === 0) {
944 //diff is less than a month
945 if (d3.utcMonth(date) < date) {
946 return format_day(date);
947 } else {
948 return format_month(date);
949 }
950 } else if (Math.floor(diff / (div *= 12)) === 0) {
951 //diff is less than a year
952 if (d3.utcMonth(date) < date) {
953 return format_day(date);
954 } else {
955 return format_month(date);
956 }
957 } else {
958 //diff is more than a year
959 if (d3.utcMonth(date) < date) {
960 return format_day(date);
961 } else if (d3.utcYear(date) < date) {
962 return format_month(date);
963 } else {
964 return format_year(date);
965 }
966 }
967 };
968 }
969
970 log_sc_format() {
971 return this.get_format_func(this._log_sc_precision());
972 }
973
974 _log_sc_precision(): number {
975 if (!isLogScale(this.axis_scale)) {
976 return -1;
977 }
978 let ticks: any[] = this.axis.tickValues();
979 const ratio = Math.abs(Math.log10(ticks[1] / ticks[0]));
980
981 if (ratio >= 0.301) {
982 //format them as they are with the max_length of 6
983 return -1;
984 } else {
985 //return a default of 3 digits of precision
986 return 3;
987 }
988 }
989
990 guess_tick_format() {
991 if (isDateScale(this.axis_scale) || isDateColorScale(this.axis_scale)) {
992 return this.date_sc_format();
993 } else if (
994 isLinearScale(this.axis_scale) ||
995 isColorScale(this.axis_scale)
996 ) {
997 return this.linear_sc_format();
998 } else if (isLogScale(this.axis_scale)) {
999 return this.log_sc_format();
1000 }
1001 }
1002
1003 get width(): number {
1004 return (
1005 this.parent.width - this.parent.margin.right - this.parent.margin.left
1006 );
1007 }
1008
1009 get height(): number {
1010 return (
1011 this.parent.height - this.parent.margin.top - this.parent.margin.bottom
1012 );
1013 }
1014
1015 get margin() {
1016 return this.parent.margin;
1017 }
1018
1019 axis_scale: Scale;
1020 axis: d3.Axis<d3.AxisDomain>;
1021 d3el: d3.Selection<HTMLElement, any, any, any>;
1022 g_axisline: d3.Selection<SVGGElement, any, any, any>;
1023 label_offset: string;
1024 offset_scale: Scale;
1025 offset_value: any;
1026 parent: Figure;
1027 tick_format: (d: number) => string;
1028 vertical: boolean;
1029 }