-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathcartesian.py
More file actions
1668 lines (1535 loc) · 66.5 KB
/
cartesian.py
File metadata and controls
1668 lines (1535 loc) · 66.5 KB
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
#!/usr/bin/env python3
"""
The standard Cartesian axes used for most ultraplot figures.
"""
import copy
import inspect
from dataclasses import dataclass, field
from typing import Any, Dict, Optional, Tuple, Union
import matplotlib.axis as maxis
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import numpy as np
from packaging import version
from .. import constructor
from .. import scale as pscale
from .. import ticker as pticker
from ..config import rc
from ..internals import (
_not_none,
_pop_rc,
_version_mpl,
docstring,
ic, # noqa: F401
labels,
warnings,
)
from ..utils import units
from . import plot, shared
__all__ = ["CartesianAxes"]
# Tuple of date converters
DATE_CONVERTERS = (mdates.DateConverter,)
if hasattr(mdates, "_SwitchableDateConverter"):
DATE_CONVERTERS += (mdates._SwitchableDateConverter,)
# Opposite side keywords
OPPOSITE_SIDE = {
"left": "right",
"right": "left",
"bottom": "top",
"top": "bottom",
}
# Format docstring
_format_docstring = """
aspect : {'auto', 'equal'} or float, optional
The data aspect ratio. See :func:`~matplotlib.axes.Axes.set_aspect`
for details.
xlabel, ylabel : str, optional
The x and y axis labels. Applied with `~matplotlib.axes.Axes.set_xlabel`
and `~matplotlib.axes.Axes.set_ylabel`.
xlabel_kw, ylabel_kw : dict-like, optional
Additional axis label settings applied with `~matplotlib.axes.Axes.set_xlabel`
and `~matplotlib.axes.Axes.set_ylabel`. See also `labelpad`, `labelcolor`,
`labelsize`, and `labelweight` below.
xlim, ylim : 2-tuple of floats or None, optional
The x and y axis data limits. Applied with :func:`~matplotlib.axes.Axes.set_xlim`
and :func:`~matplotlib.axes.Axes.set_ylim`.
xmin, ymin : float, optional
The x and y minimum data limits. Useful if you do not want
to set the maximum limits.
xmax, ymax : float, optional
The x and y maximum data limits. Useful if you do not want
to set the minimum limits.
xreverse, yreverse : bool, optional
Whether to "reverse" the x and y axis direction. Makes the x and
y axes ascend left-to-right and top-to-bottom, respectively.
xscale, yscale : scale-spec, optional
The x and y axis scales. Passed to the `~ultraplot.scale.Scale` constructor.
For example, ``xscale='log'`` applies logarithmic scaling, and
``xscale=('cutoff', 100, 2)`` applies a `~ultraplot.scale.CutoffScale`.
xscale_kw, yscale_kw : dict-like, optional
The x and y axis scale settings. Passed to `~ultraplot.scale.Scale`.
xmargin, ymargin, margin : float, default: :rc:`margin`
The default margin between plotted content and the x and y axis spines in
axes-relative coordinates. This is useful if you don't witch to explicitly set
axis limits. Use the keyword `margin` to set both at once.
xbounds, ybounds : 2-tuple of float, optional
The x and y axis data bounds within which to draw the spines. For example,
``xlim=(0, 4)`` combined with ``xbounds=(2, 4)`` will prevent the spines
from meeting at the origin. This also applies ``xspineloc='bottom'`` and
``yspineloc='left'`` by default if both spines are currently visible.
xtickrange, ytickrange : 2-tuple of float, optional
The x and y axis data ranges within which major tick marks are labelled.
For example, ``xlim=(-5, 5)`` combined with ``xtickrange=(-1, 1)`` and a
tick interval of 1 will only label the ticks marks at -1, 0, and 1. See
`~ultraplot.ticker.AutoFormatter` for details.
xwraprange, ywraprange : 2-tuple of float, optional
The x and y axis data ranges with which major tick mark values are wrapped. For
example, ``xwraprange=(0, 3)`` causes the values 0 through 9 to be formatted as
0, 1, 2, 0, 1, 2, 0, 1, 2, 0. See `~ultraplot.ticker.AutoFormatter` for details. This
can be combined with `xtickrange` and `ytickrange` to make "stacked" line plots.
xloc, yloc : optional
Shorthands for `xspineloc`, `yspineloc`.
xspineloc, yspineloc : {'b', 't', 'l', 'r', 'bottom', 'top', 'left', 'right', \
'both', 'neither', 'none', 'zero', 'center'} or 2-tuple, optional
The x and y spine locations. Applied with `~matplotlib.spines.Spine.set_position`.
Propagates to `tickloc` unless specified otherwise.
xtickloc, ytickloc : {'b', 't', 'l', 'r', 'bottom', 'top', 'left', 'right', \
'both', 'neither', 'none'}, optional
Which x and y axis spines should have major and minor tick marks. Inherits from
`spineloc` by default and propagates to `ticklabelloc` unless specified otherwise.
xticklabelloc, yticklabelloc : {'b', 't', 'l', 'r', 'bottom', 'top', 'left', 'right', \
'both', 'neither', 'none'}, optional
Which x and y axis spines should have major tick labels. Inherits from `tickloc`
by default and propagates to `labelloc` and `offsetloc` unless specified otherwise.
xlabelloc, ylabelloc : \
{'b', 't', 'l', 'r', 'bottom', 'top', 'left', 'right'}, optional
Which x and y axis spines should have axis labels. Inherits from
`ticklabelloc` by default (if `ticklabelloc` is a single side).
xoffsetloc, yoffsetloc : \
{'b', 't', 'l', 'r', 'bottom', 'top', 'left', 'right'}, optional
Which x and y axis spines should have the axis offset indicator. Inherits from
`ticklabelloc` by default (if `ticklabelloc` is a single side).
xtickdir, ytickdir, tickdir : {'out', 'in', 'inout'}, optional
Direction that major and minor tick marks point for the x and y axis.
Use the keyword `tickdir` to control both.
xticklabeldir, yticklabeldir : {'in', 'out'}, optional
Whether to place x and y axis tick label text inside or outside the axes.
Propagates to `xtickdir` and `ytickdir` unless specified otherwise.
xrotation, yrotation : float, default: 0
The rotation for x and y axis tick labels.
for normal axes, :rc:`formatter.timerotation` for time x axes.
xgrid, ygrid, grid : bool, default: :rc:`grid`
Whether to draw major gridlines on the x and y axis.
Use the keyword `grid` to toggle both.
xgridminor, ygridminor, gridminor : bool, default: :rc:`gridminor`
Whether to draw minor gridlines for the x and y axis.
Use the keyword `gridminor` to toggle both.
xtickminor, ytickminor, tickminor : bool, default: :rc:`tick.minor`
Whether to draw minor ticks on the x and y axes.
Use the keyword `tickminor` to toggle both.
xticks, yticks : optional
Aliases for `xlocator`, `ylocator`.
xlocator, ylocator : locator-spec, optional
Used to determine the x and y axis tick mark positions. Passed
to the `~ultraplot.constructor.Locator` constructor. Can be float,
list of float, string, or `matplotlib.ticker.Locator` instance.
Use ``[]``, ``'null'``, or ``'none'`` for no ticks.
xlocator_kw, ylocator_kw : dict-like, optional
Keyword arguments passed to the `matplotlib.ticker.Locator` class.
xminorticks, yminorticks : optional
Aliases for `xminorlocator`, `yminorlocator`.
xminorlocator, yminorlocator : optional
As for `xlocator`, `ylocator`, but for the minor ticks.
xminorlocator_kw, yminorlocator_kw
As for `xlocator_kw`, `ylocator_kw`, but for the minor locator.
xticklabels, yticklabels : optional
Aliases for `xformatter`, `yformatter`.
xformatter, yformatter : formatter-spec, optional
Used to determine the x and y axis tick label string format.
Passed to the `~ultraplot.constructor.Formatter` constructor.
Can be string, list of strings, or `matplotlib.ticker.Formatter` instance.
Use ``[]``, ``'null'``, or ``'none'`` for no labels.
xformatter_kw, yformatter_kw : dict-like, optional
Keyword arguments passed to the `matplotlib.ticker.Formatter` class.
xcolor, ycolor, color : color-spec, default: :rc:`meta.color`
Color for the x and y axis spines, ticks, tick labels, and axis labels.
Use the keyword `color` to set both at once.
xgridcolor, ygridcolor, gridcolor : color-spec, default: :rc:`grid.color`
Color for the x and y axis major and minor gridlines.
Use the keyword `gridcolor` to set both at once.
xlinewidth, ylinewidth, linewidth : color-spec, default: :rc:`meta.width`
Line width for the x and y axis spines and major ticks. Propagates to `tickwidth`
unless specified otherwise. Use the keyword `linewidth` to set both at once.
xtickcolor, ytickcolor, tickcolor : color-spec, default: :rc:`tick.color`
Color for the x and y axis ticks. Defaults are `xcolor`, `ycolor`, and `color`
if they were passed. Use the keyword `tickcolor` to set both at once.
xticklen, yticklen, ticklen : unit-spec, default: :rc:`tick.len`
Major tick lengths for the x and y axis.
%(units.pt)s
Use the keyword `ticklen` to set both at once.
xticklenratio, yticklenratio, ticklenratio : float, default: :rc:`tick.lenratio`
Relative scaling of `xticklen` and `yticklen` used to determine minor
tick lengths. Use the keyword `ticklenratio` to set both at once.
xtickwidth, ytickwidth, tickwidth, : unit-spec, default: :rc:`tick.width`
Major tick widths for the x ans y axis. Default is `linewidth` if it was passed.
%(units.pt)s
Use the keyword `tickwidth` to set both at once.
xtickwidthratio, ytickwidthratio, tickwidthratio : float, default: :rc:`tick.widthratio`
Relative scaling of `xtickwidth` and `ytickwidth` used to determine
minor tick widths. Use the keyword `tickwidthratio` to set both at once.
xticklabelpad, yticklabelpad, ticklabelpad : unit-spec, default: :rc:`tick.labelpad`
The padding between the x and y axis ticks and tick labels. Use the
keyword `ticklabelpad` to set both at once.
%(units.pt)s
xticklabelcolor, yticklabelcolor, ticklabelcolor \
: color-spec, default: :rc:`tick.labelcolor`
Color for the x and y tick labels. Defaults are `xcolor`, `ycolor`, and `color`
if they were passed. Use the keyword `ticklabelcolor` to set both at once.
xticklabelsize, yticklabelsize, ticklabelsize \
: unit-spec or str, default: :rc:`tick.labelsize`
Font size for the x and y tick labels.
%(units.pt)s
Use the keyword `ticklabelsize` to set both at once.
xticklabelweight, yticklabelweight, ticklabelweight \
: str, default: :rc:`tick.labelweight`
Font weight for the x and y tick labels.
Use the keyword `ticklabelweight` to set both at once.
xlabelpad, ylabelpad : unit-spec, default: :rc:`label.pad`
The padding between the x and y axis bounding box and the x and y axis labels.
%(units.pt)s
xlabelcolor, ylabelcolor, labelcolor : color-spec, default: :rc:`label.color`
Color for the x and y axis labels. Defaults are `xcolor`, `ycolor`, and `color`
if they were passed. Use the keyword `labelcolor` to set both at once.
xlabelsize, ylabelsize, labelsize : unit-spec or str, default: :rc:`label.size`
Font size for the x and y axis labels.
%(units.pt)s
Use the keyword `labelsize` to set both at once.
xlabelweight, ylabelweight, labelweight : str, default: :rc:`label.weight`
Font weight for the x and y axis labels.
Use the keyword `labelweight` to set both at once.
fixticks : bool, default: False
Whether to transform the tick locators to a `~matplotlib.ticker.FixedLocator`.
If your axis ticks are doing weird things (for example, ticks are drawn
outside of the axis spine) you can try setting this to ``True``.
"""
docstring._snippet_manager["cartesian.format"] = _format_docstring
# Shared docstring
_shared_x_keys = {
"x": "x",
"x1": "bottom",
"x2": "top",
"y": "y",
"y1": "left",
"y2": "right",
}
_shared_y_keys = {
"x": "y",
"x1": "left",
"x2": "right",
"y": "x",
"y1": "bottom",
"y2": "top",
}
_shared_docstring = """
%(descrip)s
Parameters
----------
%(extra)s**kwargs
Passed to `~ultraplot.axes.CartesianAxes`. Supports all valid
`~ultraplot.axes.CartesianAxes.format` keywords. You can optionally
omit the {x} from keywords beginning with ``{x}`` -- for example
``ax.alt{x}(lim=(0, 10))`` is equivalent to ``ax.alt{x}({x}lim=(0, 10))``.
You can also change the default side for the axis spine, axis tick marks,
axis tick labels, and/or axis labels by passing ``loc`` keywords. For example,
``ax.alt{x}(loc='{x1}')`` changes the default side from {x2} to {x1}.
Returns
-------
ultraplot.axes.CartesianAxes
The resulting axes.
Note
----
This enforces the following default settings:
* Places the old {x} axis on the {x1} and the new {x}
axis on the {x2}.
* Makes the old {x2} spine invisible and the new {x1}, {y1},
and {y2} spines invisible.
* Adjusts the {x} axis tick, tick label, and axis label positions
according to the visible spine positions.
* Syncs the old and new {y} axis limits and scales, and makes the
new {y} axis labels invisible.
"""
# Alt docstrings
# NOTE: Used by SubplotGrid.altx
_alt_descrip = """
Add an axis locked to the same location with a
distinct {x} axis.
This is an alias and arguably more intuitive name for
`~ultraplot.axes.CartesianAxes.twin{y}`, which generates
two {x} axes with a shared ("twin") {y} axes.
"""
_alt_docstring = _shared_docstring % {"descrip": _alt_descrip, "extra": ""}
docstring._snippet_manager["axes.altx"] = _alt_docstring.format(**_shared_x_keys)
docstring._snippet_manager["axes.alty"] = _alt_docstring.format(**_shared_y_keys)
# Twin docstrings
# NOTE: Used by SubplotGrid.twinx
_twin_descrip = """
Add an axis locked to the same location with a
distinct {x} axis.
This builds upon `matplotlib.axes.Axes.twin{y}`.
"""
_twin_docstring = _shared_docstring % {"descrip": _twin_descrip, "extra": ""}
docstring._snippet_manager["axes.twinx"] = _twin_docstring.format(**_shared_y_keys)
docstring._snippet_manager["axes.twiny"] = _twin_docstring.format(**_shared_x_keys)
# Dual docstrings
# NOTE: Used by SubplotGrid.dualx
_dual_descrip = """
Add an axes locked to the same location whose {x} axis denotes
equivalent coordinates in alternate units.
This is an alternative to `matplotlib.axes.Axes.secondary_{x}axis` with
additional convenience features.
"""
_dual_extra = """
funcscale : callable, 2-tuple of callables, or scale-spec
The scale used to transform units from the parent axis to the secondary
axis. This can be a `~ultraplot.scale.FuncScale` itself or a function,
(function, function) tuple, or an axis scale specification interpreted
by the `~ultraplot.constructor.Scale` constructor function, any of which
will be used to build a `~ultraplot.scale.FuncScale` and applied
to the dual axis (see `~ultraplot.scale.FuncScale` for details).
"""
_dual_docstring = _shared_docstring % {
"descrip": _dual_descrip,
"extra": _dual_extra.lstrip(),
} # noqa: E501
docstring._snippet_manager["axes.dualx"] = _dual_docstring.format(**_shared_x_keys)
docstring._snippet_manager["axes.dualy"] = _dual_docstring.format(**_shared_y_keys)
@dataclass
class _AxisFormatConfig:
"""A dataclass to hold formatting options for a single axis."""
# Limits and scale
min_: Optional[float] = None
max_: Optional[float] = None
lim: Optional[Tuple[Optional[float], Optional[float]]] = None
reverse: Optional[bool] = None
margin: Optional[float] = None
bounds: Optional[Tuple[float, float]] = None
tickrange: Optional[Tuple[float, float]] = None
wraprange: Optional[Tuple[float, float]] = None
scale: Any = None # scale-spec, e.g., 'log' or ('cutoff', 100, 2)
scale_kw: Dict[str, Any] = field(default_factory=dict)
# Spines and locations
spineloc: Any = None # e.g., 'bottom', 'zero', 'center'
tickloc: Any = None
ticklabelloc: Any = None
labelloc: Any = None
offsetloc: Any = None
# Grid
grid: Optional[bool] = None
gridminor: Optional[bool] = None
gridcolor: Any = None # color-spec
# Locators and Formatters
locator: Any = None # locator-spec
locator_kw: Dict[str, Any] = field(default_factory=dict)
minorlocator: Any = None # locator-spec
minorlocator_kw: Dict[str, Any] = field(default_factory=dict)
formatter: Any = None # formatter-spec
formatter_kw: Dict[str, Any] = field(default_factory=dict)
# Label properties
label: Optional[str] = None
label_kw: Dict[str, Any] = field(default_factory=dict)
labelpad: Any = None # unit-spec
labelcolor: Any = None # color-spec
labelsize: Any = None # unit-spec or str
labelweight: Optional[str] = None
# General appearance
color: Any = None # color-spec
linewidth: Any = None # unit-spec
rotation: Optional[Union[float, str]] = None
# Tick properties
tickminor: Optional[bool] = None
tickdir: Optional[str] = None
tickcolor: Any = None # color-spec
ticklen: Any = None # unit-spec
ticklenratio: Optional[float] = None
tickwidth: Any = None # unit-spec
tickwidthratio: Optional[float] = None
# Tick label properties
ticklabeldir: Optional[str] = None
ticklabelpad: Any = None # unit-spec
ticklabelcolor: Any = None # color-spec
ticklabelsize: Any = None # unit-spec or str
ticklabelweight: Optional[str] = None
class CartesianAxes(shared._SharedAxes, plot.PlotAxes):
"""
Axes subclass for plotting in ordinary Cartesian coordinates. Adds the
`~CartesianAxes.format` method and overrides several existing methods.
Important
---------
This is the default axes subclass. It can be specified explicitly by passing
``proj='cart'``, ``proj='cartesian'``, ``proj='rect'``, or ``proj='rectilinear'``
to axes-creation commands like `~ultraplot.figure.Figure.add_axes`,
`~ultraplot.figure.Figure.add_subplot`, and `~ultraplot.figure.Figure.subplots`.
"""
_name = "cartesian"
_name_aliases = ("cart", "rect", "rectilinar") # include matplotlib name
@docstring._snippet_manager
def __init__(self, *args, **kwargs):
"""
Parameters
----------
*args
Passed to `matplotlib.axes.Axes`.
%(cartesian.format)s
Other parameters
----------------
%(axes.format)s
%(rc.init)s
See also
--------
CartesianAxes.format
ultraplot.axes.Axes
ultraplot.axes.PlotAxes
ultraplot.figure.Figure.subplot
ultraplot.figure.Figure.add_subplot
"""
# Initialize axes
self._xaxis_current_rotation = "horizontal" # current rotation
self._yaxis_current_rotation = "horizontal"
self._xaxis_isdefault_rotation = True # whether to auto rotate the axis
self._yaxis_isdefault_rotation = True
super().__init__(*args, **kwargs)
# Apply default formatter
if self.xaxis.isDefault_majfmt:
self.xaxis.set_major_formatter(pticker.AutoFormatter())
self.xaxis.isDefault_majfmt = True
if self.yaxis.isDefault_majfmt:
self.yaxis.set_major_formatter(pticker.AutoFormatter())
self.yaxis.isDefault_majfmt = True
# Dual axes utilities
self._dualx_funcscale = None # for scaling units on dual axes
self._dualx_prevstate = None # prevent excess _dualy_scale calls
self._dualy_funcscale = None
self._dualy_prevstate = None
def _apply_axis_sharing(self):
"""
Enforce the "shared" axis labels and axis tick labels. If this is not
called at drawtime, "shared" labels can be inadvertantly turned off.
"""
# NOTE: Critical to apply labels to *shared* axes attributes rather
# than testing extents or we end up sharing labels with twin axes.
# NOTE: Similar to how _align_super_labels() calls _apply_title_above() this
# is called inside _align_axis_labels() so we align the correct text.
# NOTE: The "panel sharing group" refers to axes and panels *above* the
# bottommost or to the *right* of the leftmost panel. But the sharing level
# used for the leftmost and bottommost is the *figure* sharing level.
# Get border axes once for efficiency
border_axes = self.figure._get_border_axes()
# Apply X axis sharing
self._apply_axis_sharing_for_axis("x", border_axes)
# Apply Y axis sharing
self._apply_axis_sharing_for_axis("y", border_axes)
def _apply_axis_sharing_for_axis(
self,
axis_name: str,
border_axes: dict[str, plot.PlotAxes],
) -> None:
"""
Apply axis sharing for a specific axis (x or y).
Parameters
----------
axis_name : str
Either 'x' or 'y'
border_axes : dict
Dictionary from _get_border_axes() containing border information
"""
if axis_name == "x":
axis = self.xaxis
shared_axis = self._sharex
panel_group = self._panel_sharex_group
sharing_level = self.figure._sharex
label_params = ["labeltop", "labelbottom"]
border_sides = ["top", "bottom"]
else: # axis_name == 'y'
axis = self.yaxis
shared_axis = self._sharey
panel_group = self._panel_sharey_group
sharing_level = self.figure._sharey
label_params = ["labelleft", "labelright"]
border_sides = ["left", "right"]
if shared_axis is None or not axis.get_visible():
return
level = 3 if panel_group else sharing_level
# Handle axis label sharing (level > 0)
if level > 0:
if self.figure._is_share_label_group_member(self, axis_name):
pass
elif self.figure._is_share_label_group_member(shared_axis, axis_name):
axis.label.set_visible(False)
else:
shared_axis_obj = getattr(shared_axis, f"{axis_name}axis")
labels._transfer_label(axis.label, shared_axis_obj.label)
axis.label.set_visible(False)
# Handle tick label sharing (level > 2)
if level > 2:
label_visibility = self._determine_tick_label_visibility(
axis,
shared_axis,
axis_name,
label_params,
border_sides,
border_axes,
)
axis.set_tick_params(which="both", **label_visibility)
# Turn minor ticks off
axis.set_minor_formatter(mticker.NullFormatter())
def _determine_tick_label_visibility(
self,
axis: maxis.Axis,
shared_axis: maxis.Axis,
axis_name: str,
label_params: list[str],
border_sides: list[str],
border_axes: dict[str, list[plot.PlotAxes]],
) -> dict[str, bool]:
"""
Determine which tick labels should be visible based on sharing rules and borders.
Parameters
----------
axis : matplotlib axis
The current axis object
shared_axis : Axes
The axes this one shares with
axis_name : str
Either 'x' or 'y'
label_params : list
List of label parameter names (e.g., ['labeltop', 'labelbottom'])
border_sides : list
List of border side names (e.g., ['top', 'bottom'])
border_axes : dict
Dictionary from _get_border_axes()
Returns
-------
dict
Dictionary of label visibility parameters
"""
ticks = axis.get_tick_params()
shared_axis_obj = getattr(shared_axis, f"{axis_name}axis")
sharing_ticks = shared_axis_obj.get_tick_params()
label_visibility = {}
def _convert_label_param(label_param: str) -> str:
# Deal with logic not being consistent
# in prior mpl versions
if version.parse(str(_version_mpl)) <= version.parse("3.9"):
if label_param == "labeltop" and axis_name == "x":
label_param = "labelright"
elif label_param == "labelbottom" and axis_name == "x":
label_param = "labelleft"
return label_param
for label_param, border_side in zip(label_params, border_sides):
# Check if user has explicitly set label location via format()
label_visibility[label_param] = False
has_panel = False
for panel in self._panel_dict[border_side]:
# Check if the panel is a colorbar
colorbars = [
values
for key, values in self._colorbar_dict.items()
if border_side in key # key is tuple (side, top | center | lower)
]
if not panel in colorbars:
# Skip colorbar as their
# yaxis is not shared
has_panel = True
break
# When we have a panel, let the panel have
# the labels and turn-off for this axis + side.
if has_panel:
continue
is_border = self in border_axes.get(border_side, [])
is_panel = (
self in shared_axis._panel_dict[border_side]
and self == shared_axis._panel_dict[border_side][-1]
)
# Use automatic border detection logic
# if we are a panel we "push" the labels outwards
label_param_trans = _convert_label_param(label_param)
is_this_tick_on = ticks[label_param_trans]
is_parent_tick_on = sharing_ticks[label_param_trans]
if is_panel:
label_visibility[label_param] = is_parent_tick_on
elif is_border:
label_visibility[label_param] = is_this_tick_on
return label_visibility
def _add_alt(self, sx, **kwargs):
"""
Add an alternate axes.
"""
# Parse keyword arguments. Optionally omit redundant leading 'x' and 'y'
# WARNING: We add axes as children for tight layout algorithm convenience and
# to support eventual paradigm of arbitrarily many duplicates with spines
# arranged in an edge stack. However this means all artists drawn there take
# on zorder of their axes when drawn inside the "parent" (see Axes.draw()).
# To restore matplotlib behavior, which draws "child" artists on top simply
# because the axes was created after the "parent" one, use the inset_axes
# zorder of 4 and make the background transparent.
sy = "y" if sx == "x" else "x"
sig = self._format_signatures[CartesianAxes]
keys = tuple(key[1:] for key in sig.parameters if key[0] == sx)
kwargs = {
(sx + key if key in keys else key): val for key, val in kwargs.items()
} # noqa: E501
if f"{sy}spineloc" not in kwargs: # acccount for aliases
kwargs.setdefault(f"{sy}loc", "neither")
if f"{sx}spineloc" not in kwargs: # account for aliases
kwargs.setdefault(f"{sx}loc", "top" if sx == "x" else "right")
kwargs.setdefault(f"autoscale{sy}_on", getattr(self, f"get_autoscale{sy}_on")())
kwargs.setdefault(f"share{sy}", self)
# Initialize child axes
kwargs.setdefault("grid", False) # note xgrid=True would override this
kwargs.setdefault("zorder", 4) # increased default zorder
kwargs.setdefault("number", None)
kwargs.setdefault("autoshare", False)
if "sharex" in kwargs and "sharey" in kwargs:
raise ValueError("Twinned axes may share only one axis.")
locator = self._make_inset_locator([0, 0, 1, 1], self.transAxes)
ax = CartesianAxes(self.figure, locator(self, None).bounds, **kwargs)
ax.set_axes_locator(locator)
ax.set_adjustable("datalim")
self.add_child_axes(ax) # to facilitate tight layout
self.set_adjustable("datalim")
self._twinned_axes.join(self, ax)
# Format parent and child axes
self.format(**{f"{sx}loc": OPPOSITE_SIDE.get(kwargs[f"{sx}loc"], None)})
setattr(ax, f"_alt{sx}_parent", self)
getattr(ax, f"{sy}axis").set_visible(False)
getattr(ax, "patch").set_visible(False)
return ax
def _dual_scale(self, s, funcscale=None):
"""
Lock the child "dual" axis limits to the parent.
"""
# NOTE: We bypass autoscale_view because we set limits manually, and bypass
# child.stale = True because that is done in call to set_xlim() below.
# NOTE: We set the scale using private API to bypass application of
# set_default_locators_and_formatters: only_if_default=True is critical
# to prevent overriding user settings!
# NOTE: Dual axis only needs to be constrained if the parent axis scale
# and limits have changed, and limits are always applied before we reach
# the child.draw() because always called after parent.draw()
child = self
parent = getattr(self, f"_alt{s}_parent")
if funcscale is not None:
setattr(self, f"_dual{s}_funcscale", funcscale)
else:
funcscale = getattr(self, f"_dual{s}_funcscale")
if parent is None or funcscale is None:
return
olim = getattr(parent, f"get_{s}lim")()
scale = getattr(parent, f"{s}axis")._scale
if (scale, *olim) == getattr(child, f"_dual{s}_prevstate"):
return
funcscale = pscale.FuncScale(funcscale, invert=True, parent_scale=scale)
caxis = getattr(child, f"{s}axis")
caxis._scale = funcscale
child._update_transScale()
funcscale.set_default_locators_and_formatters(caxis, only_if_default=True)
nlim = list(map(funcscale.functions[1], np.array(olim)))
if np.sign(np.diff(olim)) != np.sign(np.diff(nlim)):
nlim = nlim[::-1] # if function flips limits, so will set_xlim!
getattr(child, f"set_{s}lim")(nlim, emit=False)
setattr(child, f"_dual{s}_prevstate", (scale, *olim))
def _fix_ticks(self, s, fixticks=False):
"""
Ensure there are no out-of-bounds ticks. Mostly a brute-force version of
`~matplotlib.axis.Axis.set_smart_bounds` (which I couldn't get to work).
"""
# NOTE: Previously triggered this every time FixedFormatter was found
# on axis but 1) that seems heavy-handed + strange and 2) internal
# application of FixedFormatter by boxplot resulted in subsequent format()
# successfully calling this and messing up the ticks for some reason.
# So avoid using this when possible, and try to make behavior consistent
# by cacheing the locators before we use them for ticks.
axis = getattr(self, f"{s}axis")
sides = ("bottom", "top") if s == "x" else ("left", "right")
l0, l1 = getattr(self, f"get_{s}lim")()
bounds = tuple(self.spines[side].get_bounds() or (None, None) for side in sides)
skipticks = lambda ticks: [ # noqa: E731
x
for x in ticks
if not any(
x < _not_none(b0, l0) or x > _not_none(b1, l1) for (b0, b1) in bounds
) # noqa: E501
]
if fixticks or any(x is not None for b in bounds for x in b):
# Major locator
locator = getattr(axis, "_major_locator_cached", None)
if locator is None:
locator = axis._major_locator_cached = axis.get_major_locator()
locator = constructor.Locator(skipticks(locator()))
axis.set_major_locator(locator)
# Minor locator
locator = getattr(axis, "_minor_locator_cached", None)
if locator is None:
locator = axis._minor_locator_cached = axis.get_minor_locator()
locator = constructor.Locator(skipticks(locator()))
axis.set_minor_locator(locator)
def _get_spine_side(self, s, loc):
"""
Get the spine side implied by the input location or position. This
propagates to tick mark, tick label, and axis label positions.
"""
# NOTE: Could defer error to CartesianAxes.format but instead use our
# own error message with info on coordinate position options.
sides = ("bottom", "top") if s == "x" else ("left", "right")
centers = ("zero", "center")
options = (*(s[0] for s in sides), *sides, "both", "neither", "none")
if np.iterable(loc) and len(loc) == 2 and loc[0] in ("axes", "data", "outward"):
lim = getattr(self, f"get_{s}lim")()
if loc[0] == "outward": # ambiguous so just choose first side
side = sides[0]
elif loc[0] == "axes":
side = sides[int(loc[1] > 0.5)]
else:
side = sides[int(loc[1] > lim[0] + 0.5 * (lim[1] - lim[0]))]
elif loc in centers: # ambiguous so just choose the first side
side = sides[0]
elif loc is None or loc in options:
side = loc
else:
raise ValueError(
f"Invalid {s} spine location {loc!r}. Options are: "
+ ", ".join(map(repr, (*options, *centers)))
+ " or a coordinate position ('axes', coord), "
+ " ('data', coord), or ('outward', coord)."
)
return side
def _sharex_limits(self, sharex):
"""
Safely share limits and tickers without resetting things.
"""
# Copy non-default limits and scales. Either this axes or the input
# axes could be a newly-created subplot while the other is a subplot
# with possibly-modified user settings we are careful to preserve.
for ax1, ax2 in ((self, sharex), (sharex, self)):
if ax1.get_xscale() == "linear" and ax2.get_xscale() != "linear":
ax1.set_xscale(ax2.get_xscale()) # non-default scale
if ax1.get_autoscalex_on() and not ax2.get_autoscalex_on():
ax1.set_xlim(ax2.get_xlim()) # non-default limits
# Copy non-default locators and formatters
self.sharex(sharex)
if sharex.xaxis.isDefault_majloc and not self.xaxis.isDefault_majloc:
sharex.xaxis.set_major_locator(self.xaxis.get_major_locator())
if sharex.xaxis.isDefault_minloc and not self.xaxis.isDefault_minloc:
sharex.xaxis.set_minor_locator(self.xaxis.get_minor_locator())
if sharex.xaxis.isDefault_majfmt and not self.xaxis.isDefault_majfmt:
sharex.xaxis.set_major_formatter(self.xaxis.get_major_formatter())
if sharex.xaxis.isDefault_minfmt and not self.xaxis.isDefault_minfmt:
sharex.xaxis.set_minor_formatter(self.xaxis.get_minor_formatter())
self.xaxis.major = sharex.xaxis.major
self.xaxis.minor = sharex.xaxis.minor
def _sharey_limits(self, sharey):
"""
Safely share limits and tickers without resetting things.
"""
# NOTE: See _sharex_limits for notes
for ax1, ax2 in ((self, sharey), (sharey, self)):
if ax1.get_yscale() == "linear" and ax2.get_yscale() != "linear":
ax1.set_yscale(ax2.get_yscale())
if ax1.get_autoscaley_on() and not ax2.get_autoscaley_on():
ax1.set_ylim(ax2.get_ylim())
self.sharey(sharey)
if sharey.yaxis.isDefault_majloc and not self.yaxis.isDefault_majloc:
sharey.yaxis.set_major_locator(self.yaxis.get_major_locator())
if sharey.yaxis.isDefault_minloc and not self.yaxis.isDefault_minloc:
sharey.yaxis.set_minor_locator(self.yaxis.get_minor_locator())
if sharey.yaxis.isDefault_majfmt and not self.yaxis.isDefault_majfmt:
sharey.yaxis.set_major_formatter(self.yaxis.get_major_formatter())
if sharey.yaxis.isDefault_minfmt and not self.yaxis.isDefault_minfmt:
sharey.yaxis.set_minor_formatter(self.yaxis.get_minor_formatter())
self.yaxis.major = sharey.yaxis.major
self.yaxis.minor = sharey.yaxis.minor
def _sharex_setup(self, sharex, *, labels=True, limits=True):
"""
Configure shared axes accounting. Input is the 'parent' axes from which this
one will draw its properties. Use keyword args to override settings.
"""
# Share panels across *different* subplots
super()._sharex_setup(sharex)
# Get the axis sharing level
level = (
3
if self._panel_sharex_group and self._is_panel_group_member(sharex)
else self.figure._sharex
)
if level not in range(5): # must be internal error
raise ValueError(f"Invalid sharing level sharex={level!r}.")
if sharex in (None, self) or not isinstance(sharex, CartesianAxes):
return
# Share future axis label changes. Implemented in _apply_axis_sharing().
# Matplotlib only uses these attributes in __init__() and cla() to share
# tickers -- all other builtin sharing features derives from shared x axes
if level > 0 and labels:
self._sharex = sharex
# Share future axis tickers, limits, and scales
# NOTE: Only difference between levels 2 and 3 is level 3 hides tick
# labels. But this is done after the fact -- tickers are still shared.
if level > 1 and limits:
self._sharex_limits(sharex)
def _sharey_setup(self, sharey, *, labels=True, limits=True):
"""
Configure shared axes accounting for panels. The input is the
'parent' axes, from which this one will draw its properties.
"""
# NOTE: See _sharex_setup for notes
super()._sharey_setup(sharey)
level = (
3
if self._panel_sharey_group and self._is_panel_group_member(sharey)
else self.figure._sharey
)
if level not in range(5): # must be internal error
raise ValueError(f"Invalid sharing level sharey={level!r}.")
if sharey in (None, self) or not isinstance(sharey, CartesianAxes):
return
if level > 0 and labels:
self._sharey = sharey
if level > 1 and limits:
self._sharey_limits(sharey)
def _apply_log_formatter_on_scale(self, s):
"""
Enforce log formatter when log scale is set and rc is enabled.
"""
if not rc.find("formatter.log", context=True):
return
if getattr(self, f"get_{s}scale")() != "log":
return
self._update_formatter(s, "log")
def set_xscale(self, value, **kwargs):
result = super().set_xscale(value, **kwargs)
self._apply_log_formatter_on_scale("x")
return result
def set_yscale(self, value, **kwargs):
result = super().set_yscale(value, **kwargs)
self._apply_log_formatter_on_scale("y")
return result
def _update_formatter(
self,
s,
formatter=None,
*,
formatter_kw=None,
tickrange=None,
wraprange=None,
):
"""
Update the axis formatter. Passes `formatter` through `Formatter` with kwargs.
"""
# Test if this is date axes
# See: https://matplotlib.org/api/units_api.html
# And: https://matplotlib.org/api/dates_api.html
axis = getattr(self, f"{s}axis")
# TODO(compat): Drop this function when mpl 3.12 is deprecated.
# Introduced in mpl 3.10 and deprecated in mpl 3.12
# Save the original if it exists
converter = (
axis.converter if hasattr(axis, "converter") else axis.get_converter()
)
date = isinstance(converter, DATE_CONVERTERS)
# Major formatter
# NOTE: The default axis formatter accepts lots of keywords. So unlike
# everywhere else that uses constructor functions we also allow only
# formatter_kw input without formatter and use 'auto' as the default.
formatter_kw = formatter_kw or {}
formatter_kw = formatter_kw.copy()
if (
formatter is not None
or tickrange is not None
or wraprange is not None
or formatter_kw
): # noqa: E501
# Tick range
formatter = _not_none(formatter, "auto")
if tickrange is not None or wraprange is not None:
if formatter != "auto":
warnings._warn_ultraplot(
"The tickrange and autorange features require "
"ultraplot.AutoFormatter formatter. Overriding the input."
)
if tickrange is not None:
formatter_kw.setdefault("tickrange", tickrange)
if wraprange is not None:
formatter_kw.setdefault("wraprange", wraprange)
# Set the formatter
# Note some formatters require 'locator' as keyword arg
if formatter in ("date", "concise"):
locator = axis.get_major_locator()
formatter_kw.setdefault("locator", locator)
formatter = constructor.Formatter(formatter, date=date, **formatter_kw)
axis.set_major_formatter(formatter)
def _update_labels(self, s, *args, **kwargs):
"""
Apply axis labels to the relevant shared axis. If spanning labels are toggled
this keeps the labels synced for all subplots in the same row or column. Label
positions will be adjusted at draw-time with figure._align_axislabels.
"""
# NOTE: Critical to test whether arguments are None or else this
# will set isDefault_label to False every time format() is called.
# NOTE: This always updates the *current* labels and sharing is handled
# later so that labels set with set_xlabel() and set_ylabel() are shared too.
# See notes in _align_axis_labels() and _apply_axis_sharing().
kwargs = rc._get_label_props(**kwargs)
no_args = all(a is None for a in args)
no_kwargs = all(v is None for v in kwargs.values())
if no_args and no_kwargs:
return # also returns if args and kwargs are empty
setter = getattr(self, f"set_{s}label")
getter = getattr(self, f"get_{s}label")
if no_args: # otherwise label text is reset!
args = (getter(),)
setter(*args, **kwargs)
def _update_locators(
self,
s,
locator=None,
minorlocator=None,
*,
tickminor=None,
locator_kw=None,
minorlocator_kw=None,
):
"""
Update the locators. Requires `Locator` instances.
"""
# Apply input major locator
axis = getattr(self, f"{s}axis")
locator_kw = locator_kw or {}
if locator is not None:
locator = constructor.Locator(locator, **locator_kw)
axis.set_major_locator(locator)
if isinstance(locator, (mticker.IndexLocator, pticker.IndexLocator)):
tickminor = _not_none(tickminor, False) # disable 'index' minor ticks
# Apply input or default minor locator
# NOTE: Parts of API (dualxy) rely on minor tick toggling preserving the
# isDefault_minloc setting. In future should override mpl minorticks_on()
# NOTE: Unlike matplotlib when "turning on" minor ticks we *always* use the
# scale default, thanks to scale classes refactoring with _ScaleBase.
isdefault = minorlocator is None
minorlocator_kw = minorlocator_kw or {}
if not isdefault:
minorlocator = constructor.Locator(minorlocator, **minorlocator_kw)
elif tickminor:
minorlocator = getattr(axis._scale, "_default_minor_locator", None)
minorlocator = copy.copy(minorlocator)
minorlocator = constructor.Locator(minorlocator or "minor")
if minorlocator is not None:
axis.set_minor_locator(minorlocator)
axis.isDefault_minloc = isdefault
# Disable minor ticks
# NOTE: Generally if you *enable* minor ticks on a dual axis, want to
# allow FuncScale updates to change the minor tick locators. If you