-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
_base.py
4644 lines (3953 loc) · 174 KB
/
_base.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
from collections.abc import Iterable, Sequence
from contextlib import ExitStack
import functools
import inspect
import logging
from numbers import Real
from operator import attrgetter
import types
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _docstring, offsetbox
import matplotlib.artist as martist
import matplotlib.axis as maxis
from matplotlib.cbook import _OrderedSet, _check_1d, index_of
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors
import matplotlib.font_manager as font_manager
from matplotlib.gridspec import SubplotSpec
import matplotlib.image as mimage
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
from matplotlib.rcsetup import cycler, validate_axisbelow
import matplotlib.spines as mspines
import matplotlib.table as mtable
import matplotlib.text as mtext
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
_log = logging.getLogger(__name__)
class _axis_method_wrapper:
"""
Helper to generate Axes methods wrapping Axis methods.
After ::
get_foo = _axis_method_wrapper("xaxis", "get_bar")
(in the body of a class) ``get_foo`` is a method that forwards it arguments
to the ``get_bar`` method of the ``xaxis`` attribute, and gets its
signature and docstring from ``Axis.get_bar``.
The docstring of ``get_foo`` is built by replacing "this Axis" by "the
{attr_name}" (i.e., "the xaxis", "the yaxis") in the wrapped method's
dedented docstring; additional replacements can be given in *doc_sub*.
"""
def __init__(self, attr_name, method_name, *, doc_sub=None):
self.attr_name = attr_name
self.method_name = method_name
# Immediately put the docstring in ``self.__doc__`` so that docstring
# manipulations within the class body work as expected.
doc = inspect.getdoc(getattr(maxis.Axis, method_name))
self._missing_subs = []
if doc:
doc_sub = {"this Axis": f"the {self.attr_name}", **(doc_sub or {})}
for k, v in doc_sub.items():
if k not in doc: # Delay raising error until we know qualname.
self._missing_subs.append(k)
doc = doc.replace(k, v)
self.__doc__ = doc
def __set_name__(self, owner, name):
# This is called at the end of the class body as
# ``self.__set_name__(cls, name_under_which_self_is_assigned)``; we
# rely on that to give the wrapper the correct __name__/__qualname__.
get_method = attrgetter(f"{self.attr_name}.{self.method_name}")
def wrapper(self, *args, **kwargs):
return get_method(self)(*args, **kwargs)
wrapper.__module__ = owner.__module__
wrapper.__name__ = name
wrapper.__qualname__ = f"{owner.__qualname__}.{name}"
wrapper.__doc__ = self.__doc__
# Manually copy the signature instead of using functools.wraps because
# displaying the Axis method source when asking for the Axes method
# source would be confusing.
wrapper.__signature__ = inspect.signature(
getattr(maxis.Axis, self.method_name))
if self._missing_subs:
raise ValueError(
"The definition of {} expected that the docstring of Axis.{} "
"contains {!r} as substrings".format(
wrapper.__qualname__, self.method_name,
", ".join(map(repr, self._missing_subs))))
setattr(owner, name, wrapper)
class _TransformedBoundsLocator:
"""
Axes locator for `.Axes.inset_axes` and similarly positioned Axes.
The locator is a callable object used in `.Axes.set_aspect` to compute the
Axes location depending on the renderer.
"""
def __init__(self, bounds, transform):
"""
*bounds* (a ``[l, b, w, h]`` rectangle) and *transform* together
specify the position of the inset Axes.
"""
self._bounds = bounds
self._transform = transform
def __call__(self, ax, renderer):
# Subtracting transSubfigure will typically rely on inverted(),
# freezing the transform; thus, this needs to be delayed until draw
# time as transSubfigure may otherwise change after this is evaluated.
return mtransforms.TransformedBbox(
mtransforms.Bbox.from_bounds(*self._bounds),
self._transform - ax.figure.transSubfigure)
def _process_plot_format(fmt, *, ambiguous_fmt_datakey=False):
"""
Convert a MATLAB style color/line style format string to a (*linestyle*,
*marker*, *color*) tuple.
Example format strings include:
* 'ko': black circles
* '.b': blue dots
* 'r--': red dashed lines
* 'C2--': the third color in the color cycle, dashed lines
The format is absolute in the sense that if a linestyle or marker is not
defined in *fmt*, there is no line or marker. This is expressed by
returning 'None' for the respective quantity.
See Also
--------
matplotlib.Line2D.lineStyles, matplotlib.colors.cnames
All possible styles and color format strings.
"""
linestyle = None
marker = None
color = None
# Is fmt just a colorspec?
try:
color = mcolors.to_rgba(fmt)
# We need to differentiate grayscale '1.0' from tri_down marker '1'
try:
fmtint = str(int(fmt))
except ValueError:
return linestyle, marker, color # Yes
else:
if fmt != fmtint:
# user definitely doesn't want tri_down marker
return linestyle, marker, color # Yes
else:
# ignore converted color
color = None
except ValueError:
pass # No, not just a color.
errfmt = ("{!r} is neither a data key nor a valid format string ({})"
if ambiguous_fmt_datakey else
"{!r} is not a valid format string ({})")
i = 0
while i < len(fmt):
c = fmt[i]
if fmt[i:i+2] in mlines.lineStyles: # First, the two-char styles.
if linestyle is not None:
raise ValueError(errfmt.format(fmt, "two linestyle symbols"))
linestyle = fmt[i:i+2]
i += 2
elif c in mlines.lineStyles:
if linestyle is not None:
raise ValueError(errfmt.format(fmt, "two linestyle symbols"))
linestyle = c
i += 1
elif c in mlines.lineMarkers:
if marker is not None:
raise ValueError(errfmt.format(fmt, "two marker symbols"))
marker = c
i += 1
elif c in mcolors.get_named_colors_mapping():
if color is not None:
raise ValueError(errfmt.format(fmt, "two color symbols"))
color = c
i += 1
elif c == 'C' and i < len(fmt) - 1:
color_cycle_number = int(fmt[i + 1])
color = mcolors.to_rgba(f"C{color_cycle_number}")
i += 2
else:
raise ValueError(
errfmt.format(fmt, f"unrecognized character {c!r}"))
if linestyle is None and marker is None:
linestyle = mpl.rcParams['lines.linestyle']
if linestyle is None:
linestyle = 'None'
if marker is None:
marker = 'None'
return linestyle, marker, color
class _process_plot_var_args:
"""
Process variable length arguments to `~.Axes.plot`, to support ::
plot(t, s)
plot(t1, s1, t2, s2)
plot(t1, s1, 'ko', t2, s2)
plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3)
an arbitrary number of *x*, *y*, *fmt* are allowed
"""
def __init__(self, command='plot'):
self.command = command
self.set_prop_cycle(None)
def set_prop_cycle(self, cycler):
if cycler is None:
cycler = mpl.rcParams['axes.prop_cycle']
self._idx = 0
self._cycler_items = [*cycler]
self._prop_keys = cycler.keys # This should make a copy
def __call__(self, axes, *args, data=None, **kwargs):
axes._process_unit_info(kwargs=kwargs)
for pos_only in "xy":
if pos_only in kwargs:
raise _api.kwarg_error(self.command, pos_only)
if not args:
return
if data is None: # Process dict views
args = [cbook.sanitize_sequence(a) for a in args]
else: # Process the 'data' kwarg.
replaced = [mpl._replacer(data, arg) for arg in args]
if len(args) == 1:
label_namer_idx = 0
elif len(args) == 2: # Can be x, y or y, c.
# Figure out what the second argument is.
# 1) If the second argument cannot be a format shorthand, the
# second argument is the label_namer.
# 2) Otherwise (it could have been a format shorthand),
# a) if we did perform a substitution, emit a warning, and
# use it as label_namer.
# b) otherwise, it is indeed a format shorthand; use the
# first argument as label_namer.
try:
_process_plot_format(args[1])
except ValueError: # case 1)
label_namer_idx = 1
else:
if replaced[1] is not args[1]: # case 2a)
_api.warn_external(
f"Second argument {args[1]!r} is ambiguous: could "
f"be a format string but is in 'data'; using as "
f"data. If it was intended as data, set the "
f"format string to an empty string to suppress "
f"this warning. If it was intended as a format "
f"string, explicitly pass the x-values as well. "
f"Alternatively, rename the entry in 'data'.",
RuntimeWarning)
label_namer_idx = 1
else: # case 2b)
label_namer_idx = 0
elif len(args) == 3:
label_namer_idx = 1
else:
raise ValueError(
"Using arbitrary long args with data is not supported due "
"to ambiguity of arguments; use multiple plotting calls "
"instead")
if kwargs.get("label") is None:
kwargs["label"] = mpl._label_from_arg(
replaced[label_namer_idx], args[label_namer_idx])
args = replaced
ambiguous_fmt_datakey = data is not None and len(args) == 2
if len(args) >= 4 and not cbook.is_scalar_or_string(
kwargs.get("label")):
raise ValueError("plot() with multiple groups of data (i.e., "
"pairs of x and y) does not support multiple "
"labels")
# Repeatedly grab (x, y) or (x, y, format) from the front of args and
# massage them into arguments to plot() or fill().
while args:
this, args = args[:2], args[2:]
if args and isinstance(args[0], str):
this += args[0],
args = args[1:]
yield from self._plot_args(
axes, this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey)
def get_next_color(self):
"""Return the next color in the cycle."""
if 'color' not in self._prop_keys:
return 'k'
c = self._cycler_items[self._idx]['color']
self._idx = (self._idx + 1) % len(self._cycler_items)
return c
def _getdefaults(self, ignore, kw):
"""
If some keys in the property cycle (excluding those in the set
*ignore*) are absent or set to None in the dict *kw*, return a copy
of the next entry in the property cycle, excluding keys in *ignore*.
Otherwise, don't advance the property cycle, and return an empty dict.
"""
prop_keys = self._prop_keys - ignore
if any(kw.get(k, None) is None for k in prop_keys):
# Need to copy this dictionary or else the next time around
# in the cycle, the dictionary could be missing entries.
default_dict = self._cycler_items[self._idx].copy()
self._idx = (self._idx + 1) % len(self._cycler_items)
for p in ignore:
default_dict.pop(p, None)
else:
default_dict = {}
return default_dict
def _setdefaults(self, defaults, kw):
"""
Add to the dict *kw* the entries in the dict *default* that are absent
or set to None in *kw*.
"""
for k in defaults:
if kw.get(k, None) is None:
kw[k] = defaults[k]
def _makeline(self, axes, x, y, kw, kwargs):
kw = {**kw, **kwargs} # Don't modify the original kw.
default_dict = self._getdefaults(set(), kw)
self._setdefaults(default_dict, kw)
seg = mlines.Line2D(x, y, **kw)
return seg, kw
def _makefill(self, axes, x, y, kw, kwargs):
# Polygon doesn't directly support unitized inputs.
x = axes.convert_xunits(x)
y = axes.convert_yunits(y)
kw = kw.copy() # Don't modify the original kw.
kwargs = kwargs.copy()
# Ignore 'marker'-related properties as they aren't Polygon
# properties, but they are Line2D properties, and so they are
# likely to appear in the default cycler construction.
# This is done here to the defaults dictionary as opposed to the
# other two dictionaries because we do want to capture when a
# *user* explicitly specifies a marker which should be an error.
# We also want to prevent advancing the cycler if there are no
# defaults needed after ignoring the given properties.
ignores = {'marker', 'markersize', 'markeredgecolor',
'markerfacecolor', 'markeredgewidth'}
# Also ignore anything provided by *kwargs*.
for k, v in kwargs.items():
if v is not None:
ignores.add(k)
# Only using the first dictionary to use as basis
# for getting defaults for back-compat reasons.
# Doing it with both seems to mess things up in
# various places (probably due to logic bugs elsewhere).
default_dict = self._getdefaults(ignores, kw)
self._setdefaults(default_dict, kw)
# Looks like we don't want "color" to be interpreted to
# mean both facecolor and edgecolor for some reason.
# So the "kw" dictionary is thrown out, and only its
# 'color' value is kept and translated as a 'facecolor'.
# This design should probably be revisited as it increases
# complexity.
facecolor = kw.get('color', None)
# Throw out 'color' as it is now handled as a facecolor
default_dict.pop('color', None)
# To get other properties set from the cycler
# modify the kwargs dictionary.
self._setdefaults(default_dict, kwargs)
seg = mpatches.Polygon(np.column_stack((x, y)),
facecolor=facecolor,
fill=kwargs.get('fill', True),
closed=kw['closed'])
seg.set(**kwargs)
return seg, kwargs
def _plot_args(self, axes, tup, kwargs, *,
return_kwargs=False, ambiguous_fmt_datakey=False):
"""
Process the arguments of ``plot([x], y, [fmt], **kwargs)`` calls.
This processes a single set of ([x], y, [fmt]) parameters; i.e. for
``plot(x, y, x2, y2)`` it will be called twice. Once for (x, y) and
once for (x2, y2).
x and y may be 2D and thus can still represent multiple datasets.
For multiple datasets, if the keyword argument *label* is a list, this
will unpack the list and assign the individual labels to the datasets.
Parameters
----------
tup : tuple
A tuple of the positional parameters. This can be one of
- (y,)
- (x, y)
- (y, fmt)
- (x, y, fmt)
kwargs : dict
The keyword arguments passed to ``plot()``.
return_kwargs : bool
Whether to also return the effective keyword arguments after label
unpacking as well.
ambiguous_fmt_datakey : bool
Whether the format string in *tup* could also have been a
misspelled data key.
Returns
-------
result
If *return_kwargs* is false, a list of Artists representing the
dataset(s).
If *return_kwargs* is true, a list of (Artist, effective_kwargs)
representing the dataset(s). See *return_kwargs*.
The Artist is either `.Line2D` (if called from ``plot()``) or
`.Polygon` otherwise.
"""
if len(tup) > 1 and isinstance(tup[-1], str):
# xy is tup with fmt stripped (could still be (y,) only)
*xy, fmt = tup
linestyle, marker, color = _process_plot_format(
fmt, ambiguous_fmt_datakey=ambiguous_fmt_datakey)
elif len(tup) == 3:
raise ValueError('third arg must be a format string')
else:
xy = tup
linestyle, marker, color = None, None, None
# Don't allow any None value; these would be up-converted to one
# element array of None which causes problems downstream.
if any(v is None for v in tup):
raise ValueError("x, y, and format string must not be None")
kw = {}
for prop_name, val in zip(('linestyle', 'marker', 'color'),
(linestyle, marker, color)):
if val is not None:
# check for conflicts between fmt and kwargs
if (fmt.lower() != 'none'
and prop_name in kwargs
and val != 'None'):
# Technically ``plot(x, y, 'o', ls='--')`` is a conflict
# because 'o' implicitly unsets the linestyle
# (linestyle='None').
# We'll gracefully not warn in this case because an
# explicit set via kwargs can be seen as intention to
# override an implicit unset.
# Note: We don't val.lower() != 'none' because val is not
# necessarily a string (can be a tuple for colors). This
# is safe, because *val* comes from _process_plot_format()
# which only returns 'None'.
_api.warn_external(
f"{prop_name} is redundantly defined by the "
f"'{prop_name}' keyword argument and the fmt string "
f'"{fmt}" (-> {prop_name}={val!r}). The keyword '
f"argument will take precedence.")
kw[prop_name] = val
if len(xy) == 2:
x = _check_1d(xy[0])
y = _check_1d(xy[1])
else:
x, y = index_of(xy[-1])
if axes.xaxis is not None:
axes.xaxis.update_units(x)
if axes.yaxis is not None:
axes.yaxis.update_units(y)
if x.shape[0] != y.shape[0]:
raise ValueError(f"x and y must have same first dimension, but "
f"have shapes {x.shape} and {y.shape}")
if x.ndim > 2 or y.ndim > 2:
raise ValueError(f"x and y can be no greater than 2D, but have "
f"shapes {x.shape} and {y.shape}")
if x.ndim == 1:
x = x[:, np.newaxis]
if y.ndim == 1:
y = y[:, np.newaxis]
if self.command == 'plot':
make_artist = self._makeline
else:
kw['closed'] = kwargs.get('closed', True)
make_artist = self._makefill
ncx, ncy = x.shape[1], y.shape[1]
if ncx > 1 and ncy > 1 and ncx != ncy:
raise ValueError(f"x has {ncx} columns but y has {ncy} columns")
if ncx == 0 or ncy == 0:
return []
label = kwargs.get('label')
n_datasets = max(ncx, ncy)
if n_datasets > 1 and not cbook.is_scalar_or_string(label):
if len(label) != n_datasets:
raise ValueError(f"label must be scalar or have the same "
f"length as the input data, but found "
f"{len(label)} for {n_datasets} datasets.")
labels = label
else:
labels = [label] * n_datasets
result = (make_artist(axes, x[:, j % ncx], y[:, j % ncy], kw,
{**kwargs, 'label': label})
for j, label in enumerate(labels))
if return_kwargs:
return list(result)
else:
return [l[0] for l in result]
@_api.define_aliases({"facecolor": ["fc"]})
class _AxesBase(martist.Artist):
name = "rectilinear"
# axis names are the prefixes for the attributes that contain the
# respective axis; e.g. 'x' <-> self.xaxis, containing an XAxis.
# Note that PolarAxes uses these attributes as well, so that we have
# 'x' <-> self.xaxis, containing a ThetaAxis. In particular we do not
# have 'theta' in _axis_names.
# In practice, this is ('x', 'y') for all 2D Axes and ('x', 'y', 'z')
# for Axes3D.
_axis_names = ("x", "y")
_shared_axes = {name: cbook.Grouper() for name in _axis_names}
_twinned_axes = cbook.Grouper()
_subclass_uses_cla = False
@property
def _axis_map(self):
"""A mapping of axis names, e.g. 'x', to `Axis` instances."""
return {name: getattr(self, f"{name}axis")
for name in self._axis_names}
def __str__(self):
return "{0}({1[0]:g},{1[1]:g};{1[2]:g}x{1[3]:g})".format(
type(self).__name__, self._position.bounds)
def __init__(self, fig,
*args,
facecolor=None, # defaults to rc axes.facecolor
frameon=True,
sharex=None, # use Axes instance's xaxis info
sharey=None, # use Axes instance's yaxis info
label='',
xscale=None,
yscale=None,
box_aspect=None,
**kwargs
):
"""
Build an Axes in a figure.
Parameters
----------
fig : `~matplotlib.figure.Figure`
The Axes is built in the `.Figure` *fig*.
*args
``*args`` can be a single ``(left, bottom, width, height)``
rectangle or a single `.Bbox`. This specifies the rectangle (in
figure coordinates) where the Axes is positioned.
``*args`` can also consist of three numbers or a single three-digit
number; in the latter case, the digits are considered as
independent numbers. The numbers are interpreted as ``(nrows,
ncols, index)``: ``(nrows, ncols)`` specifies the size of an array
of subplots, and ``index`` is the 1-based index of the subplot
being created. Finally, ``*args`` can also directly be a
`.SubplotSpec` instance.
sharex, sharey : `~matplotlib.axes.Axes`, optional
The x- or y-`~.matplotlib.axis` is shared with the x- or y-axis in
the input `~.axes.Axes`.
frameon : bool, default: True
Whether the Axes frame is visible.
box_aspect : float, optional
Set a fixed aspect for the Axes box, i.e. the ratio of height to
width. See `~.axes.Axes.set_box_aspect` for details.
**kwargs
Other optional keyword arguments:
%(Axes:kwdoc)s
Returns
-------
`~.axes.Axes`
The new `~.axes.Axes` object.
"""
super().__init__()
if "rect" in kwargs:
if args:
raise TypeError(
"'rect' cannot be used together with positional arguments")
rect = kwargs.pop("rect")
_api.check_isinstance((mtransforms.Bbox, Iterable), rect=rect)
args = (rect,)
subplotspec = None
if len(args) == 1 and isinstance(args[0], mtransforms.Bbox):
self._position = args[0]
elif len(args) == 1 and np.iterable(args[0]):
self._position = mtransforms.Bbox.from_bounds(*args[0])
else:
self._position = self._originalPosition = mtransforms.Bbox.unit()
subplotspec = SubplotSpec._from_subplot_args(fig, args)
if self._position.width < 0 or self._position.height < 0:
raise ValueError('Width and height specified must be non-negative')
self._originalPosition = self._position.frozen()
self.axes = self
self._aspect = 'auto'
self._adjustable = 'box'
self._anchor = 'C'
self._stale_viewlims = {name: False for name in self._axis_names}
self._sharex = sharex
self._sharey = sharey
self.set_label(label)
self.set_figure(fig)
# The subplotspec needs to be set after the figure (so that
# figure-level subplotpars are taken into account), but the figure
# needs to be set after self._position is initialized.
if subplotspec:
self.set_subplotspec(subplotspec)
else:
self._subplotspec = None
self.set_box_aspect(box_aspect)
self._axes_locator = None # Optionally set via update(kwargs).
self._children = []
# placeholder for any colorbars added that use this Axes.
# (see colorbar.py):
self._colorbars = []
self.spines = mspines.Spines.from_dict(self._gen_axes_spines())
# this call may differ for non-sep axes, e.g., polar
self._init_axis()
if facecolor is None:
facecolor = mpl.rcParams['axes.facecolor']
self._facecolor = facecolor
self._frameon = frameon
self.set_axisbelow(mpl.rcParams['axes.axisbelow'])
self._rasterization_zorder = None
self.clear()
# funcs used to format x and y - fall back on major formatters
self.fmt_xdata = None
self.fmt_ydata = None
self.set_navigate(True)
self.set_navigate_mode(None)
if xscale:
self.set_xscale(xscale)
if yscale:
self.set_yscale(yscale)
self._internal_update(kwargs)
for name, axis in self._axis_map.items():
axis.callbacks._connect_picklable(
'units', self._unit_change_handler(name))
rcParams = mpl.rcParams
self.tick_params(
top=rcParams['xtick.top'] and rcParams['xtick.minor.top'],
bottom=rcParams['xtick.bottom'] and rcParams['xtick.minor.bottom'],
labeltop=(rcParams['xtick.labeltop'] and
rcParams['xtick.minor.top']),
labelbottom=(rcParams['xtick.labelbottom'] and
rcParams['xtick.minor.bottom']),
left=rcParams['ytick.left'] and rcParams['ytick.minor.left'],
right=rcParams['ytick.right'] and rcParams['ytick.minor.right'],
labelleft=(rcParams['ytick.labelleft'] and
rcParams['ytick.minor.left']),
labelright=(rcParams['ytick.labelright'] and
rcParams['ytick.minor.right']),
which='minor')
self.tick_params(
top=rcParams['xtick.top'] and rcParams['xtick.major.top'],
bottom=rcParams['xtick.bottom'] and rcParams['xtick.major.bottom'],
labeltop=(rcParams['xtick.labeltop'] and
rcParams['xtick.major.top']),
labelbottom=(rcParams['xtick.labelbottom'] and
rcParams['xtick.major.bottom']),
left=rcParams['ytick.left'] and rcParams['ytick.major.left'],
right=rcParams['ytick.right'] and rcParams['ytick.major.right'],
labelleft=(rcParams['ytick.labelleft'] and
rcParams['ytick.major.left']),
labelright=(rcParams['ytick.labelright'] and
rcParams['ytick.major.right']),
which='major')
def __init_subclass__(cls, **kwargs):
parent_uses_cla = super(cls, cls)._subclass_uses_cla
if 'cla' in cls.__dict__:
_api.warn_deprecated(
'3.6',
pending=True,
message=f'Overriding `Axes.cla` in {cls.__qualname__} is '
'pending deprecation in %(since)s and will be fully '
'deprecated in favor of `Axes.clear` in the future. '
'Please report '
f'this to the {cls.__module__!r} author.')
cls._subclass_uses_cla = 'cla' in cls.__dict__ or parent_uses_cla
super().__init_subclass__(**kwargs)
def __getstate__(self):
state = super().__getstate__()
# Prune the sharing & twinning info to only contain the current group.
state["_shared_axes"] = {
name: self._shared_axes[name].get_siblings(self)
for name in self._axis_names if self in self._shared_axes[name]}
state["_twinned_axes"] = (self._twinned_axes.get_siblings(self)
if self in self._twinned_axes else None)
return state
def __setstate__(self, state):
# Merge the grouping info back into the global groupers.
shared_axes = state.pop("_shared_axes")
for name, shared_siblings in shared_axes.items():
self._shared_axes[name].join(*shared_siblings)
twinned_siblings = state.pop("_twinned_axes")
if twinned_siblings:
self._twinned_axes.join(*twinned_siblings)
self.__dict__ = state
self._stale = True
def __repr__(self):
fields = []
if self.get_label():
fields += [f"label={self.get_label()!r}"]
if hasattr(self, "get_title"):
titles = {}
for k in ["left", "center", "right"]:
title = self.get_title(loc=k)
if title:
titles[k] = title
if titles:
fields += [f"title={titles}"]
for name, axis in self._axis_map.items():
if axis.get_label() and axis.get_label().get_text():
fields += [f"{name}label={axis.get_label().get_text()!r}"]
return f"<{self.__class__.__name__}: " + ", ".join(fields) + ">"
def get_subplotspec(self):
"""Return the `.SubplotSpec` associated with the subplot, or None."""
return self._subplotspec
def set_subplotspec(self, subplotspec):
"""Set the `.SubplotSpec`. associated with the subplot."""
self._subplotspec = subplotspec
self._set_position(subplotspec.get_position(self.figure))
def get_gridspec(self):
"""Return the `.GridSpec` associated with the subplot, or None."""
return self._subplotspec.get_gridspec() if self._subplotspec else None
def get_window_extent(self, renderer=None):
"""
Return the Axes bounding box in display space.
This bounding box does not include the spines, ticks, ticklabels,
or other labels. For a bounding box including these elements use
`~matplotlib.axes.Axes.get_tightbbox`.
See Also
--------
matplotlib.axes.Axes.get_tightbbox
matplotlib.axis.Axis.get_tightbbox
matplotlib.spines.Spine.get_window_extent
"""
return self.bbox
def _init_axis(self):
# This is moved out of __init__ because non-separable axes don't use it
self.xaxis = maxis.XAxis(self, clear=False)
self.spines.bottom.register_axis(self.xaxis)
self.spines.top.register_axis(self.xaxis)
self.yaxis = maxis.YAxis(self, clear=False)
self.spines.left.register_axis(self.yaxis)
self.spines.right.register_axis(self.yaxis)
def set_figure(self, fig):
# docstring inherited
super().set_figure(fig)
self.bbox = mtransforms.TransformedBbox(self._position,
fig.transSubfigure)
# these will be updated later as data is added
self.dataLim = mtransforms.Bbox.null()
self._viewLim = mtransforms.Bbox.unit()
self.transScale = mtransforms.TransformWrapper(
mtransforms.IdentityTransform())
self._set_lim_and_transforms()
def _unstale_viewLim(self):
# We should arrange to store this information once per share-group
# instead of on every axis.
need_scale = {
name: any(ax._stale_viewlims[name]
for ax in self._shared_axes[name].get_siblings(self))
for name in self._axis_names}
if any(need_scale.values()):
for name in need_scale:
for ax in self._shared_axes[name].get_siblings(self):
ax._stale_viewlims[name] = False
self.autoscale_view(**{f"scale{name}": scale
for name, scale in need_scale.items()})
@property
def viewLim(self):
self._unstale_viewLim()
return self._viewLim
def _request_autoscale_view(self, axis="all", tight=None):
"""
Mark a single axis, or all of them, as stale wrt. autoscaling.
No computation is performed until the next autoscaling; thus, separate
calls to control individual axises incur negligible performance cost.
Parameters
----------
axis : str, default: "all"
Either an element of ``self._axis_names``, or "all".
tight : bool or None, default: None
"""
axis_names = _api.check_getitem(
{**{k: [k] for k in self._axis_names}, "all": self._axis_names},
axis=axis)
for name in axis_names:
self._stale_viewlims[name] = True
if tight is not None:
self._tight = tight
def _set_lim_and_transforms(self):
"""
Set the *_xaxis_transform*, *_yaxis_transform*, *transScale*,
*transData*, *transLimits* and *transAxes* transformations.
.. note::
This method is primarily used by rectilinear projections of the
`~matplotlib.axes.Axes` class, and is meant to be overridden by
new kinds of projection Axes that need different transformations
and limits. (See `~matplotlib.projections.polar.PolarAxes` for an
example.)
"""
self.transAxes = mtransforms.BboxTransformTo(self.bbox)
# Transforms the x and y axis separately by a scale factor.
# It is assumed that this part will have non-linear components
# (e.g., for a log scale).
self.transScale = mtransforms.TransformWrapper(
mtransforms.IdentityTransform())
# An affine transformation on the data, generally to limit the
# range of the axes
self.transLimits = mtransforms.BboxTransformFrom(
mtransforms.TransformedBbox(self._viewLim, self.transScale))
# The parentheses are important for efficiency here -- they
# group the last two (which are usually affines) separately
# from the first (which, with log-scaling can be non-affine).
self.transData = self.transScale + (self.transLimits + self.transAxes)
self._xaxis_transform = mtransforms.blended_transform_factory(
self.transData, self.transAxes)
self._yaxis_transform = mtransforms.blended_transform_factory(
self.transAxes, self.transData)
def get_xaxis_transform(self, which='grid'):
"""
Get the transformation used for drawing x-axis labels, ticks
and gridlines. The x-direction is in data coordinates and the
y-direction is in axis coordinates.
.. note::
This transformation is primarily used by the
`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
Parameters
----------
which : {'grid', 'tick1', 'tick2'}
"""
if which == 'grid':
return self._xaxis_transform
elif which == 'tick1':
# for cartesian projection, this is bottom spine
return self.spines.bottom.get_spine_transform()
elif which == 'tick2':
# for cartesian projection, this is top spine
return self.spines.top.get_spine_transform()
else:
raise ValueError(f'unknown value for which: {which!r}')
def get_xaxis_text1_transform(self, pad_points):
"""
Returns
-------
transform : Transform
The transform used for drawing x-axis labels, which will add
*pad_points* of padding (in points) between the axis and the label.
The x-direction is in data coordinates and the y-direction is in
axis coordinates
valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
The text vertical alignment.
halign : {'center', 'left', 'right'}
The text horizontal alignment.
Notes
-----
This transformation is primarily used by the `~matplotlib.axis.Axis`
class, and is meant to be overridden by new kinds of projections that
may need to place axis elements in different locations.
"""
labels_align = mpl.rcParams["xtick.alignment"]
return (self.get_xaxis_transform(which='tick1') +
mtransforms.ScaledTranslation(0, -1 * pad_points / 72,
self.figure.dpi_scale_trans),
"top", labels_align)
def get_xaxis_text2_transform(self, pad_points):
"""
Returns
-------
transform : Transform
The transform used for drawing secondary x-axis labels, which will
add *pad_points* of padding (in points) between the axis and the
label. The x-direction is in data coordinates and the y-direction
is in axis coordinates
valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
The text vertical alignment.
halign : {'center', 'left', 'right'}
The text horizontal alignment.
Notes
-----
This transformation is primarily used by the `~matplotlib.axis.Axis`
class, and is meant to be overridden by new kinds of projections that
may need to place axis elements in different locations.
"""
labels_align = mpl.rcParams["xtick.alignment"]
return (self.get_xaxis_transform(which='tick2') +
mtransforms.ScaledTranslation(0, pad_points / 72,
self.figure.dpi_scale_trans),
"bottom", labels_align)
def get_yaxis_transform(self, which='grid'):
"""
Get the transformation used for drawing y-axis labels, ticks
and gridlines. The x-direction is in axis coordinates and the
y-direction is in data coordinates.
.. note::
This transformation is primarily used by the
`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.