/
axis.py
2532 lines (2163 loc) · 89.3 KB
/
axis.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
"""
Classes for the ticks and x and y axis.
"""
import datetime
import functools
import logging
import numpy as np
import matplotlib as mpl
from matplotlib import _api
import matplotlib.artist as martist
import matplotlib.cbook as cbook
import matplotlib.lines as mlines
import matplotlib.scale as mscale
import matplotlib.text as mtext
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
import matplotlib.units as munits
_log = logging.getLogger(__name__)
GRIDLINE_INTERPOLATION_STEPS = 180
# This list is being used for compatibility with Axes.grid, which
# allows all Line2D kwargs.
_line_inspector = martist.ArtistInspector(mlines.Line2D)
_line_param_names = _line_inspector.get_setters()
_line_param_aliases = [list(d)[0] for d in _line_inspector.aliasd.values()]
_gridline_param_names = ['grid_' + name
for name in _line_param_names + _line_param_aliases]
class Tick(martist.Artist):
"""
Abstract base class for the axis ticks, grid lines and labels.
Ticks mark a position on an Axis. They contain two lines as markers and
two labels; one each for the bottom and top positions (in case of an
`.XAxis`) or for the left and right positions (in case of a `.YAxis`).
Attributes
----------
tick1line : `.Line2D`
The left/bottom tick marker.
tick2line : `.Line2D`
The right/top tick marker.
gridline : `.Line2D`
The grid line associated with the label position.
label1 : `.Text`
The left/bottom tick label.
label2 : `.Text`
The right/top tick label.
"""
def __init__(self, axes, loc, *,
size=None, # points
width=None,
color=None,
tickdir=None,
pad=None,
labelsize=None,
labelcolor=None,
zorder=None,
gridOn=None, # defaults to axes.grid depending on
# axes.grid.which
tick1On=True,
tick2On=True,
label1On=True,
label2On=False,
major=True,
labelrotation=0,
grid_color=None,
grid_linestyle=None,
grid_linewidth=None,
grid_alpha=None,
**kw # Other Line2D kwargs applied to gridlines.
):
"""
bbox is the Bound2D bounding box in display coords of the Axes
loc is the tick location in data coords
size is the tick size in points
"""
super().__init__()
if gridOn is None:
if major and (mpl.rcParams['axes.grid.which']
in ('both', 'major')):
gridOn = mpl.rcParams['axes.grid']
elif (not major) and (mpl.rcParams['axes.grid.which']
in ('both', 'minor')):
gridOn = mpl.rcParams['axes.grid']
else:
gridOn = False
self.set_figure(axes.figure)
self.axes = axes
self._loc = loc
self._major = major
name = self.__name__
major_minor = "major" if major else "minor"
if size is None:
size = mpl.rcParams[f"{name}.{major_minor}.size"]
self._size = size
if width is None:
width = mpl.rcParams[f"{name}.{major_minor}.width"]
self._width = width
if color is None:
color = mpl.rcParams[f"{name}.color"]
if pad is None:
pad = mpl.rcParams[f"{name}.{major_minor}.pad"]
self._base_pad = pad
if labelcolor is None:
labelcolor = mpl.rcParams[f"{name}.labelcolor"]
if labelcolor == 'inherit':
# inherit from tick color
labelcolor = mpl.rcParams[f"{name}.color"]
if labelsize is None:
labelsize = mpl.rcParams[f"{name}.labelsize"]
self._set_labelrotation(labelrotation)
if zorder is None:
if major:
zorder = mlines.Line2D.zorder + 0.01
else:
zorder = mlines.Line2D.zorder
self._zorder = zorder
if grid_color is None:
grid_color = mpl.rcParams["grid.color"]
if grid_linestyle is None:
grid_linestyle = mpl.rcParams["grid.linestyle"]
if grid_linewidth is None:
grid_linewidth = mpl.rcParams["grid.linewidth"]
if grid_alpha is None:
grid_alpha = mpl.rcParams["grid.alpha"]
grid_kw = {k[5:]: v for k, v in kw.items()}
self.tick1line = mlines.Line2D(
[], [],
color=color, linestyle="none", zorder=zorder, visible=tick1On,
markeredgecolor=color, markersize=size, markeredgewidth=width,
)
self.tick2line = mlines.Line2D(
[], [],
color=color, linestyle="none", zorder=zorder, visible=tick2On,
markeredgecolor=color, markersize=size, markeredgewidth=width,
)
self.gridline = mlines.Line2D(
[], [],
color=grid_color, alpha=grid_alpha, visible=gridOn,
linestyle=grid_linestyle, linewidth=grid_linewidth, marker="",
**grid_kw,
)
self.gridline.get_path()._interpolation_steps = \
GRIDLINE_INTERPOLATION_STEPS
self.label1 = mtext.Text(
np.nan, np.nan,
fontsize=labelsize, color=labelcolor, visible=label1On,
rotation=self._labelrotation[1])
self.label2 = mtext.Text(
np.nan, np.nan,
fontsize=labelsize, color=labelcolor, visible=label2On,
rotation=self._labelrotation[1])
self._apply_tickdir(tickdir)
for artist in [self.tick1line, self.tick2line, self.gridline,
self.label1, self.label2]:
self._set_artist_props(artist)
self.update_position(loc)
@property
@_api.deprecated("3.1", alternative="Tick.label1", pending=True)
def label(self):
return self.label1
def _set_labelrotation(self, labelrotation):
if isinstance(labelrotation, str):
mode = labelrotation
angle = 0
elif isinstance(labelrotation, (tuple, list)):
mode, angle = labelrotation
else:
mode = 'default'
angle = labelrotation
_api.check_in_list(['auto', 'default'], labelrotation=mode)
self._labelrotation = (mode, angle)
def _apply_tickdir(self, tickdir):
"""Set tick direction. Valid values are 'out', 'in', 'inout'."""
# This method is responsible for updating `_pad`, and, in subclasses,
# for setting the tick{1,2}line markers as well. From the user
# perspective this should always be called though _apply_params, which
# further updates ticklabel positions using the new pads.
if tickdir is None:
tickdir = mpl.rcParams[f'{self.__name__}.direction']
_api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
self._tickdir = tickdir
self._pad = self._base_pad + self.get_tick_padding()
@_api.deprecated("3.5", alternative="`.Axis.set_tick_params`")
def apply_tickdir(self, tickdir):
self._apply_tickdir(tickdir)
self.stale = True
def get_tickdir(self):
return self._tickdir
def get_tick_padding(self):
"""Get the length of the tick outside of the axes."""
padding = {
'in': 0.0,
'inout': 0.5,
'out': 1.0
}
return self._size * padding[self._tickdir]
def get_children(self):
children = [self.tick1line, self.tick2line,
self.gridline, self.label1, self.label2]
return children
def set_clip_path(self, clippath, transform=None):
# docstring inherited
super().set_clip_path(clippath, transform)
self.gridline.set_clip_path(clippath, transform)
self.stale = True
def get_pad_pixels(self):
return self.figure.dpi * self._base_pad / 72
def contains(self, mouseevent):
"""
Test whether the mouse event occurred in the Tick marks.
This function always returns false. It is more useful to test if the
axis as a whole contains the mouse rather than the set of tick marks.
"""
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
return False, {}
def set_pad(self, val):
"""
Set the tick label pad in points
Parameters
----------
val : float
"""
self._apply_params(pad=val)
self.stale = True
def get_pad(self):
"""Get the value of the tick label pad in points."""
return self._base_pad
def _get_text1(self):
"""Get the default Text 1 instance."""
def _get_text2(self):
"""Get the default Text 2 instance."""
def _get_tick1line(self):
"""Get the default line2D instance for tick1."""
def _get_tick2line(self):
"""Get the default line2D instance for tick2."""
def _get_gridline(self):
"""Get the default grid Line2d instance for this tick."""
def get_loc(self):
"""Return the tick location (data coords) as a scalar."""
return self._loc
@martist.allow_rasterization
def draw(self, renderer):
if not self.get_visible():
self.stale = False
return
renderer.open_group(self.__name__, gid=self.get_gid())
for artist in [self.gridline, self.tick1line, self.tick2line,
self.label1, self.label2]:
artist.draw(renderer)
renderer.close_group(self.__name__)
self.stale = False
def set_label1(self, s):
"""
Set the label1 text.
Parameters
----------
s : str
"""
self.label1.set_text(s)
self.stale = True
set_label = set_label1
def set_label2(self, s):
"""
Set the label2 text.
Parameters
----------
s : str
"""
self.label2.set_text(s)
self.stale = True
def set_url(self, url):
"""
Set the url of label1 and label2.
Parameters
----------
url : str
"""
super().set_url(url)
self.label1.set_url(url)
self.label2.set_url(url)
self.stale = True
def _set_artist_props(self, a):
a.set_figure(self.figure)
def get_view_interval(self):
"""
Return the view limits ``(min, max)`` of the axis the tick belongs to.
"""
raise NotImplementedError('Derived must override')
def _apply_params(self, **kw):
for name, target in [("gridOn", self.gridline),
("tick1On", self.tick1line),
("tick2On", self.tick2line),
("label1On", self.label1),
("label2On", self.label2)]:
if name in kw:
target.set_visible(kw.pop(name))
if any(k in kw for k in ['size', 'width', 'pad', 'tickdir']):
self._size = kw.pop('size', self._size)
# Width could be handled outside this block, but it is
# convenient to leave it here.
self._width = kw.pop('width', self._width)
self._base_pad = kw.pop('pad', self._base_pad)
# _apply_tickdir uses _size and _base_pad to make _pad, and also
# sets the ticklines markers.
self._apply_tickdir(kw.pop('tickdir', self._tickdir))
for line in (self.tick1line, self.tick2line):
line.set_markersize(self._size)
line.set_markeredgewidth(self._width)
# _get_text1_transform uses _pad from _apply_tickdir.
trans = self._get_text1_transform()[0]
self.label1.set_transform(trans)
trans = self._get_text2_transform()[0]
self.label2.set_transform(trans)
tick_kw = {k: v for k, v in kw.items() if k in ['color', 'zorder']}
if 'color' in kw:
tick_kw['markeredgecolor'] = kw['color']
self.tick1line.set(**tick_kw)
self.tick2line.set(**tick_kw)
for k, v in tick_kw.items():
setattr(self, '_' + k, v)
if 'labelrotation' in kw:
self._set_labelrotation(kw.pop('labelrotation'))
self.label1.set(rotation=self._labelrotation[1])
self.label2.set(rotation=self._labelrotation[1])
label_kw = {k[5:]: v for k, v in kw.items()
if k in ['labelsize', 'labelcolor']}
self.label1.set(**label_kw)
self.label2.set(**label_kw)
grid_kw = {k[5:]: v for k, v in kw.items()
if k in _gridline_param_names}
self.gridline.set(**grid_kw)
def update_position(self, loc):
"""Set the location of tick in data coords with scalar *loc*."""
raise NotImplementedError('Derived must override')
def _get_text1_transform(self):
raise NotImplementedError('Derived must override')
def _get_text2_transform(self):
raise NotImplementedError('Derived must override')
class XTick(Tick):
"""
Contains all the Artists needed to make an x tick - the tick line,
the label text and the grid line
"""
__name__ = 'xtick'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# x in data coords, y in axes coords
ax = self.axes
self.tick1line.set(
data=([0], [0]), transform=ax.get_xaxis_transform("tick1"))
self.tick2line.set(
data=([0], [1]), transform=ax.get_xaxis_transform("tick2"))
self.gridline.set(
data=([0, 0], [0, 1]), transform=ax.get_xaxis_transform("grid"))
# the y loc is 3 points below the min of y axis
trans, va, ha = self._get_text1_transform()
self.label1.set(
x=0, y=0,
verticalalignment=va, horizontalalignment=ha, transform=trans,
)
trans, va, ha = self._get_text2_transform()
self.label2.set(
x=0, y=1,
verticalalignment=va, horizontalalignment=ha, transform=trans,
)
def _get_text1_transform(self):
return self.axes.get_xaxis_text1_transform(self._pad)
def _get_text2_transform(self):
return self.axes.get_xaxis_text2_transform(self._pad)
def _apply_tickdir(self, tickdir):
# docstring inherited
super()._apply_tickdir(tickdir)
mark1, mark2 = {
'out': (mlines.TICKDOWN, mlines.TICKUP),
'in': (mlines.TICKUP, mlines.TICKDOWN),
'inout': ('|', '|'),
}[self._tickdir]
self.tick1line.set_marker(mark1)
self.tick2line.set_marker(mark2)
def update_position(self, loc):
"""Set the location of tick in data coords with scalar *loc*."""
self.tick1line.set_xdata((loc,))
self.tick2line.set_xdata((loc,))
self.gridline.set_xdata((loc,))
self.label1.set_x(loc)
self.label2.set_x(loc)
self._loc = loc
self.stale = True
def get_view_interval(self):
# docstring inherited
return self.axes.viewLim.intervalx
class YTick(Tick):
"""
Contains all the Artists needed to make a Y tick - the tick line,
the label text and the grid line
"""
__name__ = 'ytick'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# x in axes coords, y in data coords
ax = self.axes
self.tick1line.set(
data=([0], [0]), transform=ax.get_yaxis_transform("tick1"))
self.tick2line.set(
data=([1], [0]), transform=ax.get_yaxis_transform("tick2"))
self.gridline.set(
data=([0, 1], [0, 0]), transform=ax.get_yaxis_transform("grid"))
# the y loc is 3 points below the min of y axis
trans, va, ha = self._get_text1_transform()
self.label1.set(
x=0, y=0,
verticalalignment=va, horizontalalignment=ha, transform=trans,
)
trans, va, ha = self._get_text2_transform()
self.label2.set(
x=1, y=0,
verticalalignment=va, horizontalalignment=ha, transform=trans,
)
def _get_text1_transform(self):
return self.axes.get_yaxis_text1_transform(self._pad)
def _get_text2_transform(self):
return self.axes.get_yaxis_text2_transform(self._pad)
def _apply_tickdir(self, tickdir):
# docstring inherited
super()._apply_tickdir(tickdir)
mark1, mark2 = {
'out': (mlines.TICKLEFT, mlines.TICKRIGHT),
'in': (mlines.TICKRIGHT, mlines.TICKLEFT),
'inout': ('_', '_'),
}[self._tickdir]
self.tick1line.set_marker(mark1)
self.tick2line.set_marker(mark2)
def update_position(self, loc):
"""Set the location of tick in data coords with scalar *loc*."""
self.tick1line.set_ydata((loc,))
self.tick2line.set_ydata((loc,))
self.gridline.set_ydata((loc,))
self.label1.set_y(loc)
self.label2.set_y(loc)
self._loc = loc
self.stale = True
def get_view_interval(self):
# docstring inherited
return self.axes.viewLim.intervaly
class Ticker:
"""
A container for the objects defining tick position and format.
Attributes
----------
locator : `matplotlib.ticker.Locator` subclass
Determines the positions of the ticks.
formatter : `matplotlib.ticker.Formatter` subclass
Determines the format of the tick labels.
"""
def __init__(self):
self._locator = None
self._formatter = None
self._locator_is_default = True
self._formatter_is_default = True
@property
def locator(self):
return self._locator
@locator.setter
def locator(self, locator):
if not isinstance(locator, mticker.Locator):
raise TypeError('locator must be a subclass of '
'matplotlib.ticker.Locator')
self._locator = locator
@property
def formatter(self):
return self._formatter
@formatter.setter
def formatter(self, formatter):
if not isinstance(formatter, mticker.Formatter):
raise TypeError('formatter must be a subclass of '
'matplotlib.ticker.Formatter')
self._formatter = formatter
class _LazyTickList:
"""
A descriptor for lazy instantiation of tick lists.
See comment above definition of the ``majorTicks`` and ``minorTicks``
attributes.
"""
def __init__(self, major):
self._major = major
def __get__(self, instance, cls):
if instance is None:
return self
else:
# instance._get_tick() can itself try to access the majorTicks
# attribute (e.g. in certain projection classes which override
# e.g. get_xaxis_text1_transform). In order to avoid infinite
# recursion, first set the majorTicks on the instance to an empty
# list, then create the tick and append it.
if self._major:
instance.majorTicks = []
tick = instance._get_tick(major=True)
instance.majorTicks.append(tick)
return instance.majorTicks
else:
instance.minorTicks = []
tick = instance._get_tick(major=False)
instance.minorTicks.append(tick)
return instance.minorTicks
class Axis(martist.Artist):
"""
Base class for `.XAxis` and `.YAxis`.
Attributes
----------
isDefault_label : bool
axes : `matplotlib.axes.Axes`
The `~.axes.Axes` to which the Axis belongs.
major : `matplotlib.axis.Ticker`
Determines the major tick positions and their label format.
minor : `matplotlib.axis.Ticker`
Determines the minor tick positions and their label format.
callbacks : `matplotlib.cbook.CallbackRegistry`
label : `.Text`
The axis label.
labelpad : float
The distance between the axis label and the tick labels.
Defaults to :rc:`axes.labelpad` = 4.
offsetText : `.Text`
A `.Text` object containing the data offset of the ticks (if any).
pickradius : float
The acceptance radius for containment tests. See also `.Axis.contains`.
majorTicks : list of `.Tick`
The major ticks.
minorTicks : list of `.Tick`
The minor ticks.
"""
OFFSETTEXTPAD = 3
def __str__(self):
return "{}({},{})".format(
type(self).__name__, *self.axes.transAxes.transform((0, 0)))
def __init__(self, axes, pickradius=15):
"""
Parameters
----------
axes : `matplotlib.axes.Axes`
The `~.axes.Axes` to which the created Axis belongs.
pickradius : float
The acceptance radius for containment tests. See also
`.Axis.contains`.
"""
super().__init__()
self._remove_overlapping_locs = True
self.set_figure(axes.figure)
self.isDefault_label = True
self.axes = axes
self.major = Ticker()
self.minor = Ticker()
self.callbacks = cbook.CallbackRegistry()
self._autolabelpos = True
self.label = mtext.Text(
np.nan, np.nan,
fontsize=mpl.rcParams['axes.labelsize'],
fontweight=mpl.rcParams['axes.labelweight'],
color=mpl.rcParams['axes.labelcolor'],
)
self._set_artist_props(self.label)
self.offsetText = mtext.Text(np.nan, np.nan)
self._set_artist_props(self.offsetText)
self.labelpad = mpl.rcParams['axes.labelpad']
self.pickradius = pickradius
# Initialize here for testing; later add API
self._major_tick_kw = dict()
self._minor_tick_kw = dict()
self.clear()
self._set_scale('linear')
@property
def isDefault_majloc(self):
return self.major._locator_is_default
@isDefault_majloc.setter
def isDefault_majloc(self, value):
self.major._locator_is_default = value
@property
def isDefault_majfmt(self):
return self.major._formatter_is_default
@isDefault_majfmt.setter
def isDefault_majfmt(self, value):
self.major._formatter_is_default = value
@property
def isDefault_minloc(self):
return self.minor._locator_is_default
@isDefault_minloc.setter
def isDefault_minloc(self, value):
self.minor._locator_is_default = value
@property
def isDefault_minfmt(self):
return self.minor._formatter_is_default
@isDefault_minfmt.setter
def isDefault_minfmt(self, value):
self.minor._formatter_is_default = value
# During initialization, Axis objects often create ticks that are later
# unused; this turns out to be a very slow step. Instead, use a custom
# descriptor to make the tick lists lazy and instantiate them as needed.
majorTicks = _LazyTickList(major=True)
minorTicks = _LazyTickList(major=False)
def get_remove_overlapping_locs(self):
return self._remove_overlapping_locs
def set_remove_overlapping_locs(self, val):
self._remove_overlapping_locs = bool(val)
remove_overlapping_locs = property(
get_remove_overlapping_locs, set_remove_overlapping_locs,
doc=('If minor ticker locations that overlap with major '
'ticker locations should be trimmed.'))
def set_label_coords(self, x, y, transform=None):
"""
Set the coordinates of the label.
By default, the x coordinate of the y label and the y coordinate of the
x label are determined by the tick label bounding boxes, but this can
lead to poor alignment of multiple labels if there are multiple axes.
You can also specify the coordinate system of the label with the
transform. If None, the default coordinate system will be the axes
coordinate system: (0, 0) is bottom left, (0.5, 0.5) is center, etc.
"""
self._autolabelpos = False
if transform is None:
transform = self.axes.transAxes
self.label.set_transform(transform)
self.label.set_position((x, y))
self.stale = True
def get_transform(self):
return self._scale.get_transform()
def get_scale(self):
"""Return this Axis' scale (as a str)."""
return self._scale.name
def _set_scale(self, value, **kwargs):
if not isinstance(value, mscale.ScaleBase):
self._scale = mscale.scale_factory(value, self, **kwargs)
else:
self._scale = value
self._scale.set_default_locators_and_formatters(self)
self.isDefault_majloc = True
self.isDefault_minloc = True
self.isDefault_majfmt = True
self.isDefault_minfmt = True
def limit_range_for_scale(self, vmin, vmax):
return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos())
def get_children(self):
return [self.label, self.offsetText,
*self.get_major_ticks(), *self.get_minor_ticks()]
def _reset_major_tick_kw(self):
self._major_tick_kw.clear()
self._major_tick_kw['gridOn'] = (
mpl.rcParams['axes.grid'] and
mpl.rcParams['axes.grid.which'] in ('both', 'major'))
def _reset_minor_tick_kw(self):
self._minor_tick_kw.clear()
self._minor_tick_kw['gridOn'] = (
mpl.rcParams['axes.grid'] and
mpl.rcParams['axes.grid.which'] in ('both', 'minor'))
def clear(self):
"""
Clear the axis.
This resets axis properties to their default values:
- the label
- the scale
- locators, formatters and ticks
- major and minor grid
- units
- registered callbacks
"""
self.label.set_text('') # self.set_label_text would change isDefault_
self._set_scale('linear')
# Clear the callback registry for this axis, or it may "leak"
self.callbacks = cbook.CallbackRegistry()
# whether the grids are on
self._major_tick_kw['gridOn'] = (
mpl.rcParams['axes.grid'] and
mpl.rcParams['axes.grid.which'] in ('both', 'major'))
self._minor_tick_kw['gridOn'] = (
mpl.rcParams['axes.grid'] and
mpl.rcParams['axes.grid.which'] in ('both', 'minor'))
self.reset_ticks()
self.converter = None
self.units = None
self.set_units(None)
self.stale = True
@_api.deprecated("3.4", alternative="`.Axis.clear`")
def cla(self):
"""Clear this axis."""
return self.clear()
def reset_ticks(self):
"""
Re-initialize the major and minor Tick lists.
Each list starts with a single fresh Tick.
"""
# Restore the lazy tick lists.
try:
del self.majorTicks
except AttributeError:
pass
try:
del self.minorTicks
except AttributeError:
pass
try:
self.set_clip_path(self.axes.patch)
except AttributeError:
pass
def set_tick_params(self, which='major', reset=False, **kw):
"""
Set appearance parameters for ticks, ticklabels, and gridlines.
For documentation of keyword arguments, see
:meth:`matplotlib.axes.Axes.tick_params`.
"""
_api.check_in_list(['major', 'minor', 'both'], which=which)
kwtrans = self._translate_tick_kw(kw)
# the kwargs are stored in self._major/minor_tick_kw so that any
# future new ticks will automatically get them
if reset:
if which in ['major', 'both']:
self._reset_major_tick_kw()
self._major_tick_kw.update(kwtrans)
if which in ['minor', 'both']:
self._reset_minor_tick_kw()
self._minor_tick_kw.update(kwtrans)
self.reset_ticks()
else:
if which in ['major', 'both']:
self._major_tick_kw.update(kwtrans)
for tick in self.majorTicks:
tick._apply_params(**kwtrans)
if which in ['minor', 'both']:
self._minor_tick_kw.update(kwtrans)
for tick in self.minorTicks:
tick._apply_params(**kwtrans)
# labelOn and labelcolor also apply to the offset text.
if 'label1On' in kwtrans or 'label2On' in kwtrans:
self.offsetText.set_visible(
self._major_tick_kw.get('label1On', False)
or self._major_tick_kw.get('label2On', False))
if 'labelcolor' in kwtrans:
self.offsetText.set_color(kwtrans['labelcolor'])
self.stale = True
@staticmethod
def _translate_tick_kw(kw):
# The following lists may be moved to a more accessible location.
kwkeys = ['size', 'width', 'color', 'tickdir', 'pad',
'labelsize', 'labelcolor', 'zorder', 'gridOn',
'tick1On', 'tick2On', 'label1On', 'label2On',
'length', 'direction', 'left', 'bottom', 'right', 'top',
'labelleft', 'labelbottom', 'labelright', 'labeltop',
'labelrotation'] + _gridline_param_names
kwtrans = {}
if 'length' in kw:
kwtrans['size'] = kw.pop('length')
if 'direction' in kw:
kwtrans['tickdir'] = kw.pop('direction')
if 'rotation' in kw:
kwtrans['labelrotation'] = kw.pop('rotation')
if 'left' in kw:
kwtrans['tick1On'] = kw.pop('left')
if 'bottom' in kw:
kwtrans['tick1On'] = kw.pop('bottom')
if 'right' in kw:
kwtrans['tick2On'] = kw.pop('right')
if 'top' in kw:
kwtrans['tick2On'] = kw.pop('top')
if 'labelleft' in kw:
kwtrans['label1On'] = kw.pop('labelleft')
if 'labelbottom' in kw:
kwtrans['label1On'] = kw.pop('labelbottom')
if 'labelright' in kw:
kwtrans['label2On'] = kw.pop('labelright')
if 'labeltop' in kw:
kwtrans['label2On'] = kw.pop('labeltop')
if 'colors' in kw:
c = kw.pop('colors')
kwtrans['color'] = c
kwtrans['labelcolor'] = c
# Maybe move the checking up to the caller of this method.
for key in kw:
if key not in kwkeys:
raise ValueError(
"keyword %s is not recognized; valid keywords are %s"
% (key, kwkeys))
kwtrans.update(kw)
return kwtrans
def set_clip_path(self, clippath, transform=None):
super().set_clip_path(clippath, transform)
for child in self.majorTicks + self.minorTicks:
child.set_clip_path(clippath, transform)
self.stale = True
def get_view_interval(self):
"""Return the ``(min, max)`` view limits of this axis."""
raise NotImplementedError('Derived must override')
def set_view_interval(self, vmin, vmax, ignore=False):
"""
Set the axis view limits. This method is for internal use; Matplotlib
users should typically use e.g. `~.Axes.set_xlim` or `~.Axes.set_ylim`.
If *ignore* is False (the default), this method will never reduce the
preexisting view limits, only expand them if *vmin* or *vmax* are not
within them. Moreover, the order of *vmin* and *vmax* does not matter;
the orientation of the axis will not change.
If *ignore* is True, the view limits will be set exactly to ``(vmin,
vmax)`` in that order.
"""
raise NotImplementedError('Derived must override')
def get_data_interval(self):
"""Return the ``(min, max)`` data limits of this axis."""
raise NotImplementedError('Derived must override')
def set_data_interval(self, vmin, vmax, ignore=False):
"""
Set the axis data limits. This method is for internal use.
If *ignore* is False (the default), this method will never reduce the
preexisting data limits, only expand them if *vmin* or *vmax* are not
within them. Moreover, the order of *vmin* and *vmax* does not matter;
the orientation of the axis will not change.
If *ignore* is True, the data limits will be set exactly to ``(vmin,
vmax)`` in that order.
"""
raise NotImplementedError('Derived must override')
def get_inverted(self):
"""
Return whether this Axis is oriented in the "inverse" direction.
The "normal" direction is increasing to the right for the x-axis and to
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
low, high = self.get_view_interval()
return high < low
def set_inverted(self, inverted):
"""
Set whether this Axis is oriented in the "inverse" direction.
The "normal" direction is increasing to the right for the x-axis and to
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
# Currently, must be implemented in subclasses using set_xlim/set_ylim
# rather than generically using set_view_interval, so that shared
# axes get updated as well.
raise NotImplementedError('Derived must override')