forked from matplotlib/matplotlib
-
Notifications
You must be signed in to change notification settings - Fork 1
/
figure.py
3251 lines (2679 loc) · 116 KB
/
figure.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
"""
`matplotlib.figure` implements the following classes:
`Figure`
Top level `~matplotlib.artist.Artist`, which holds all plot elements.
Many methods are implemented in `FigureBase`.
`SubFigure`
A logical figure inside a figure, usually added to a figure (or parent
`SubFigure`) with `Figure.add_subfigure` or `Figure.subfigures` methods
(provisional API v3.4).
`SubplotParams`
Control the default spacing between subplots.
"""
import inspect
import logging
from numbers import Integral
import numpy as np
import matplotlib as mpl
from matplotlib import docstring, projections
from matplotlib import __version__ as _mpl_version
import matplotlib.artist as martist
from matplotlib.artist import (
Artist, allow_rasterization, _finalize_rasterization)
from matplotlib.backend_bases import (
FigureCanvasBase, NonGuiException, MouseButton)
import matplotlib._api as _api
import matplotlib.cbook as cbook
import matplotlib.colorbar as cbar
import matplotlib.image as mimage
from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput
from matplotlib.gridspec import GridSpec
import matplotlib.legend as mlegend
from matplotlib.patches import Rectangle
from matplotlib.text import Text
from matplotlib.transforms import (Affine2D, Bbox, BboxTransformTo,
TransformedBbox)
import matplotlib._layoutgrid as layoutgrid
_log = logging.getLogger(__name__)
def _stale_figure_callback(self, val):
if self.figure:
self.figure.stale = val
class _AxesStack(cbook.Stack):
"""
Specialization of Stack, to handle all tracking of Axes in a Figure.
This stack stores ``ind, axes`` pairs, where ``ind`` is a serial index
tracking the order in which axes were added.
AxesStack is a callable; calling it returns the current axes.
"""
def __init__(self):
super().__init__()
self._ind = 0
def as_list(self):
"""
Return a list of the Axes instances that have been added to the figure.
"""
return [a for i, a in sorted(self._elements)]
def _entry_from_axes(self, e):
return next(((ind, a) for ind, a in self._elements if a == e), None)
def remove(self, a):
"""Remove the axes from the stack."""
super().remove(self._entry_from_axes(a))
def bubble(self, a):
"""
Move the given axes, which must already exist in the stack, to the top.
"""
return super().bubble(self._entry_from_axes(a))
def add(self, a):
"""
Add Axes *a* to the stack.
If *a* is already on the stack, don't add it again.
"""
# All the error checking may be unnecessary; but this method
# is called so seldom that the overhead is negligible.
_api.check_isinstance(Axes, a=a)
if a in self:
return
self._ind += 1
super().push((self._ind, a))
def __call__(self):
"""
Return the active axes.
If no axes exists on the stack, then returns None.
"""
if not len(self._elements):
return None
else:
index, axes = self._elements[self._pos]
return axes
def __contains__(self, a):
return a in self.as_list()
class SubplotParams:
"""
A class to hold the parameters for a subplot.
"""
def __init__(self, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None):
"""
Defaults are given by :rc:`figure.subplot.[name]`.
Parameters
----------
left : float
The position of the left edge of the subplots,
as a fraction of the figure width.
right : float
The position of the right edge of the subplots,
as a fraction of the figure width.
bottom : float
The position of the bottom edge of the subplots,
as a fraction of the figure height.
top : float
The position of the top edge of the subplots,
as a fraction of the figure height.
wspace : float
The width of the padding between subplots,
as a fraction of the average Axes width.
hspace : float
The height of the padding between subplots,
as a fraction of the average Axes height.
"""
self.validate = True
for key in ["left", "bottom", "right", "top", "wspace", "hspace"]:
setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"])
self.update(left, bottom, right, top, wspace, hspace)
def update(self, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None):
"""
Update the dimensions of the passed parameters. *None* means unchanged.
"""
if self.validate:
if ((left if left is not None else self.left)
>= (right if right is not None else self.right)):
raise ValueError('left cannot be >= right')
if ((bottom if bottom is not None else self.bottom)
>= (top if top is not None else self.top)):
raise ValueError('bottom cannot be >= top')
if left is not None:
self.left = left
if right is not None:
self.right = right
if bottom is not None:
self.bottom = bottom
if top is not None:
self.top = top
if wspace is not None:
self.wspace = wspace
if hspace is not None:
self.hspace = hspace
class FigureBase(Artist):
"""
Base class for `.figure.Figure` and `.figure.SubFigure` containing the
methods that add artists to the figure or subfigure, create Axes, etc.
"""
def __init__(self):
super().__init__()
# remove the non-figure artist _axes property
# as it makes no sense for a figure to be _in_ an axes
# this is used by the property methods in the artist base class
# which are over-ridden in this class
del self._axes
self._suptitle = None
self._supxlabel = None
self._supylabel = None
# constrained_layout:
self._layoutgrid = None
# groupers to keep track of x and y labels we want to align.
# see self.align_xlabels and self.align_ylabels and
# axis._get_tick_boxes_siblings
self._align_label_groups = {"x": cbook.Grouper(), "y": cbook.Grouper()}
self.figure = self
# list of child gridspecs for this figure
self._gridspecs = []
self._localaxes = _AxesStack() # track all axes and current axes
self.artists = []
self.lines = []
self.patches = []
self.texts = []
self.images = []
self.legends = []
self.subfigs = []
self.stale = True
self.suppressComposite = None
def _get_draw_artists(self, renderer):
"""Also runs apply_aspect"""
artists = self.get_children()
for sfig in self.subfigs:
artists.remove(sfig)
childa = sfig.get_children()
for child in childa:
if child in artists:
artists.remove(child)
artists.remove(self.patch)
artists = sorted(
(artist for artist in artists if not artist.get_animated()),
key=lambda artist: artist.get_zorder())
for ax in self._localaxes.as_list():
locator = ax.get_axes_locator()
if locator:
pos = locator(ax, renderer)
ax.apply_aspect(pos)
else:
ax.apply_aspect()
for child in ax.get_children():
if hasattr(child, 'apply_aspect'):
locator = child.get_axes_locator()
if locator:
pos = locator(child, renderer)
child.apply_aspect(pos)
else:
child.apply_aspect()
return artists
def autofmt_xdate(
self, bottom=0.2, rotation=30, ha='right', which='major'):
"""
Date ticklabels often overlap, so it is useful to rotate them
and right align them. Also, a common use case is a number of
subplots with shared x-axis where the x-axis is date data. The
ticklabels are often long, and it helps to rotate them on the
bottom subplot and turn them off on other subplots, as well as
turn off xlabels.
Parameters
----------
bottom : float, default: 0.2
The bottom of the subplots for `subplots_adjust`.
rotation : float, default: 30 degrees
The rotation angle of the xtick labels in degrees.
ha : {'left', 'center', 'right'}, default: 'right'
The horizontal alignment of the xticklabels.
which : {'major', 'minor', 'both'}, default: 'major'
Selects which ticklabels to rotate.
"""
if which is None:
_api.warn_deprecated(
"3.3", message="Support for passing which=None to mean "
"which='major' is deprecated since %(since)s and will be "
"removed %(removal)s.")
allsubplots = all(hasattr(ax, 'get_subplotspec') for ax in self.axes)
if len(self.axes) == 1:
for label in self.axes[0].get_xticklabels(which=which):
label.set_ha(ha)
label.set_rotation(rotation)
else:
if allsubplots:
for ax in self.get_axes():
if ax.get_subplotspec().is_last_row():
for label in ax.get_xticklabels(which=which):
label.set_ha(ha)
label.set_rotation(rotation)
else:
for label in ax.get_xticklabels(which=which):
label.set_visible(False)
ax.set_xlabel('')
if allsubplots:
self.subplots_adjust(bottom=bottom)
self.stale = True
def get_children(self):
"""Get a list of artists contained in the figure."""
return [self.patch,
*self.artists,
*self._localaxes.as_list(),
*self.lines,
*self.patches,
*self.texts,
*self.images,
*self.legends,
*self.subfigs]
def contains(self, mouseevent):
"""
Test whether the mouse event occurred on the figure.
Returns
-------
bool, {}
"""
inside, info = self._default_contains(mouseevent, figure=self)
if inside is not None:
return inside, info
inside = self.bbox.contains(mouseevent.x, mouseevent.y)
return inside, {}
def get_window_extent(self, *args, **kwargs):
"""
Return the figure bounding box in display space. Arguments are ignored.
"""
return self.bbox
def _suplabels(self, t, info, **kwargs):
"""
Add a centered %(name)s to the figure.
Parameters
----------
t : str
The %(name)s text.
x : float, default: %(x0)s
The x location of the text in figure coordinates.
y : float, default: %(y0)s
The y location of the text in figure coordinates.
horizontalalignment, ha : {'center', 'left', 'right'}, default: %(ha)s
The horizontal alignment of the text relative to (*x*, *y*).
verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, \
default: %(va)s
The vertical alignment of the text relative to (*x*, *y*).
fontsize, size : default: :rc:`figure.titlesize`
The font size of the text. See `.Text.set_size` for possible
values.
fontweight, weight : default: :rc:`figure.titleweight`
The font weight of the text. See `.Text.set_weight` for possible
values.
Returns
-------
text
The `.Text` instance of the %(name)s.
Other Parameters
----------------
fontproperties : None or dict, optional
A dict of font properties. If *fontproperties* is given the
default values for font size and weight are taken from the
`.FontProperties` defaults. :rc:`figure.titlesize` and
:rc:`figure.titleweight` are ignored in this case.
**kwargs
Additional kwargs are `matplotlib.text.Text` properties.
"""
suplab = getattr(self, info['name'])
x = kwargs.pop('x', None)
y = kwargs.pop('y', None)
if info['name'] in ['_supxlabel', '_suptitle']:
autopos = y is None
elif info['name'] == '_supylabel':
autopos = x is None
if x is None:
x = info['x0']
if y is None:
y = info['y0']
if 'horizontalalignment' not in kwargs and 'ha' not in kwargs:
kwargs['horizontalalignment'] = info['ha']
if 'verticalalignment' not in kwargs and 'va' not in kwargs:
kwargs['verticalalignment'] = info['va']
if 'rotation' not in kwargs:
kwargs['rotation'] = info['rotation']
if 'fontproperties' not in kwargs:
if 'fontsize' not in kwargs and 'size' not in kwargs:
kwargs['size'] = mpl.rcParams['figure.titlesize']
if 'fontweight' not in kwargs and 'weight' not in kwargs:
kwargs['weight'] = mpl.rcParams['figure.titleweight']
sup = self.text(x, y, t, **kwargs)
if suplab is not None:
suplab.set_text(t)
suplab.set_position((x, y))
suplab.update_from(sup)
sup.remove()
else:
suplab = sup
suplab._autopos = autopos
setattr(self, info['name'], suplab)
self.stale = True
return suplab
@docstring.Substitution(x0=0.5, y0=0.98, name='suptitle', ha='center',
va='top')
@docstring.copy(_suplabels)
def suptitle(self, t, **kwargs):
# docstring from _suplabels...
info = {'name': '_suptitle', 'x0': 0.5, 'y0': 0.98,
'ha': 'center', 'va': 'top', 'rotation': 0}
return self._suplabels(t, info, **kwargs)
@docstring.Substitution(x0=0.5, y0=0.01, name='supxlabel', ha='center',
va='bottom')
@docstring.copy(_suplabels)
def supxlabel(self, t, **kwargs):
# docstring from _suplabels...
info = {'name': '_supxlabel', 'x0': 0.5, 'y0': 0.01,
'ha': 'center', 'va': 'bottom', 'rotation': 0}
return self._suplabels(t, info, **kwargs)
@docstring.Substitution(x0=0.02, y0=0.5, name='supylabel', ha='left',
va='center')
@docstring.copy(_suplabels)
def supylabel(self, t, **kwargs):
# docstring from _suplabels...
info = {'name': '_supylabel', 'x0': 0.02, 'y0': 0.5,
'ha': 'left', 'va': 'center', 'rotation': 'vertical',
'rotation_mode': 'anchor'}
return self._suplabels(t, info, **kwargs)
def get_edgecolor(self):
"""Get the edge color of the Figure rectangle."""
return self.patch.get_edgecolor()
def get_facecolor(self):
"""Get the face color of the Figure rectangle."""
return self.patch.get_facecolor()
def get_frameon(self):
"""
Return the figure's background patch visibility, i.e.
whether the figure background will be drawn. Equivalent to
``Figure.patch.get_visible()``.
"""
return self.patch.get_visible()
def set_linewidth(self, linewidth):
"""
Set the line width of the Figure rectangle.
Parameters
----------
linewidth : number
"""
self.patch.set_linewidth(linewidth)
def get_linewidth(self):
"""
Get the line width of the Figure rectangle.
"""
return self.patch.get_linewidth()
def set_edgecolor(self, color):
"""
Set the edge color of the Figure rectangle.
Parameters
----------
color : color
"""
self.patch.set_edgecolor(color)
def set_facecolor(self, color):
"""
Set the face color of the Figure rectangle.
Parameters
----------
color : color
"""
self.patch.set_facecolor(color)
def set_frameon(self, b):
"""
Set the figure's background patch visibility, i.e.
whether the figure background will be drawn. Equivalent to
``Figure.patch.set_visible()``.
Parameters
----------
b : bool
"""
self.patch.set_visible(b)
self.stale = True
frameon = property(get_frameon, set_frameon)
def add_artist(self, artist, clip=False):
"""
Add an `.Artist` to the figure.
Usually artists are added to Axes objects using `.Axes.add_artist`;
this method can be used in the rare cases where one needs to add
artists directly to the figure instead.
Parameters
----------
artist : `~matplotlib.artist.Artist`
The artist to add to the figure. If the added artist has no
transform previously set, its transform will be set to
``figure.transSubfigure``.
clip : bool, default: False
Whether the added artist should be clipped by the figure patch.
Returns
-------
`~matplotlib.artist.Artist`
The added artist.
"""
artist.set_figure(self)
self.artists.append(artist)
artist._remove_method = self.artists.remove
if not artist.is_transform_set():
artist.set_transform(self.transSubfigure)
if clip:
artist.set_clip_path(self.patch)
self.stale = True
return artist
@docstring.dedent_interpd
def add_axes(self, *args, **kwargs):
"""
Add an Axes to the figure.
Call signatures::
add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters
----------
rect : sequence of float
The dimensions [left, bottom, width, height] of the new Axes. All
quantities are in fractions of figure width and height.
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
The projection type of the `~.axes.Axes`. *str* is the name of
a custom projection, see `~matplotlib.projections`. The default
None results in a 'rectilinear' projection.
polar : bool, default: False
If True, equivalent to projection='polar'.
axes_class : subclass type of `~.axes.Axes`, optional
The `.axes.Axes` subclass that is instantiated. This parameter
is incompatible with *projection* and *polar*. See
:ref:`axisartist_users-guide-index` for examples.
sharex, sharey : `~.axes.Axes`, optional
Share the x or y `~matplotlib.axis` with sharex and/or sharey.
The axis will have the same limits, ticks, and scale as the axis
of the shared axes.
label : str
A label for the returned Axes.
Returns
-------
`~.axes.Axes`, or a subclass of `~.axes.Axes`
The returned axes class depends on the projection used. It is
`~.axes.Axes` if rectilinear projection is used and
`.projections.polar.PolarAxes` if polar projection is used.
Other Parameters
----------------
**kwargs
This method also takes the keyword arguments for
the returned Axes class. The keyword arguments for the
rectilinear Axes class `~.axes.Axes` can be found in
the following table but there might also be other keyword
arguments if another projection is used, see the actual Axes
class.
%(Axes_kwdoc)s
Notes
-----
In rare circumstances, `.add_axes` may be called with a single
argument, an Axes instance already created in the present figure but
not in the figure's list of Axes.
See Also
--------
.Figure.add_subplot
.pyplot.subplot
.pyplot.axes
.Figure.subplots
.pyplot.subplots
Examples
--------
Some simple examples::
rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax = fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax)
"""
if not len(args) and 'rect' not in kwargs:
_api.warn_deprecated(
"3.3",
message="Calling add_axes() without argument is "
"deprecated since %(since)s and will be removed %(removal)s. "
"You may want to use add_subplot() instead.")
return
elif 'rect' in kwargs:
if len(args):
raise TypeError(
"add_axes() got multiple values for argument 'rect'")
args = (kwargs.pop('rect'), )
if isinstance(args[0], Axes):
a = args[0]
key = a._projection_init
if a.get_figure() is not self:
raise ValueError(
"The Axes must have been created in the present figure")
else:
rect = args[0]
if not np.isfinite(rect).all():
raise ValueError('all entries in rect must be finite '
'not {}'.format(rect))
projection_class, pkw = self._process_projection_requirements(
*args, **kwargs)
# create the new axes using the axes class given
a = projection_class(self, rect, **pkw)
key = (projection_class, pkw)
return self._add_axes_internal(a, key)
@docstring.dedent_interpd
def add_subplot(self, *args, **kwargs):
"""
Add an `~.axes.Axes` to the figure as part of a subplot arrangement.
Call signatures::
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
Parameters
----------
*args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
The position of the subplot described by one of
- Three integers (*nrows*, *ncols*, *index*). The subplot will
take the *index* position on a grid with *nrows* rows and
*ncols* columns. *index* starts at 1 in the upper left corner
and increases to the right. *index* can also be a two-tuple
specifying the (*first*, *last*) indices (1-based, and including
*last*) of the subplot, e.g., ``fig.add_subplot(3, 1, (1, 2))``
makes a subplot that spans the upper 2/3 of the figure.
- A 3-digit integer. The digits are interpreted as if given
separately as three single-digit integers, i.e.
``fig.add_subplot(235)`` is the same as
``fig.add_subplot(2, 3, 5)``. Note that this can only be used
if there are no more than 9 subplots.
- A `.SubplotSpec`.
In rare circumstances, `.add_subplot` may be called with a single
argument, a subplot Axes instance already created in the
present figure but not in the figure's list of Axes.
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
The projection type of the subplot (`~.axes.Axes`). *str* is the
name of a custom projection, see `~matplotlib.projections`. The
default None results in a 'rectilinear' projection.
polar : bool, default: False
If True, equivalent to projection='polar'.
axes_class : subclass type of `~.axes.Axes`, optional
The `.axes.Axes` subclass that is instantiated. This parameter
is incompatible with *projection* and *polar*. See
:ref:`axisartist_users-guide-index` for examples.
sharex, sharey : `~.axes.Axes`, optional
Share the x or y `~matplotlib.axis` with sharex and/or sharey.
The axis will have the same limits, ticks, and scale as the axis
of the shared axes.
label : str
A label for the returned Axes.
Returns
-------
`.axes.SubplotBase`, or another subclass of `~.axes.Axes`
The Axes of the subplot. The returned Axes base class depends on
the projection used. It is `~.axes.Axes` if rectilinear projection
is used and `.projections.polar.PolarAxes` if polar projection
is used. The returned Axes is then a subplot subclass of the
base class.
Other Parameters
----------------
**kwargs
This method also takes the keyword arguments for the returned Axes
base class; except for the *figure* argument. The keyword arguments
for the rectilinear base class `~.axes.Axes` can be found in
the following table but there might also be other keyword
arguments if another projection is used.
%(Axes_kwdoc)s
See Also
--------
.Figure.add_axes
.pyplot.subplot
.pyplot.axes
.Figure.subplots
.pyplot.subplots
Examples
--------
::
fig = plt.figure()
fig.add_subplot(231)
ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general
fig.add_subplot(232, frameon=False) # subplot with no frame
fig.add_subplot(233, projection='polar') # polar subplot
fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1
fig.add_subplot(235, facecolor="red") # red subplot
ax1.remove() # delete ax1 from the figure
fig.add_subplot(ax1) # add ax1 back to the figure
"""
if 'figure' in kwargs:
# Axes itself allows for a 'figure' kwarg, but since we want to
# bind the created Axes to self, it is not allowed here.
raise TypeError(
"add_subplot() got an unexpected keyword argument 'figure'")
if len(args) == 1 and isinstance(args[0], SubplotBase):
ax = args[0]
key = ax._projection_init
if ax.get_figure() is not self:
raise ValueError("The Subplot must have been created in "
"the present figure")
else:
if not args:
args = (1, 1, 1)
# Normalize correct ijk values to (i, j, k) here so that
# add_subplot(211) == add_subplot(2, 1, 1). Invalid values will
# trigger errors later (via SubplotSpec._from_subplot_args).
if (len(args) == 1 and isinstance(args[0], Integral)
and 100 <= args[0] <= 999):
args = tuple(map(int, str(args[0])))
projection_class, pkw = self._process_projection_requirements(
*args, **kwargs)
ax = subplot_class_factory(projection_class)(self, *args, **pkw)
key = (projection_class, pkw)
return self._add_axes_internal(ax, key)
def _add_axes_internal(self, ax, key):
"""Private helper for `add_axes` and `add_subplot`."""
self._axstack.add(ax)
self._localaxes.add(ax)
self.sca(ax)
ax._remove_method = self.delaxes
# this is to support plt.subplot's re-selection logic
ax._projection_init = key
self.stale = True
ax.stale_callback = _stale_figure_callback
return ax
@_api.make_keyword_only("3.3", "sharex")
def subplots(self, nrows=1, ncols=1, sharex=False, sharey=False,
squeeze=True, subplot_kw=None, gridspec_kw=None):
"""
Add a set of subplots to this figure.
This utility wrapper makes it convenient to create common layouts of
subplots in a single call.
Parameters
----------
nrows, ncols : int, default: 1
Number of rows/columns of the subplot grid.
sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of properties among x (*sharex*) or y (*sharey*)
axes:
- True or 'all': x- or y-axis will be shared among all subplots.
- False or 'none': each subplot x- or y-axis will be independent.
- 'row': each subplot row will share an x- or y-axis.
- 'col': each subplot column will share an x- or y-axis.
When subplots have a shared x-axis along a column, only the x tick
labels of the bottom subplot are created. Similarly, when subplots
have a shared y-axis along a row, only the y tick labels of the
first column subplot are created. To later turn other subplots'
ticklabels on, use `~matplotlib.axes.Axes.tick_params`.
When subplots have a shared axis that has units, calling
`.Axis.set_units` will update each axis with the new units.
squeeze : bool, default: True
- If True, extra dimensions are squeezed out from the returned
array of Axes:
- if only one subplot is constructed (nrows=ncols=1), the
resulting single Axes object is returned as a scalar.
- for Nx1 or 1xM subplots, the returned object is a 1D numpy
object array of Axes objects.
- for NxM, subplots with N>1 and M>1 are returned as a 2D array.
- If False, no squeezing at all is done: the returned Axes object
is always a 2D array containing Axes instances, even if it ends
up being 1x1.
subplot_kw : dict, optional
Dict with keywords passed to the `.Figure.add_subplot` call used to
create each subplot.
gridspec_kw : dict, optional
Dict with keywords passed to the
`~matplotlib.gridspec.GridSpec` constructor used to create
the grid the subplots are placed on.
Returns
-------
`~.axes.Axes` or array of Axes
Either a single `~matplotlib.axes.Axes` object or an array of Axes
objects if more than one subplot was created. The dimensions of the
resulting array can be controlled with the *squeeze* keyword, see
above.
See Also
--------
.pyplot.subplots
.Figure.add_subplot
.pyplot.subplot
Examples
--------
::
# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create a figure
plt.figure()
# Create a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Create two subplots and unpack the output array immediately
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Create four polar Axes and access them through the returned array
axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
# Share a X axis with each column of subplots
fig.subplots(2, 2, sharex='col')
# Share a Y axis with each row of subplots
fig.subplots(2, 2, sharey='row')
# Share both X and Y axes with all subplots
fig.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
fig.subplots(2, 2, sharex=True, sharey=True)
"""
if gridspec_kw is None:
gridspec_kw = {}
gs = self.add_gridspec(nrows, ncols, figure=self, **gridspec_kw)
axs = gs.subplots(sharex=sharex, sharey=sharey, squeeze=squeeze,
subplot_kw=subplot_kw)
return axs
def delaxes(self, ax):
"""
Remove the `~.axes.Axes` *ax* from the figure; update the current Axes.
"""
def _reset_locators_and_formatters(axis):
# Set the formatters and locators to be associated with axis
# (where previously they may have been associated with another
# Axis instance)
#
# Because set_major_formatter() etc. force isDefault_* to be False,
# we have to manually check if the original formatter was a
# default and manually set isDefault_* if that was the case.
majfmt = axis.get_major_formatter()
isDefault = majfmt.axis.isDefault_majfmt
axis.set_major_formatter(majfmt)
if isDefault:
majfmt.axis.isDefault_majfmt = True
majloc = axis.get_major_locator()
isDefault = majloc.axis.isDefault_majloc
axis.set_major_locator(majloc)
if isDefault:
majloc.axis.isDefault_majloc = True
minfmt = axis.get_minor_formatter()
isDefault = majloc.axis.isDefault_minfmt
axis.set_minor_formatter(minfmt)
if isDefault:
minfmt.axis.isDefault_minfmt = True
minloc = axis.get_minor_locator()
isDefault = majloc.axis.isDefault_minloc
axis.set_minor_locator(minloc)
if isDefault:
minloc.axis.isDefault_minloc = True
def _break_share_link(ax, grouper):
siblings = grouper.get_siblings(ax)
if len(siblings) > 1:
grouper.remove(ax)
for last_ax in siblings:
if ax is not last_ax:
return last_ax
return None
self._axstack.remove(ax)
self._axobservers.process("_axes_change_event", self)
self.stale = True
self._localaxes.remove(ax)
last_ax = _break_share_link(ax, ax._shared_y_axes)
if last_ax is not None:
_reset_locators_and_formatters(last_ax.yaxis)
last_ax = _break_share_link(ax, ax._shared_x_axes)
if last_ax is not None:
_reset_locators_and_formatters(last_ax.xaxis)
# Note: in the docstring below, the newlines in the examples after the
# calls to legend() allow replacing it with figlegend() to generate the
# docstring of pyplot.figlegend.
@docstring.dedent_interpd
def legend(self, *args, **kwargs):
"""
Place a legend on the figure.
Call signatures::
legend()
legend(labels)
legend(handles, labels)
The call signatures correspond to these three different ways to use
this method:
**1. Automatic detection of elements to be shown in the legend**
The elements to be added to the legend are automatically determined,
when you do not pass in any extra arguments.
In this case, the labels are taken from the artist. You can specify
them either at artist creation or by calling the
:meth:`~.Artist.set_label` method on the artist::