/
ticker.py
2869 lines (2399 loc) · 97.8 KB
/
ticker.py
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
"""
Tick locating and formatting
============================
This module contains classes for configuring tick locating and formatting.
Generic tick locators and formatters are provided, as well as domain specific
custom ones.
Although the locators know nothing about major or minor ticks, they are used
by the Axis class to support major and minor tick locating and formatting.
Tick locating
-------------
The Locator class is the base class for all tick locators. The locators
handle autoscaling of the view limits based on the data limits, and the
choosing of tick locations. A useful semi-automatic tick locator is
`MultipleLocator`. It is initialized with a base, e.g., 10, and it picks
axis limits and ticks that are multiples of that base.
The Locator subclasses defined here are
:class:`AutoLocator`
`MaxNLocator` with simple defaults. This is the default tick locator for
most plotting.
:class:`MaxNLocator`
Finds up to a max number of intervals with ticks at nice locations.
:class:`LinearLocator`
Space ticks evenly from min to max.
:class:`LogLocator`
Space ticks logarithmically from min to max.
:class:`MultipleLocator`
Ticks and range are a multiple of base; either integer or float.
:class:`FixedLocator`
Tick locations are fixed.
:class:`IndexLocator`
Locator for index plots (e.g., where ``x = range(len(y))``).
:class:`NullLocator`
No ticks.
:class:`SymmetricalLogLocator`
Locator for use with with the symlog norm; works like `LogLocator` for the
part outside of the threshold and adds 0 if inside the limits.
:class:`LogitLocator`
Locator for logit scaling.
:class:`AutoMinorLocator`
Locator for minor ticks when the axis is linear and the
major ticks are uniformly spaced. Subdivides the major
tick interval into a specified number of minor intervals,
defaulting to 4 or 5 depending on the major interval.
There are a number of locators specialized for date locations - see
the :mod:`.dates` module.
You can define your own locator by deriving from Locator. You must
override the ``__call__`` method, which returns a sequence of locations,
and you will probably want to override the autoscale method to set the
view limits from the data limits.
If you want to override the default locator, use one of the above or a custom
locator and pass it to the x or y axis instance. The relevant methods are::
ax.xaxis.set_major_locator(xmajor_locator)
ax.xaxis.set_minor_locator(xminor_locator)
ax.yaxis.set_major_locator(ymajor_locator)
ax.yaxis.set_minor_locator(yminor_locator)
The default minor locator is `NullLocator`, i.e., no minor ticks on by default.
.. note::
`Locator` instances should not be used with more than one
`~matplotlib.axis.Axis` or `~matplotlib.axes.Axes`. So instead of::
locator = MultipleLocator(5)
ax.xaxis.set_major_locator(locator)
ax2.xaxis.set_major_locator(locator)
do the following instead::
ax.xaxis.set_major_locator(MultipleLocator(5))
ax2.xaxis.set_major_locator(MultipleLocator(5))
Tick formatting
---------------
Tick formatting is controlled by classes derived from Formatter. The formatter
operates on a single tick value and returns a string to the axis.
:class:`NullFormatter`
No labels on the ticks.
:class:`FixedFormatter`
Set the strings manually for the labels.
:class:`FuncFormatter`
User defined function sets the labels.
:class:`StrMethodFormatter`
Use string `format` method.
:class:`FormatStrFormatter`
Use an old-style sprintf format string.
:class:`ScalarFormatter`
Default formatter for scalars: autopick the format string.
:class:`LogFormatter`
Formatter for log axes.
:class:`LogFormatterExponent`
Format values for log axis using ``exponent = log_base(value)``.
:class:`LogFormatterMathtext`
Format values for log axis using ``exponent = log_base(value)``
using Math text.
:class:`LogFormatterSciNotation`
Format values for log axis using scientific notation.
:class:`LogitFormatter`
Probability formatter.
:class:`EngFormatter`
Format labels in engineering notation.
:class:`PercentFormatter`
Format labels as a percentage.
You can derive your own formatter from the Formatter base class by
simply overriding the ``__call__`` method. The formatter class has
access to the axis view and data limits.
To control the major and minor tick label formats, use one of the
following methods::
ax.xaxis.set_major_formatter(xmajor_formatter)
ax.xaxis.set_minor_formatter(xminor_formatter)
ax.yaxis.set_major_formatter(ymajor_formatter)
ax.yaxis.set_minor_formatter(yminor_formatter)
In addition to a `.Formatter` instance, `~.Axis.set_major_formatter` and
`~.Axis.set_minor_formatter` also accept a ``str`` or function. ``str`` input
will be internally replaced with an autogenerated `.StrMethodFormatter` with
the input ``str``. For function input, a `.FuncFormatter` with the input
function will be generated and used.
See :doc:`/gallery/ticks_and_spines/major_minor_demo` for an
example of setting major and minor ticks. See the :mod:`matplotlib.dates`
module for more information and examples of using date locators and formatters.
"""
import itertools
import logging
import locale
import math
from numbers import Integral
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook
from matplotlib import transforms as mtransforms
_log = logging.getLogger(__name__)
__all__ = ('TickHelper', 'Formatter', 'FixedFormatter',
'NullFormatter', 'FuncFormatter', 'FormatStrFormatter',
'StrMethodFormatter', 'ScalarFormatter', 'LogFormatter',
'LogFormatterExponent', 'LogFormatterMathtext',
'LogFormatterSciNotation',
'LogitFormatter', 'EngFormatter', 'PercentFormatter',
'Locator', 'IndexLocator', 'FixedLocator', 'NullLocator',
'LinearLocator', 'LogLocator', 'AutoLocator',
'MultipleLocator', 'MaxNLocator', 'AutoMinorLocator',
'SymmetricalLogLocator', 'LogitLocator')
class _DummyAxis:
__name__ = "dummy"
def __init__(self, minpos=0):
self.dataLim = mtransforms.Bbox.unit()
self.viewLim = mtransforms.Bbox.unit()
self._minpos = minpos
def get_view_interval(self):
return self.viewLim.intervalx
def set_view_interval(self, vmin, vmax):
self.viewLim.intervalx = vmin, vmax
def get_minpos(self):
return self._minpos
def get_data_interval(self):
return self.dataLim.intervalx
def set_data_interval(self, vmin, vmax):
self.dataLim.intervalx = vmin, vmax
def get_tick_space(self):
# Just use the long-standing default of nbins==9
return 9
class TickHelper:
axis = None
def set_axis(self, axis):
self.axis = axis
def create_dummy_axis(self, **kwargs):
if self.axis is None:
self.axis = _DummyAxis(**kwargs)
@_api.deprecated("3.5", alternative=".axis.set_view_interval")
def set_view_interval(self, vmin, vmax):
self.axis.set_view_interval(vmin, vmax)
@_api.deprecated("3.5", alternative=".axis.set_data_interval")
def set_data_interval(self, vmin, vmax):
self.axis.set_data_interval(vmin, vmax)
@_api.deprecated(
"3.5",
alternative=".axis.set_view_interval and .axis.set_data_interval")
def set_bounds(self, vmin, vmax):
self.set_view_interval(vmin, vmax)
self.set_data_interval(vmin, vmax)
class Formatter(TickHelper):
"""
Create a string based on a tick value and location.
"""
# some classes want to see all the locs to help format
# individual ones
locs = []
def __call__(self, x, pos=None):
"""
Return the format for tick value *x* at position pos.
``pos=None`` indicates an unspecified location.
"""
raise NotImplementedError('Derived must override')
def format_ticks(self, values):
"""Return the tick labels for all the ticks at once."""
self.set_locs(values)
return [self(value, i) for i, value in enumerate(values)]
def format_data(self, value):
"""
Return the full string representation of the value with the
position unspecified.
"""
return self.__call__(value)
def format_data_short(self, value):
"""
Return a short string version of the tick value.
Defaults to the position-independent long value.
"""
return self.format_data(value)
def get_offset(self):
return ''
def set_locs(self, locs):
"""
Set the locations of the ticks.
This method is called before computing the tick labels because some
formatters need to know all tick locations to do so.
"""
self.locs = locs
@staticmethod
def fix_minus(s):
"""
Some classes may want to replace a hyphen for minus with the proper
unicode symbol (U+2212) for typographical correctness. This is a
helper method to perform such a replacement when it is enabled via
:rc:`axes.unicode_minus`.
"""
return (s.replace('-', '\N{MINUS SIGN}')
if mpl.rcParams['axes.unicode_minus']
else s)
def _set_locator(self, locator):
"""Subclasses may want to override this to set a locator."""
pass
class NullFormatter(Formatter):
"""Always return the empty string."""
def __call__(self, x, pos=None):
# docstring inherited
return ''
class FixedFormatter(Formatter):
"""
Return fixed strings for tick labels based only on position, not value.
.. note::
`.FixedFormatter` should only be used together with `.FixedLocator`.
Otherwise, the labels may end up in unexpected positions.
"""
def __init__(self, seq):
"""Set the sequence *seq* of strings that will be used for labels."""
self.seq = seq
self.offset_string = ''
def __call__(self, x, pos=None):
"""
Return the label that matches the position, regardless of the value.
For positions ``pos < len(seq)``, return ``seq[i]`` regardless of
*x*. Otherwise return empty string. ``seq`` is the sequence of
strings that this object was initialized with.
"""
if pos is None or pos >= len(self.seq):
return ''
else:
return self.seq[pos]
def get_offset(self):
return self.offset_string
def set_offset_string(self, ofs):
self.offset_string = ofs
class FuncFormatter(Formatter):
"""
Use a user-defined function for formatting.
The function should take in two inputs (a tick value ``x`` and a
position ``pos``), and return a string containing the corresponding
tick label.
"""
def __init__(self, func):
self.func = func
self.offset_string = ""
def __call__(self, x, pos=None):
"""
Return the value of the user defined function.
*x* and *pos* are passed through as-is.
"""
return self.func(x, pos)
def get_offset(self):
return self.offset_string
def set_offset_string(self, ofs):
self.offset_string = ofs
class FormatStrFormatter(Formatter):
"""
Use an old-style ('%' operator) format string to format the tick.
The format string should have a single variable format (%) in it.
It will be applied to the value (not the position) of the tick.
Negative numeric values will use a dash not a unicode minus,
use mathtext to get a unicode minus by wrappping the format specifier
with $ (e.g. "$%g$").
"""
def __init__(self, fmt):
self.fmt = fmt
def __call__(self, x, pos=None):
"""
Return the formatted label string.
Only the value *x* is formatted. The position is ignored.
"""
return self.fmt % x
class StrMethodFormatter(Formatter):
"""
Use a new-style format string (as used by `str.format`) to format the tick.
The field used for the tick value must be labeled *x* and the field used
for the tick position must be labeled *pos*.
"""
def __init__(self, fmt):
self.fmt = fmt
def __call__(self, x, pos=None):
"""
Return the formatted label string.
*x* and *pos* are passed to `str.format` as keyword arguments
with those exact names.
"""
return self.fmt.format(x=x, pos=pos)
class ScalarFormatter(Formatter):
"""
Format tick values as a number.
Parameters
----------
useOffset : bool or float, default: :rc:`axes.formatter.useoffset`
Whether to use offset notation. See `.set_useOffset`.
useMathText : bool, default: :rc:`axes.formatter.use_mathtext`
Whether to use fancy math formatting. See `.set_useMathText`.
useLocale : bool, default: :rc:`axes.formatter.use_locale`.
Whether to use locale settings for decimal sign and positive sign.
See `.set_useLocale`.
Notes
-----
In addition to the parameters above, the formatting of scientific vs.
floating point representation can be configured via `.set_scientific`
and `.set_powerlimits`).
**Offset notation and scientific notation**
Offset notation and scientific notation look quite similar at first sight.
Both split some information from the formatted tick values and display it
at the end of the axis.
- The scientific notation splits up the order of magnitude, i.e. a
multiplicative scaling factor, e.g. ``1e6``.
- The offset notation separates an additive constant, e.g. ``+1e6``. The
offset notation label is always prefixed with a ``+`` or ``-`` sign
and is thus distinguishable from the order of magnitude label.
The following plot with x limits ``1_000_000`` to ``1_000_010`` illustrates
the different formatting. Note the labels at the right edge of the x axis.
.. plot::
lim = (1_000_000, 1_000_010)
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, gridspec_kw={'hspace': 2})
ax1.set(title='offset_notation', xlim=lim)
ax2.set(title='scientific notation', xlim=lim)
ax2.xaxis.get_major_formatter().set_useOffset(False)
ax3.set(title='floating point notation', xlim=lim)
ax3.xaxis.get_major_formatter().set_useOffset(False)
ax3.xaxis.get_major_formatter().set_scientific(False)
"""
def __init__(self, useOffset=None, useMathText=None, useLocale=None):
if useOffset is None:
useOffset = mpl.rcParams['axes.formatter.useoffset']
self._offset_threshold = \
mpl.rcParams['axes.formatter.offset_threshold']
self.set_useOffset(useOffset)
self._usetex = mpl.rcParams['text.usetex']
if useMathText is None:
useMathText = mpl.rcParams['axes.formatter.use_mathtext']
if useMathText is False:
try:
ufont = mpl.font_manager.findfont(
mpl.font_manager.FontProperties(
mpl.rcParams["font.family"]
),
fallback_to_default=False,
)
except ValueError:
ufont = None
if ufont == str(cbook._get_data_path("fonts/ttf/cmr10.ttf")):
_api.warn_external(
"cmr10 font should ideally be used with "
"mathtext, set axes.formatter.use_mathtext to True"
)
self.set_useMathText(useMathText)
self.orderOfMagnitude = 0
self.format = ''
self._scientific = True
self._powerlimits = mpl.rcParams['axes.formatter.limits']
if useLocale is None:
useLocale = mpl.rcParams['axes.formatter.use_locale']
self._useLocale = useLocale
def get_useOffset(self):
"""
Return whether automatic mode for offset notation is active.
This returns True if ``set_useOffset(True)``; it returns False if an
explicit offset was set, e.g. ``set_useOffset(1000)``.
See Also
--------
ScalarFormatter.set_useOffset
"""
return self._useOffset
def set_useOffset(self, val):
"""
Set whether to use offset notation.
When formatting a set numbers whose value is large compared to their
range, the formatter can separate an additive constant. This can
shorten the formatted numbers so that they are less likely to overlap
when drawn on an axis.
Parameters
----------
val : bool or float
- If False, do not use offset notation.
- If True (=automatic mode), use offset notation if it can make
the residual numbers significantly shorter. The exact behavior
is controlled by :rc:`axes.formatter.offset_threshold`.
- If a number, force an offset of the given value.
Examples
--------
With active offset notation, the values
``100_000, 100_002, 100_004, 100_006, 100_008``
will be formatted as ``0, 2, 4, 6, 8`` plus an offset ``+1e5``, which
is written to the edge of the axis.
"""
if val in [True, False]:
self.offset = 0
self._useOffset = val
else:
self._useOffset = False
self.offset = val
useOffset = property(fget=get_useOffset, fset=set_useOffset)
def get_useLocale(self):
"""
Return whether locale settings are used for formatting.
See Also
--------
ScalarFormatter.set_useLocale
"""
return self._useLocale
def set_useLocale(self, val):
"""
Set whether to use locale settings for decimal sign and positive sign.
Parameters
----------
val : bool or None
*None* resets to :rc:`axes.formatter.use_locale`.
"""
if val is None:
self._useLocale = mpl.rcParams['axes.formatter.use_locale']
else:
self._useLocale = val
useLocale = property(fget=get_useLocale, fset=set_useLocale)
def _format_maybe_minus_and_locale(self, fmt, arg):
"""
Format *arg* with *fmt*, applying unicode minus and locale if desired.
"""
return self.fix_minus(locale.format_string(fmt, (arg,), True)
if self._useLocale else fmt % arg)
def get_useMathText(self):
"""
Return whether to use fancy math formatting.
See Also
--------
ScalarFormatter.set_useMathText
"""
return self._useMathText
def set_useMathText(self, val):
r"""
Set whether to use fancy math formatting.
If active, scientific notation is formatted as :math:`1.2 \times 10^3`.
Parameters
----------
val : bool or None
*None* resets to :rc:`axes.formatter.use_mathtext`.
"""
if val is None:
self._useMathText = mpl.rcParams['axes.formatter.use_mathtext']
else:
self._useMathText = val
useMathText = property(fget=get_useMathText, fset=set_useMathText)
def __call__(self, x, pos=None):
"""
Return the format for tick value *x* at position *pos*.
"""
if len(self.locs) == 0:
return ''
else:
xp = (x - self.offset) / (10. ** self.orderOfMagnitude)
if abs(xp) < 1e-8:
xp = 0
return self._format_maybe_minus_and_locale(self.format, xp)
def set_scientific(self, b):
"""
Turn scientific notation on or off.
See Also
--------
ScalarFormatter.set_powerlimits
"""
self._scientific = bool(b)
def set_powerlimits(self, lims):
r"""
Set size thresholds for scientific notation.
Parameters
----------
lims : (int, int)
A tuple *(min_exp, max_exp)* containing the powers of 10 that
determine the switchover threshold. For a number representable as
:math:`a \times 10^\mathrm{exp}`` with :math:`1 <= |a| < 10`,
scientific notation will be used if ``exp <= min_exp`` or
``exp >= max_exp``.
The default limits are controlled by :rc:`axes.formatter.limits`.
In particular numbers with *exp* equal to the thresholds are
written in scientific notation.
Typically, *min_exp* will be negative and *max_exp* will be
positive.
For example, ``formatter.set_powerlimits((-3, 4))`` will provide
the following formatting:
:math:`1 \times 10^{-3}, 9.9 \times 10^{-3}, 0.01,`
:math:`9999, 1 \times 10^4`.
See Also
--------
ScalarFormatter.set_scientific
"""
if len(lims) != 2:
raise ValueError("'lims' must be a sequence of length 2")
self._powerlimits = lims
def format_data_short(self, value):
# docstring inherited
if isinstance(value, np.ma.MaskedArray) and value.mask:
return ""
if isinstance(value, Integral):
fmt = "%d"
else:
if getattr(self.axis, "__name__", "") in ["xaxis", "yaxis"]:
if self.axis.__name__ == "xaxis":
axis_trf = self.axis.axes.get_xaxis_transform()
axis_inv_trf = axis_trf.inverted()
screen_xy = axis_trf.transform((value, 0))
neighbor_values = axis_inv_trf.transform(
screen_xy + [[-1, 0], [+1, 0]])[:, 0]
else: # yaxis:
axis_trf = self.axis.axes.get_yaxis_transform()
axis_inv_trf = axis_trf.inverted()
screen_xy = axis_trf.transform((0, value))
neighbor_values = axis_inv_trf.transform(
screen_xy + [[0, -1], [0, +1]])[:, 1]
delta = abs(neighbor_values - value).max()
else:
# Rough approximation: no more than 1e4 divisions.
a, b = self.axis.get_view_interval()
delta = (b - a) / 1e4
# If e.g. value = 45.67 and delta = 0.02, then we want to round to
# 2 digits after the decimal point (floor(log10(0.02)) = -2);
# 45.67 contributes 2 digits before the decimal point
# (floor(log10(45.67)) + 1 = 2): the total is 4 significant digits.
# A value of 0 contributes 1 "digit" before the decimal point.
sig_digits = max(
0,
(math.floor(math.log10(abs(value))) + 1 if value else 1)
- math.floor(math.log10(delta)))
fmt = f"%-#.{sig_digits}g"
return self._format_maybe_minus_and_locale(fmt, value)
def format_data(self, value):
# docstring inherited
e = math.floor(math.log10(abs(value)))
s = round(value / 10**e, 10)
exponent = self._format_maybe_minus_and_locale("%d", e)
significand = self._format_maybe_minus_and_locale(
"%d" if s % 1 == 0 else "%1.10f", s)
if e == 0:
return significand
elif self._useMathText or self._usetex:
exponent = "10^{%s}" % exponent
return (exponent if s == 1 # reformat 1x10^y as 10^y
else rf"{significand} \times {exponent}")
else:
return f"{significand}e{exponent}"
def get_offset(self):
"""
Return scientific notation, plus offset.
"""
if len(self.locs) == 0:
return ''
s = ''
if self.orderOfMagnitude or self.offset:
offsetStr = ''
sciNotStr = ''
if self.offset:
offsetStr = self.format_data(self.offset)
if self.offset > 0:
offsetStr = '+' + offsetStr
if self.orderOfMagnitude:
if self._usetex or self._useMathText:
sciNotStr = self.format_data(10 ** self.orderOfMagnitude)
else:
sciNotStr = '1e%d' % self.orderOfMagnitude
if self._useMathText or self._usetex:
if sciNotStr != '':
sciNotStr = r'\times\mathdefault{%s}' % sciNotStr
s = r'$%s\mathdefault{%s}$' % (sciNotStr, offsetStr)
else:
s = ''.join((sciNotStr, offsetStr))
return self.fix_minus(s)
def set_locs(self, locs):
# docstring inherited
self.locs = locs
if len(self.locs) > 0:
if self._useOffset:
self._compute_offset()
self._set_order_of_magnitude()
self._set_format()
def _compute_offset(self):
locs = self.locs
# Restrict to visible ticks.
vmin, vmax = sorted(self.axis.get_view_interval())
locs = np.asarray(locs)
locs = locs[(vmin <= locs) & (locs <= vmax)]
if not len(locs):
self.offset = 0
return
lmin, lmax = locs.min(), locs.max()
# Only use offset if there are at least two ticks and every tick has
# the same sign.
if lmin == lmax or lmin <= 0 <= lmax:
self.offset = 0
return
# min, max comparing absolute values (we want division to round towards
# zero so we work on absolute values).
abs_min, abs_max = sorted([abs(float(lmin)), abs(float(lmax))])
sign = math.copysign(1, lmin)
# What is the smallest power of ten such that abs_min and abs_max are
# equal up to that precision?
# Note: Internally using oom instead of 10 ** oom avoids some numerical
# accuracy issues.
oom_max = np.ceil(math.log10(abs_max))
oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
if abs_min // 10 ** oom != abs_max // 10 ** oom)
if (abs_max - abs_min) / 10 ** oom <= 1e-2:
# Handle the case of straddling a multiple of a large power of ten
# (relative to the span).
# What is the smallest power of ten such that abs_min and abs_max
# are no more than 1 apart at that precision?
oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
if abs_max // 10 ** oom - abs_min // 10 ** oom > 1)
# Only use offset if it saves at least _offset_threshold digits.
n = self._offset_threshold - 1
self.offset = (sign * (abs_max // 10 ** oom) * 10 ** oom
if abs_max // 10 ** oom >= 10**n
else 0)
def _set_order_of_magnitude(self):
# if scientific notation is to be used, find the appropriate exponent
# if using an numerical offset, find the exponent after applying the
# offset. When lower power limit = upper <> 0, use provided exponent.
if not self._scientific:
self.orderOfMagnitude = 0
return
if self._powerlimits[0] == self._powerlimits[1] != 0:
# fixed scaling when lower power limit = upper <> 0.
self.orderOfMagnitude = self._powerlimits[0]
return
# restrict to visible ticks
vmin, vmax = sorted(self.axis.get_view_interval())
locs = np.asarray(self.locs)
locs = locs[(vmin <= locs) & (locs <= vmax)]
locs = np.abs(locs)
if not len(locs):
self.orderOfMagnitude = 0
return
if self.offset:
oom = math.floor(math.log10(vmax - vmin))
else:
if locs[0] > locs[-1]:
val = locs[0]
else:
val = locs[-1]
if val == 0:
oom = 0
else:
oom = math.floor(math.log10(val))
if oom <= self._powerlimits[0]:
self.orderOfMagnitude = oom
elif oom >= self._powerlimits[1]:
self.orderOfMagnitude = oom
else:
self.orderOfMagnitude = 0
def _set_format(self):
# set the format string to format all the ticklabels
if len(self.locs) < 2:
# Temporarily augment the locations with the axis end points.
_locs = [*self.locs, *self.axis.get_view_interval()]
else:
_locs = self.locs
locs = (np.asarray(_locs) - self.offset) / 10. ** self.orderOfMagnitude
loc_range = np.ptp(locs)
# Curvilinear coordinates can yield two identical points.
if loc_range == 0:
loc_range = np.max(np.abs(locs))
# Both points might be zero.
if loc_range == 0:
loc_range = 1
if len(self.locs) < 2:
# We needed the end points only for the loc_range calculation.
locs = locs[:-2]
loc_range_oom = int(math.floor(math.log10(loc_range)))
# first estimate:
sigfigs = max(0, 3 - loc_range_oom)
# refined estimate:
thresh = 1e-3 * 10 ** loc_range_oom
while sigfigs >= 0:
if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh:
sigfigs -= 1
else:
break
sigfigs += 1
self.format = '%1.' + str(sigfigs) + 'f'
if self._usetex or self._useMathText:
self.format = r'$\mathdefault{%s}$' % self.format
class LogFormatter(Formatter):
"""
Base class for formatting ticks on a log or symlog scale.
It may be instantiated directly, or subclassed.
Parameters
----------
base : float, default: 10.
Base of the logarithm used in all calculations.
labelOnlyBase : bool, default: False
If True, label ticks only at integer powers of base.
This is normally True for major ticks and False for
minor ticks.
minor_thresholds : (subset, all), default: (1, 0.4)
If labelOnlyBase is False, these two numbers control
the labeling of ticks that are not at integer powers of
base; normally these are the minor ticks. The controlling
parameter is the log of the axis data range. In the typical
case where base is 10 it is the number of decades spanned
by the axis, so we can call it 'numdec'. If ``numdec <= all``,
all minor ticks will be labeled. If ``all < numdec <= subset``,
then only a subset of minor ticks will be labeled, so as to
avoid crowding. If ``numdec > subset`` then no minor ticks will
be labeled.
linthresh : None or float, default: None
If a symmetric log scale is in use, its ``linthresh``
parameter must be supplied here.
Notes
-----
The `set_locs` method must be called to enable the subsetting
logic controlled by the ``minor_thresholds`` parameter.
In some cases such as the colorbar, there is no distinction between
major and minor ticks; the tick locations might be set manually,
or by a locator that puts ticks at integer powers of base and
at intermediate locations. For this situation, disable the
minor_thresholds logic by using ``minor_thresholds=(np.inf, np.inf)``,
so that all ticks will be labeled.
To disable labeling of minor ticks when 'labelOnlyBase' is False,
use ``minor_thresholds=(0, 0)``. This is the default for the
"classic" style.
Examples
--------
To label a subset of minor ticks when the view limits span up
to 2 decades, and all of the ticks when zoomed in to 0.5 decades
or less, use ``minor_thresholds=(2, 0.5)``.
To label all minor ticks when the view limits span up to 1.5
decades, use ``minor_thresholds=(1.5, 1.5)``.
"""
def __init__(self, base=10.0, labelOnlyBase=False,
minor_thresholds=None,
linthresh=None):
self._base = float(base)
self.labelOnlyBase = labelOnlyBase
if minor_thresholds is None:
if mpl.rcParams['_internal.classic_mode']:
minor_thresholds = (0, 0)
else:
minor_thresholds = (1, 0.4)
self.minor_thresholds = minor_thresholds
self._sublabels = None
self._linthresh = linthresh
def base(self, base):
"""
Change the *base* for labeling.
.. warning::
Should always match the base used for :class:`LogLocator`
"""
self._base = base
def label_minor(self, labelOnlyBase):
"""
Switch minor tick labeling on or off.
Parameters
----------
labelOnlyBase : bool
If True, label ticks only at integer powers of base.
"""
self.labelOnlyBase = labelOnlyBase
def set_locs(self, locs=None):
"""
Use axis view limits to control which ticks are labeled.
The *locs* parameter is ignored in the present algorithm.
"""
if np.isinf(self.minor_thresholds[0]):
self._sublabels = None
return
# Handle symlog case:
linthresh = self._linthresh
if linthresh is None:
try:
linthresh = self.axis.get_transform().linthresh
except AttributeError:
pass
vmin, vmax = self.axis.get_view_interval()
if vmin > vmax:
vmin, vmax = vmax, vmin
if linthresh is None and vmin <= 0:
# It's probably a colorbar with
# a format kwarg setting a LogFormatter in the manner
# that worked with 1.5.x, but that doesn't work now.
self._sublabels = {1} # label powers of base
return
b = self._base
if linthresh is not None: # symlog
# Only compute the number of decades in the logarithmic part of the
# axis
numdec = 0
if vmin < -linthresh:
rhs = min(vmax, -linthresh)
numdec += math.log(vmin / rhs) / math.log(b)
if vmax > linthresh:
lhs = max(vmin, linthresh)