-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathaxes.js
1971 lines (1736 loc) · 68.5 KB
/
axes.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
/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var d3 = require('d3');
var isNumeric = require('fast-isnumeric');
var Plotly = require('../../plotly');
var Lib = require('../../lib');
var svgTextUtils = require('../../lib/svg_text_utils');
var Titles = require('../../components/titles');
var Color = require('../../components/color');
var Drawing = require('../../components/drawing');
var axes = module.exports = {};
axes.layoutAttributes = require('./layout_attributes');
axes.supplyLayoutDefaults = require('./layout_defaults');
axes.setConvert = require('./set_convert');
var axisIds = require('./axis_ids');
axes.id2name = axisIds.id2name;
axes.cleanId = axisIds.cleanId;
axes.list = axisIds.list;
axes.listIds = axisIds.listIds;
axes.getFromId = axisIds.getFromId;
axes.getFromTrace = axisIds.getFromTrace;
// find the list of possible axes to reference with an xref or yref attribute
// and coerce it to that list
axes.coerceRef = function(containerIn, containerOut, gd, axLetter, dflt) {
var axlist = gd._fullLayout._has('gl2d') ? [] : axes.listIds(gd, axLetter),
refAttr = axLetter + 'ref',
attrDef = {};
// data-ref annotations are not supported in gl2d yet
attrDef[refAttr] = {
valType: 'enumerated',
values: axlist.concat(['paper']),
dflt: dflt || axlist[0] || 'paper'
};
// xref, yref
return Lib.coerce(containerIn, containerOut, attrDef, refAttr);
};
// empty out types for all axes containing these traces
// so we auto-set them again
axes.clearTypes = function(gd, traces) {
if(!Array.isArray(traces) || !traces.length) {
traces = (gd._fullData).map(function(d, i) { return i; });
}
traces.forEach(function(tracenum) {
var trace = gd.data[tracenum];
delete (axes.getFromId(gd, trace.xaxis) || {}).type;
delete (axes.getFromId(gd, trace.yaxis) || {}).type;
});
};
// get counteraxis letter for this axis (name or id)
// this can also be used as the id for default counter axis
axes.counterLetter = function(id) {
var axLetter = id.charAt(0);
if(axLetter === 'x') return 'y';
if(axLetter === 'y') return 'x';
};
// incorporate a new minimum difference and first tick into
// forced
axes.minDtick = function(ax, newDiff, newFirst, allow) {
// doesn't make sense to do forced min dTick on log or category axes,
// and the plot itself may decide to cancel (ie non-grouped bars)
if(['log', 'category'].indexOf(ax.type) !== -1 || !allow) {
ax._minDtick = 0;
}
// null means there's nothing there yet
else if(ax._minDtick === null) {
ax._minDtick = newDiff;
ax._forceTick0 = newFirst;
}
else if(ax._minDtick) {
// existing minDtick is an integer multiple of newDiff
// (within rounding err)
// and forceTick0 can be shifted to newFirst
if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 &&
(((newFirst - ax._forceTick0) / newDiff % 1) +
1.000001) % 1 < 2e-6) {
ax._minDtick = newDiff;
ax._forceTick0 = newFirst;
}
// if the converse is true (newDiff is a multiple of minDtick and
// newFirst can be shifted to forceTick0) then do nothing - same
// forcing stands. Otherwise, cancel forced minimum
else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 ||
(((newFirst - ax._forceTick0) / ax._minDtick % 1) +
1.000001) % 1 > 2e-6) {
ax._minDtick = 0;
}
}
};
axes.getAutoRange = function(ax) {
var newRange = [];
var minmin = ax._min[0].val,
maxmax = ax._max[0].val,
i;
for(i = 1; i < ax._min.length; i++) {
if(minmin !== maxmax) break;
minmin = Math.min(minmin, ax._min[i].val);
}
for(i = 1; i < ax._max.length; i++) {
if(minmin !== maxmax) break;
maxmax = Math.max(maxmax, ax._max[i].val);
}
var j, minpt, maxpt, minbest, maxbest, dp, dv,
mbest = 0,
axReverse = (ax.range && ax.range[1] < ax.range[0]);
// one-time setting to easily reverse the axis
// when plotting from code
if(ax.autorange === 'reversed') {
axReverse = true;
ax.autorange = true;
}
for(i = 0; i < ax._min.length; i++) {
minpt = ax._min[i];
for(j = 0; j < ax._max.length; j++) {
maxpt = ax._max[j];
dv = maxpt.val - minpt.val;
dp = ax._length - minpt.pad - maxpt.pad;
if(dv > 0 && dp > 0 && dv / dp > mbest) {
minbest = minpt;
maxbest = maxpt;
mbest = dv / dp;
}
}
}
if(minmin === maxmax) {
newRange = axReverse ?
[minmin + 1, ax.rangemode !== 'normal' ? 0 : minmin - 1] :
[ax.rangemode !== 'normal' ? 0 : minmin - 1, minmin + 1];
}
else if(mbest) {
if(ax.type === 'linear' || ax.type === '-') {
if(ax.rangemode === 'tozero' && minbest.val >= 0) {
minbest = {val: 0, pad: 0};
}
else if(ax.rangemode === 'nonnegative') {
if(minbest.val - mbest * minbest.pad < 0) {
minbest = {val: 0, pad: 0};
}
if(maxbest.val < 0) {
maxbest = {val: 1, pad: 0};
}
}
// in case it changed again...
mbest = (maxbest.val - minbest.val) /
(ax._length - minbest.pad - maxbest.pad);
}
newRange = [
minbest.val - mbest * minbest.pad,
maxbest.val + mbest * maxbest.pad
];
// don't let axis have zero size
if(newRange[0] === newRange[1]) {
newRange = [newRange[0] - 1, newRange[0] + 1];
}
// maintain reversal
if(axReverse) {
newRange.reverse();
}
}
return newRange;
};
axes.doAutoRange = function(ax) {
if(!ax._length) ax.setScale();
// TODO do we really need this?
var hasDeps = (ax._min && ax._max && ax._min.length && ax._max.length);
if(ax.autorange && hasDeps) {
ax.range = axes.getAutoRange(ax);
// doAutoRange will get called on fullLayout,
// but we want to report its results back to layout
var axIn = ax._gd.layout[ax._name];
if(!axIn) ax._gd.layout[ax._name] = axIn = {};
if(axIn !== ax) {
axIn.range = ax.range.slice();
axIn.autorange = ax.autorange;
}
}
};
// save a copy of the initial axis ranges in fullLayout
// use them in mode bar and dblclick events
axes.saveRangeInitial = function(gd, overwrite) {
var axList = axes.list(gd, '', true),
hasOneAxisChanged = false;
for(var i = 0; i < axList.length; i++) {
var ax = axList[i];
var isNew = (ax._rangeInitial === undefined);
var hasChanged = (
isNew || !(
ax.range[0] === ax._rangeInitial[0] &&
ax.range[1] === ax._rangeInitial[1]
)
);
if((isNew && ax.autorange === false) || (overwrite && hasChanged)) {
ax._rangeInitial = ax.range.slice();
hasOneAxisChanged = true;
}
}
return hasOneAxisChanged;
};
// axes.expand: if autoranging, include new data in the outer limits
// for this axis
// data is an array of numbers (ie already run through ax.d2c)
// available options:
// vpad: (number or number array) pad values (data value +-vpad)
// ppad: (number or number array) pad pixels (pixel location +-ppad)
// ppadplus, ppadminus, vpadplus, vpadminus:
// separate padding for each side, overrides symmetric
// padded: (boolean) add 5% padding to both ends
// (unless one end is overridden by tozero)
// tozero: (boolean) make sure to include zero if axis is linear,
// and make it a tight bound if possible
var FP_SAFE = Number.MAX_VALUE / 2;
axes.expand = function(ax, data, options) {
if(!(ax.autorange || ax._needsExpand) || !data) return;
if(!ax._min) ax._min = [];
if(!ax._max) ax._max = [];
if(!options) options = {};
if(!ax._m) ax.setScale();
var len = data.length,
extrappad = options.padded ? ax._length * 0.05 : 0,
tozero = options.tozero && (ax.type === 'linear' || ax.type === '-'),
i, j, v, di, dmin, dmax,
ppadiplus, ppadiminus, includeThis, vmin, vmax;
function getPad(item) {
if(Array.isArray(item)) {
return function(i) { return Math.max(Number(item[i]||0), 0); };
}
else {
var v = Math.max(Number(item||0), 0);
return function() { return v; };
}
}
var ppadplus = getPad((ax._m > 0 ?
options.ppadplus : options.ppadminus) || options.ppad || 0),
ppadminus = getPad((ax._m > 0 ?
options.ppadminus : options.ppadplus) || options.ppad || 0),
vpadplus = getPad(options.vpadplus || options.vpad),
vpadminus = getPad(options.vpadminus || options.vpad);
function addItem(i) {
di = data[i];
if(!isNumeric(di)) return;
ppadiplus = ppadplus(i) + extrappad;
ppadiminus = ppadminus(i) + extrappad;
vmin = di - vpadminus(i);
vmax = di + vpadplus(i);
// special case for log axes: if vpad makes this object span
// more than an order of mag, clip it to one order. This is so
// we don't have non-positive errors or absurdly large lower
// range due to rounding errors
if(ax.type === 'log' && vmin < vmax / 10) { vmin = vmax / 10; }
dmin = ax.c2l(vmin);
dmax = ax.c2l(vmax);
if(tozero) {
dmin = Math.min(0, dmin);
dmax = Math.max(0, dmax);
}
// In order to stop overflow errors, don't consider points
// too close to the limits of js floating point
function goodNumber(v) {
return isNumeric(v) && Math.abs(v) < FP_SAFE;
}
if(goodNumber(dmin)) {
includeThis = true;
// take items v from ax._min and compare them to the
// presently active point:
// - if the item supercedes the new point, set includethis false
// - if the new pt supercedes the item, delete it from ax._min
for(j = 0; j < ax._min.length && includeThis; j++) {
v = ax._min[j];
if(v.val <= dmin && v.pad >= ppadiminus) {
includeThis = false;
}
else if(v.val >= dmin && v.pad <= ppadiminus) {
ax._min.splice(j, 1);
j--;
}
}
if(includeThis) {
ax._min.push({
val: dmin,
pad: (tozero && dmin === 0) ? 0 : ppadiminus
});
}
}
if(goodNumber(dmax)) {
includeThis = true;
for(j = 0; j < ax._max.length && includeThis; j++) {
v = ax._max[j];
if(v.val >= dmax && v.pad >= ppadiplus) {
includeThis = false;
}
else if(v.val <= dmax && v.pad <= ppadiplus) {
ax._max.splice(j, 1);
j--;
}
}
if(includeThis) {
ax._max.push({
val: dmax,
pad: (tozero && dmax === 0) ? 0 : ppadiplus
});
}
}
}
// For efficiency covering monotonic or near-monotonic data,
// check a few points at both ends first and then sweep
// through the middle
for(i = 0; i < 6; i++) addItem(i);
for(i = len - 1; i > 5; i--) addItem(i);
};
axes.autoBin = function(data, ax, nbins, is2d) {
var datamin = Lib.aggNums(Math.min, null, data),
datamax = Lib.aggNums(Math.max, null, data);
if(ax.type === 'category') {
return {
start: datamin - 0.5,
end: datamax + 0.5,
size: 1
};
}
var size0;
if(nbins) size0 = ((datamax - datamin) / nbins);
else {
// totally auto: scale off std deviation so the highest bin is
// somewhat taller than the total number of bins, but don't let
// the size get smaller than the 'nice' rounded down minimum
// difference between values
var distinctData = Lib.distinctVals(data),
msexp = Math.pow(10, Math.floor(
Math.log(distinctData.minDiff) / Math.LN10)),
// TODO: there are some date cases where this will fail...
minSize = msexp * Lib.roundUp(
distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true);
size0 = Math.max(minSize, 2 * Lib.stdev(data) /
Math.pow(data.length, is2d ? 0.25 : 0.4));
}
// piggyback off autotick code to make "nice" bin sizes
var dummyax = {
type: ax.type === 'log' ? 'linear' : ax.type,
range: [datamin, datamax]
};
axes.autoTicks(dummyax, size0);
var binstart = axes.tickIncrement(
axes.tickFirst(dummyax), dummyax.dtick, 'reverse'),
binend;
function nearEdge(v) {
// is a value within 1% of a bin edge?
return (1 + (v - binstart) * 100 / dummyax.dtick) % 100 < 2;
}
// check for too many data points right at the edges of bins
// (>50% within 1% of bin edges) or all data points integral
// and offset the bins accordingly
if(typeof dummyax.dtick === 'number') {
var edgecount = 0,
midcount = 0,
intcount = 0,
blankcount = 0;
for(var i = 0; i < data.length; i++) {
if(data[i] % 1 === 0) intcount++;
else if(!isNumeric(data[i])) blankcount++;
if(nearEdge(data[i])) edgecount++;
if(nearEdge(data[i] + dummyax.dtick / 2)) midcount++;
}
var datacount = data.length - blankcount;
if(intcount === datacount && ax.type !== 'date') {
// all integers: if bin size is <1, it's because
// that was specifically requested (large nbins)
// so respect that... but center the bins containing
// integers on those integers
if(dummyax.dtick < 1) {
binstart = datamin - 0.5 * dummyax.dtick;
}
// otherwise start half an integer down regardless of
// the bin size, just enough to clear up endpoint
// ambiguity about which integers are in which bins.
else binstart -= 0.5;
}
else if(midcount < datacount * 0.1) {
if(edgecount > datacount * 0.3 ||
nearEdge(datamin) || nearEdge(datamax)) {
// lots of points at the edge, not many in the middle
// shift half a bin
var binshift = dummyax.dtick / 2;
binstart += (binstart + binshift < datamin) ? binshift : -binshift;
}
}
var bincount = 1 + Math.floor((datamax - binstart) / dummyax.dtick);
binend = binstart + bincount * dummyax.dtick;
}
else {
// calculate the endpoint for nonlinear ticks - you have to
// just increment until you're done
binend = binstart;
while(binend <= datamax) {
binend = axes.tickIncrement(binend, dummyax.dtick);
}
}
return {
start: binstart,
end: binend,
size: dummyax.dtick
};
};
// ----------------------------------------------------
// Ticks and grids
// ----------------------------------------------------
// calculate the ticks: text, values, positioning
// if ticks are set to automatic, determine the right values (tick0,dtick)
// in any case, set tickround to # of digits to round tick labels to,
// or codes to this effect for log and date scales
axes.calcTicks = function calcTicks(ax) {
if(ax.tickmode === 'array') return arrayTicks(ax);
// calculate max number of (auto) ticks to display based on plot size
if(ax.tickmode === 'auto' || !ax.dtick) {
var nt = ax.nticks,
minPx;
if(!nt) {
if(ax.type === 'category') {
minPx = ax.tickfont ? (ax.tickfont.size || 12) * 1.2 : 15;
nt = ax._length / minPx;
}
else {
minPx = ax._id.charAt(0) === 'y' ? 40 : 80;
nt = Lib.constrain(ax._length / minPx, 4, 9) + 1;
}
}
axes.autoTicks(ax, Math.abs(ax.range[1] - ax.range[0]) / nt);
// check for a forced minimum dtick
if(ax._minDtick > 0 && ax.dtick < ax._minDtick * 2) {
ax.dtick = ax._minDtick;
ax.tick0 = ax._forceTick0;
}
}
// check for missing tick0
if(!ax.tick0) {
ax.tick0 = (ax.type === 'date') ?
new Date(2000, 0, 1).getTime() : 0;
}
// now figure out rounding of tick values
autoTickRound(ax);
// find the first tick
ax._tmin = axes.tickFirst(ax);
// check for reversed axis
var axrev = (ax.range[1] < ax.range[0]);
// return the full set of tick vals
var vals = [],
// add a tiny bit so we get ticks which may have rounded out
endtick = ax.range[1] * 1.0001 - ax.range[0] * 0.0001;
if(ax.type === 'category') {
endtick = (axrev) ? Math.max(-0.5, endtick) :
Math.min(ax._categories.length - 0.5, endtick);
}
for(var x = ax._tmin;
(axrev) ? (x >= endtick) : (x <= endtick);
x = axes.tickIncrement(x, ax.dtick, axrev)) {
vals.push(x);
// prevent infinite loops
if(vals.length > 1000) break;
}
// save the last tick as well as first, so we can
// show the exponent only on the last one
ax._tmax = vals[vals.length - 1];
var ticksOut = new Array(vals.length);
for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]);
return ticksOut;
};
function arrayTicks(ax) {
var vals = ax.tickvals,
text = ax.ticktext,
ticksOut = new Array(vals.length),
r0expanded = ax.range[0] * 1.0001 - ax.range[1] * 0.0001,
r1expanded = ax.range[1] * 1.0001 - ax.range[0] * 0.0001,
tickMin = Math.min(r0expanded, r1expanded),
tickMax = Math.max(r0expanded, r1expanded),
vali,
i,
j = 0;
// without a text array, just format the given values as any other ticks
// except with more precision to the numbers
if(!Array.isArray(text)) text = [];
for(i = 0; i < vals.length; i++) {
vali = ax.d2l(vals[i]);
if(vali > tickMin && vali < tickMax) {
if(text[i] === undefined) ticksOut[j] = axes.tickText(ax, vali);
else ticksOut[j] = tickTextObj(ax, vali, String(text[i]));
j++;
}
}
if(j < vals.length) ticksOut.splice(j, vals.length - j);
return ticksOut;
}
var roundBase10 = [2, 5, 10],
roundBase24 = [1, 2, 3, 6, 12],
roundBase60 = [1, 2, 5, 10, 15, 30],
// 2&3 day ticks are weird, but need something btwn 1&7
roundDays = [1, 2, 3, 7, 14],
// approx. tick positions for log axes, showing all (1) and just 1, 2, 5 (2)
// these don't have to be exact, just close enough to round to the right value
roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1],
roundLog2 = [-0.301, 0, 0.301, 0.699, 1];
function roundDTick(roughDTick, base, roundingSet) {
return base * Lib.roundUp(roughDTick / base, roundingSet);
}
// autoTicks: calculate best guess at pleasant ticks for this axis
// inputs:
// ax - an axis object
// roughDTick - rough tick spacing (to be turned into a nice round number)
// outputs (into ax):
// tick0: starting point for ticks (not necessarily on the graph)
// usually 0 for numeric (=10^0=1 for log) or jan 1, 2000 for dates
// dtick: the actual, nice round tick spacing, somewhat larger than roughDTick
// if the ticks are spaced linearly (linear scale, categories,
// log with only full powers, date ticks < month),
// this will just be a number
// months: M#
// years: M# where # is 12*number of years
// log with linear ticks: L# where # is the linear tick spacing
// log showing powers plus some intermediates:
// D1 shows all digits, D2 shows 2 and 5
axes.autoTicks = function(ax, roughDTick) {
var base;
if(ax.type === 'date') {
ax.tick0 = new Date(2000, 0, 1).getTime();
if(roughDTick > 15778800000) {
// years if roughDTick > 6mo
roughDTick /= 31557600000;
base = Math.pow(10, Math.floor(Math.log(roughDTick) / Math.LN10));
ax.dtick = 'M' + (12 * roundDTick(roughDTick, base, roundBase10));
}
else if(roughDTick > 1209600000) {
// months if roughDTick > 2wk
roughDTick /= 2629800000;
ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24);
}
else if(roughDTick > 43200000) {
// days if roughDTick > 12h
ax.dtick = roundDTick(roughDTick, 86400000, roundDays);
// get week ticks on sunday
ax.tick0 = new Date(2000, 0, 2).getTime();
}
else if(roughDTick > 1800000) {
// hours if roughDTick > 30m
ax.dtick = roundDTick(roughDTick, 3600000, roundBase24);
}
else if(roughDTick > 30000) {
// minutes if roughDTick > 30sec
ax.dtick = roundDTick(roughDTick, 60000, roundBase60);
}
else if(roughDTick > 500) {
// seconds if roughDTick > 0.5sec
ax.dtick = roundDTick(roughDTick, 1000, roundBase60);
}
else {
//milliseconds
base = Math.pow(10, Math.floor(Math.log(roughDTick) / Math.LN10));
ax.dtick = roundDTick(roughDTick, base, roundBase10);
}
}
else if(ax.type === 'log') {
ax.tick0 = 0;
//only show powers of 10
if(roughDTick > 0.7) ax.dtick = Math.ceil(roughDTick);
else if(Math.abs(ax.range[1] - ax.range[0]) < 1) {
// span is less than one power of 10
var nt = 1.5 * Math.abs((ax.range[1] - ax.range[0]) / roughDTick);
// ticks on a linear scale, labeled fully
roughDTick = Math.abs(Math.pow(10, ax.range[1]) -
Math.pow(10, ax.range[0])) / nt;
base = Math.pow(10, Math.floor(Math.log(roughDTick) / Math.LN10));
ax.dtick = 'L' + roundDTick(roughDTick, base, roundBase10);
}
else {
// include intermediates between powers of 10,
// labeled with small digits
// ax.dtick = "D2" (show 2 and 5) or "D1" (show all digits)
ax.dtick = (roughDTick > 0.3) ? 'D2' : 'D1';
}
}
else if(ax.type === 'category') {
ax.tick0 = 0;
ax.dtick = Math.ceil(Math.max(roughDTick, 1));
}
else {
// auto ticks always start at 0
ax.tick0 = 0;
base = Math.pow(10, Math.floor(Math.log(roughDTick) / Math.LN10));
ax.dtick = roundDTick(roughDTick, base, roundBase10);
}
// prevent infinite loops
if(ax.dtick === 0) ax.dtick = 1;
// TODO: this is from log axis histograms with autorange off
if(!isNumeric(ax.dtick) && typeof ax.dtick !== 'string') {
var olddtick = ax.dtick;
ax.dtick = 1;
throw 'ax.dtick error: ' + String(olddtick);
}
};
// after dtick is already known, find tickround = precision
// to display in tick labels
// for numeric ticks, integer # digits after . to round to
// for date ticks, the last date part to show (y,m,d,H,M,S)
// or an integer # digits past seconds
function autoTickRound(ax) {
var dtick = ax.dtick,
maxend;
ax._tickexponent = 0;
if(!isNumeric(dtick) && typeof dtick !== 'string') dtick = 1;
if(ax.type === 'category') ax._tickround = null;
else if(isNumeric(dtick) || dtick.charAt(0) === 'L') {
if(ax.type === 'date') {
if(dtick >= 86400000) ax._tickround = 'd';
else if(dtick >= 3600000) ax._tickround = 'H';
else if(dtick >= 60000) ax._tickround = 'M';
else if(dtick >= 1000) ax._tickround = 'S';
else ax._tickround = 3 - Math.round(Math.log(dtick / 2) / Math.LN10);
}
else {
if(!isNumeric(dtick)) dtick = Number(dtick.substr(1));
// 2 digits past largest digit of dtick
ax._tickround = 2 - Math.floor(Math.log(dtick) / Math.LN10 + 0.01);
if(ax.type === 'log') {
maxend = Math.pow(10, Math.max(ax.range[0], ax.range[1]));
}
else maxend = Math.max(Math.abs(ax.range[0]), Math.abs(ax.range[1]));
var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01);
if(Math.abs(rangeexp) > 3) {
if(ax.exponentformat === 'SI' || ax.exponentformat === 'B') {
ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3);
}
else ax._tickexponent = rangeexp;
}
}
}
else if(dtick.charAt(0) === 'M') ax._tickround = (dtick.length === 2) ? 'm' : 'y';
else ax._tickround = null;
}
// months and years don't have constant millisecond values
// (but a year is always 12 months so we only need months)
// log-scale ticks are also not consistently spaced, except
// for pure powers of 10
// numeric ticks always have constant differences, other datetime ticks
// can all be calculated as constant number of milliseconds
axes.tickIncrement = function(x, dtick, axrev) {
var axSign = axrev ? -1 : 1;
// includes all dates smaller than month, and pure 10^n in log
if(isNumeric(dtick)) return x + axSign * dtick;
var tType = dtick.charAt(0),
dtSigned = axSign * Number(dtick.substr(1));
// Dates: months (or years)
if(tType === 'M') {
var y = new Date(x);
// is this browser consistent? setMonth edits a date but
// returns that date's milliseconds
return y.setMonth(y.getMonth() + dtSigned);
}
// Log scales: Linear, Digits
else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10;
// log10 of 2,5,10, or all digits (logs just have to be
// close enough to round)
else if(tType === 'D') {
var tickset = (dtick === 'D2') ? roundLog2 : roundLog1,
x2 = x + axSign * 0.01,
frac = Lib.roundUp(mod(x2, 1), tickset, axrev);
return Math.floor(x2) +
Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
}
else throw 'unrecognized dtick ' + String(dtick);
};
// calculate the first tick on an axis
axes.tickFirst = function(ax) {
var axrev = ax.range[1] < ax.range[0],
sRound = axrev ? Math.floor : Math.ceil,
// add a tiny extra bit to make sure we get ticks
// that may have been rounded out
r0 = ax.range[0] * 1.0001 - ax.range[1] * 0.0001,
dtick = ax.dtick,
tick0 = ax.tick0;
if(isNumeric(dtick)) {
var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0;
// make sure no ticks outside the category list
if(ax.type === 'category') {
tmin = Lib.constrain(tmin, 0, ax._categories.length - 1);
}
return tmin;
}
var tType = dtick.charAt(0),
dtNum = Number(dtick.substr(1)),
t0,
mdif,
t1;
// Dates: months (or years)
if(tType === 'M') {
t0 = new Date(tick0);
r0 = new Date(r0);
mdif = (r0.getFullYear() - t0.getFullYear()) * 12 +
r0.getMonth() - t0.getMonth();
t1 = t0.setMonth(t0.getMonth() +
(Math.round(mdif / dtNum) + (axrev ? 1 : -1)) * dtNum);
while(axrev ? t1 > r0 : t1 < r0) {
t1 = axes.tickIncrement(t1, dtick, axrev);
}
return t1;
}
// Log scales: Linear, Digits
else if(tType === 'L') {
return Math.log(sRound(
(Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10;
}
else if(tType === 'D') {
var tickset = (dtick === 'D2') ? roundLog2 : roundLog1,
frac = Lib.roundUp(mod(r0, 1), tickset, axrev);
return Math.floor(r0) +
Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
}
else throw 'unrecognized dtick ' + String(dtick);
};
var yearFormat = d3.time.format('%Y'),
monthFormat = d3.time.format('%b %Y'),
dayFormat = d3.time.format('%b %-d'),
hourFormat = d3.time.format('%b %-d %Hh'),
minuteFormat = d3.time.format('%H:%M'),
secondFormat = d3.time.format(':%S');
// add one item to d3's vocabulary:
// %{n}f where n is the max number of digits
// of fractional seconds
var fracMatch = /%(\d?)f/g;
function modDateFormat(fmt, x) {
var fm = fmt.match(fracMatch),
d = new Date(x);
if(fm) {
var digits = Math.min(+fm[1] || 6, 6),
fracSecs = String((x / 1000 % 1) + 2.0000005)
.substr(2, digits).replace(/0+$/, '') || '0';
return d3.time.format(fmt.replace(fracMatch, fracSecs))(d);
}
else {
return d3.time.format(fmt)(d);
}
}
// draw the text for one tick.
// px,py are the location on gd.paper
// prefix is there so the x axis ticks can be dropped a line
// ax is the axis layout, x is the tick value
// hover is a (truthy) flag for whether to show numbers with a bit
// more precision for hovertext
axes.tickText = function(ax, x, hover) {
var out = tickTextObj(ax, x),
hideexp,
arrayMode = ax.tickmode === 'array',
extraPrecision = hover || arrayMode,
i;
if(arrayMode && Array.isArray(ax.ticktext)) {
var minDiff = Math.abs(ax.range[1] - ax.range[0]) / 10000;
for(i = 0; i < ax.ticktext.length; i++) {
if(Math.abs(x - ax.d2l(ax.tickvals[i])) < minDiff) break;
}
if(i < ax.ticktext.length) {
out.text = String(ax.ticktext[i]);
return out;
}
}
function isHidden(showAttr) {
var first_or_last;
if(showAttr === undefined) return true;
if(hover) return showAttr === 'none';
first_or_last = {
first: ax._tmin,
last: ax._tmax
}[showAttr];
return showAttr !== 'all' && x !== first_or_last;
}
hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : '';
if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision);
else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp);
else if(ax.type === 'category') formatCategory(ax, out);
else formatLinear(ax, out, hover, extraPrecision, hideexp);
// add prefix and suffix
if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text;
if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix;
return out;
};
function tickTextObj(ax, x, text) {
var tf = ax.tickfont || ax._gd._fullLayout.font;
return {
x: x,
dx: 0,
dy: 0,
text: text || '',
fontSize: tf.size,
font: tf.family,
fontColor: tf.color
};
}
function formatDate(ax, out, hover, extraPrecision) {
var x = out.x,
tr = ax._tickround,
d = new Date(x),
// suffix completes the full date info, to be included
// with only the first tick
suffix = '',
tt;
if(hover && ax.hoverformat) {
tt = modDateFormat(ax.hoverformat, x);
}
else if(ax.tickformat) {
tt = modDateFormat(ax.tickformat, x);
// TODO: potentially hunt for ways to automatically add more
// precision to the hover text?
}
else {
if(extraPrecision) {
if(isNumeric(tr)) tr += 2;
else tr = {y: 'm', m: 'd', d: 'H', H: 'M', M: 'S', S: 2}[tr];
}
if(tr === 'y') tt = yearFormat(d);
else if(tr === 'm') tt = monthFormat(d);
else {
if(x === ax._tmin && !hover) {
suffix = '<br>' + yearFormat(d);
}
if(tr === 'd') tt = dayFormat(d);
else if(tr === 'H') tt = hourFormat(d);
else {
if(x === ax._tmin && !hover) {
suffix = '<br>' + dayFormat(d) + ', ' + yearFormat(d);
}
tt = minuteFormat(d);
if(tr !== 'M') {
tt += secondFormat(d);
if(tr !== 'S') {
tt += numFormat(mod(x / 1000, 1), ax, 'none', hover)
.substr(1);
}
}
}
}
}
out.text = tt + suffix;
}
function formatLog(ax, out, hover, extraPrecision, hideexp) {
var dtick = ax.dtick,
x = out.x;
if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3';
if(ax.tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) {
out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision);
}
else if(isNumeric(dtick) || ((dtick.charAt(0) === 'D') && (mod(x + 0.01, 1) < 0.1))) {
if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1) {
var p = Math.round(x);
if(p === 0) out.text = 1;
else if(p === 1) out.text = '10';
else if(p > 1) out.text = '10<sup>' + p + '</sup>';
else out.text = '10<sup>\u2212' + -p + '</sup>';
out.fontSize *= 1.25;
}
else {
out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover');
if(dtick === 'D1' && ax._id.charAt(0) === 'y') {
out.dy -= out.fontSize / 6;
}
}
}
else if(dtick.charAt(0) === 'D') {
out.text = String(Math.round(Math.pow(10, mod(x, 1))));
out.fontSize *= 0.75;
}
else throw 'unrecognized dtick ' + String(dtick);
// if 9's are printed on log scale, move the 10's away a bit