FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
matplotlib/lib/matplotlib/figure.py at v3.11.2 · matplotlib/matplotlib · GitHub
matplotlib
/
matplotlib
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
8.5k
Star
23.3k
Code
Issues
1.1k
Pull requests
438
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
figure.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
3809 lines (3148 loc) · 141 KB
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
figure.py
Copy path
File metadata and controls
3809 lines (3148 loc) · 141 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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.
Figures are typically created using pyplot methods `~.pyplot.figure`,
`~.pyplot.subplots`, and `~.pyplot.subplot_mosaic`.
.. plot::
:include-source:
fig, ax = plt.subplots(figsize=(2, 2), facecolor='lightskyblue',
layout='constrained')
fig.suptitle('Figure')
ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium')
Some situations call for directly instantiating a `~.figure.Figure` class,
usually inside an application of some sort (see :ref:`user_interfaces` for a
list of examples) . More information about Figures can be found at
:ref:`figure-intro`.
"""
from
contextlib
import
ExitStack
import
inspect
import
itertools
import
functools
import
logging
from
numbers
import
Integral
import
threading
import
numpy
as
np
import
matplotlib
as
mpl
from
matplotlib
import
_blocking_input
,
backend_bases
,
_docstring
,
projections
from
matplotlib
.
artist
import
(
Artist
,
allow_rasterization
,
_finalize_rasterization
)
from
matplotlib
.
backend_bases
import
(
DrawEvent
,
FigureCanvasBase
,
NonGuiException
,
MouseButton
,
_get_renderer
)
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
from
matplotlib
.
gridspec
import
GridSpec
,
SubplotParams
from
matplotlib
.
layout_engine
import
(
ConstrainedLayoutEngine
,
TightLayoutEngine
,
LayoutEngine
,
PlaceHolderLayoutEngine
)
import
matplotlib
.
legend
as
mlegend
from
matplotlib
.
patches
import
Rectangle
from
matplotlib
.
text
import
Text
from
matplotlib
.
transforms
import
(
Affine2D
,
Bbox
,
BboxTransformTo
,
TransformedBbox
)
_log
=
logging
.
getLogger
(
__name__
)
def
_stale_figure_callback
(
self
,
val
):
if
(
fig
:=
self
.
get_figure
(
root
=
False
))
is
not
None
:
fig
.
stale
=
val
class
_AxesStack
:
"""
Helper class to track Axes in a figure.
Axes are tracked both in the order in which they have been added
(``self._axes`` insertion/iteration order) and in the separate "gca" stack
(which is the index to which they map in the ``self._axes`` dict).
"""
def
__init__
(
self
):
self
.
_axes
=
{}
# Mapping of Axes to "gca" order.
self
.
_counter
=
itertools
.
count
()
def
as_list
(
self
):
"""List the Axes that have been added to the figure."""
return
[
*
self
.
_axes
]
# This relies on dict preserving order.
def
remove
(
self
,
a
):
"""Remove the Axes from the stack."""
self
.
_axes
.
pop
(
a
)
def
bubble
(
self
,
a
):
"""Move an Axes, which must already exist in the stack, to the top."""
if
a
not
in
self
.
_axes
:
raise
ValueError
(
"Axes has not been added yet"
)
self
.
_axes
[
a
]
=
next
(
self
.
_counter
)
def
add
(
self
,
a
):
"""Add an Axes to the stack, ignoring it if already present."""
if
a
not
in
self
.
_axes
:
self
.
_axes
[
a
]
=
next
(
self
.
_counter
)
def
current
(
self
):
"""Return the active Axes, or None if the stack is empty."""
return
max
(
self
.
_axes
,
key
=
self
.
_axes
.
__getitem__
,
default
=
None
)
def
__getstate__
(
self
):
return
{
**
vars
(
self
),
"_counter"
:
max
(
self
.
_axes
.
values
(),
default
=
0
)
}
def
__setstate__
(
self
,
state
):
next_counter
=
state
.
pop
(
'_counter'
)
vars
(
self
).
update
(
state
)
self
.
_counter
=
itertools
.
count
(
next_counter
)
class
FigureBase
(
Artist
):
"""
Base class for `.Figure` and `.SubFigure` containing the methods that add
artists to the figure or subfigure, create Axes, etc.
"""
def
__init__
(
self
,
**
kwargs
):
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
# groupers to keep track of x, y labels and title we want to align.
# see self.align_xlabels, self.align_ylabels,
# self.align_titles, and axis._get_tick_boxes_siblings
self
.
_align_label_groups
=
{
"x"
:
cbook
.
Grouper
(),
"y"
:
cbook
.
Grouper
(),
"title"
:
cbook
.
Grouper
()
}
self
.
_localaxes
=
[]
# track all Axes
self
.
artists
=
[]
self
.
lines
=
[]
self
.
patches
=
[]
self
.
texts
=
[]
self
.
images
=
[]
self
.
legends
=
[]
self
.
subfigs
=
[]
self
.
stale
=
True
self
.
suppressComposite
=
None
self
.
set
(
**
kwargs
)
def
_get_draw_artists
(
self
,
renderer
):
"""Also runs apply_aspect"""
artists
=
self
.
get_children
()
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
:
locator
=
ax
.
get_axes_locator
()
ax
.
apply_aspect
(
locator
(
ax
,
renderer
)
if
locator
else
None
)
for
child
in
ax
.
get_children
():
if
hasattr
(
child
,
'apply_aspect'
):
locator
=
child
.
get_axes_locator
()
child
.
apply_aspect
(
locator
(
child
,
renderer
)
if
locator
else
None
)
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.
"""
_api
.
check_in_list
([
'major'
,
'minor'
,
'both'
],
which
=
which
)
axes
=
[
ax
for
ax
in
self
.
axes
if
ax
.
_label
!=
'<colorbar>'
]
allsubplots
=
all
(
ax
.
get_subplotspec
()
for
ax
in
axes
)
if
len
(
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
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
(
''
)
engine
=
self
.
get_layout_engine
()
if
allsubplots
and
(
engine
is
None
or
engine
.
adjust_compatible
):
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
,
*
self
.
lines
,
*
self
.
patches
,
*
self
.
texts
,
*
self
.
images
,
*
self
.
legends
,
*
self
.
subfigs
]
def
get_figure
(
self
,
root
=
None
):
"""
Return the `.Figure` or `.SubFigure` instance the (Sub)Figure belongs to.
Parameters
----------
root : bool, default=True
If False, return the (Sub)Figure this artist is on. If True,
return the root Figure for a nested tree of SubFigures.
.. deprecated:: 3.10
From version 3.12 *root* will default to False.
"""
if
self
.
_root_figure
is
self
:
# Top level Figure
return
self
if
self
.
_parent
is
self
.
_root_figure
:
# Return early to prevent the deprecation warning when *root* does not
# matter
return
self
.
_parent
if
root
is
None
:
# When deprecation expires, consider removing the docstring and just
# inheriting the one from Artist.
message
=
(
'From Matplotlib 3.12 SubFigure.get_figure will by default '
'return the direct parent figure, which may be a SubFigure. '
'To suppress this warning, pass the root parameter. Pass '
'`True` to maintain the old behavior and `False` to opt-in to '
'the future behavior.'
)
_api
.
warn_deprecated
(
'3.10'
,
message
=
message
)
root
=
True
if
root
:
return
self
.
_root_figure
return
self
.
_parent
def
set_figure
(
self
,
fig
):
"""
.. deprecated:: 3.10
Currently this method will raise an exception if *fig* is anything other
than the root `.Figure` this (Sub)Figure is on. In future it will always
raise an exception.
"""
no_switch
=
(
"The parent and root figures of a (Sub)Figure are set at "
"instantiation and cannot be changed."
)
if
fig
is
self
.
_root_figure
:
_api
.
warn_deprecated
(
"3.10"
,
message
=
(
f"
{
no_switch
}
From Matplotlib 3.12 this operation will raise "
"an exception."
))
return
raise
ValueError
(
no_switch
)
figure
=
property
(
functools
.
partial
(
get_figure
,
root
=
True
),
set_figure
,
doc
=
(
"The root `Figure`. To get the parent of a `SubFigure`, "
"use the `get_figure` method."
))
def
contains
(
self
,
mouseevent
):
"""
Test whether the mouse event occurred on the figure.
Returns
-------
bool, {}
"""
if
self
.
_different_canvas
(
mouseevent
):
return
False
, {}
inside
=
self
.
bbox
.
contains
(
mouseevent
.
x
,
mouseevent
.
y
)
return
inside
, {}
def
get_window_extent
(
self
,
renderer
=
None
):
# docstring inherited
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.%(rc)ssize`
The font size of the text. See `.Text.set_size` for possible
values.
fontweight, weight : default: :rc:`figure.%(rc)sweight`
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.%(rc)ssize` and
:rc:`figure.%(rc)sweight` are ignored in this case.
**kwargs
Additional kwargs are `matplotlib.text.Text` properties.
"""
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'
]
kwargs
=
cbook
.
normalize_kwargs
(
kwargs
,
Text
)
kwargs
.
setdefault
(
'horizontalalignment'
,
info
[
'ha'
])
kwargs
.
setdefault
(
'verticalalignment'
,
info
[
'va'
])
kwargs
.
setdefault
(
'rotation'
,
info
[
'rotation'
])
if
'fontproperties'
not
in
kwargs
:
kwargs
.
setdefault
(
'fontsize'
,
mpl
.
rcParams
[
info
[
'size'
]])
kwargs
.
setdefault
(
'fontweight'
,
mpl
.
rcParams
[
info
[
'weight'
]])
suplab
=
getattr
(
self
,
info
[
'name'
])
if
suplab
is
not
None
:
suplab
.
set_text
(
t
)
suplab
.
set_position
((
x
,
y
))
suplab
.
set
(
**
kwargs
)
else
:
suplab
=
self
.
text
(
x
,
y
,
t
,
**
kwargs
)
setattr
(
self
,
info
[
'name'
],
suplab
)
suplab
.
_remove_method
=
functools
.
partial
(
self
.
_remove_suplabel
,
name
=
info
[
'name'
])
suplab
.
_autopos
=
autopos
self
.
stale
=
True
return
suplab
def
_remove_suplabel
(
self
,
label
,
name
):
self
.
texts
.
remove
(
label
)
setattr
(
self
,
name
,
None
)
@
_docstring
.
Substitution
(
x0
=
0.5
,
y0
=
0.98
,
name
=
'super title'
,
ha
=
'center'
,
va
=
'top'
,
rc
=
'title'
)
@
_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
,
'size'
:
'figure.titlesize'
,
'weight'
:
'figure.titleweight'
}
return
self
.
_suplabels
(
t
,
info
,
**
kwargs
)
def
get_suptitle
(
self
):
"""Return the suptitle as string or an empty string if not set."""
text_obj
=
self
.
_suptitle
return
""
if
text_obj
is
None
else
text_obj
.
get_text
()
@
_docstring
.
Substitution
(
x0
=
0.5
,
y0
=
0.01
,
name
=
'super xlabel'
,
ha
=
'center'
,
va
=
'bottom'
,
rc
=
'label'
)
@
_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
,
'size'
:
'figure.labelsize'
,
'weight'
:
'figure.labelweight'
}
return
self
.
_suplabels
(
t
,
info
,
**
kwargs
)
def
get_supxlabel
(
self
):
"""Return the supxlabel as string or an empty string if not set."""
text_obj
=
self
.
_supxlabel
return
""
if
text_obj
is
None
else
text_obj
.
get_text
()
@
_docstring
.
Substitution
(
x0
=
0.02
,
y0
=
0.5
,
name
=
'super ylabel'
,
ha
=
'left'
,
va
=
'center'
,
rc
=
'label'
)
@
_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'
,
'size'
:
'figure.labelsize'
,
'weight'
:
'figure.labelweight'
}
return
self
.
_suplabels
(
t
,
info
,
**
kwargs
)
def
get_supylabel
(
self
):
"""Return the supylabel as string or an empty string if not set."""
text_obj
=
self
.
_supylabel
return
""
if
text_obj
is
None
else
text_obj
.
get_text
()
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 : :mpltype:`color`
"""
self
.
patch
.
set_edgecolor
(
color
)
def
set_facecolor
(
self
,
color
):
"""
Set the face color of the Figure rectangle.
Parameters
----------
color : :mpltype:`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.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
and
artist
.
get_clip_path
()
is
None
:
artist
.
set_clip_path
(
self
.
patch
)
self
.
stale
=
True
return
artist
@
_docstring
.
interpd
def
add_axes
(
self
,
*
args
,
**
kwargs
):
"""
Add an `~.axes.Axes` to the figure.
Call signatures::
add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters
----------
rect : tuple (left, bottom, width, height)
The dimensions (left, bottom, width, height) of the new
`~.axes.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 : `~matplotlib.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
:
raise
TypeError
(
"add_axes() missing 1 required positional argument: 'rect'"
)
elif
'rect'
in
kwargs
:
if
len
(
args
):
raise
TypeError
(
"add_axes() got multiple values for argument 'rect'"
)
args
=
(
kwargs
.
pop
(
'rect'
), )
if
len
(
args
)
!=
1
:
raise
_api
.
nargs_error
(
"add_axes"
,
1
,
len
(
args
))
if
isinstance
(
args
[
0
],
Axes
):
a
,
=
args
key
=
a
.
_projection_init
if
a
.
get_figure
(
root
=
False
)
is
not
self
:
raise
ValueError
(
"The Axes must have been created in the present figure"
)
else
:
rect
,
=
args
if
not
np
.
isfinite
(
rect
).
all
():
raise
ValueError
(
f'all entries in rect must be finite not
{
rect
}
'
)
projection_class
,
pkw
=
self
.
_process_projection_requirements
(
**
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
.
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 : `~matplotlib.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`
The Axes of the subplot. The returned Axes can actually be an
instance of a subclass, such as `.projections.polar.PolarAxes` for
polar projections.
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
_api
.
kwarg_error
(
"add_subplot"
,
"figure"
)
if
(
len
(
args
)
==
1
and
isinstance
(
args
[
0
],
mpl
.
axes
.
_base
.
_AxesBase
)
and
args
[
0
].
get_subplotspec
()):
ax
=
args
[
0
]
key
=
ax
.
_projection_init
if
ax
.
get_figure
(
root
=
False
)
is
not
self
:
raise
ValueError
(
"The Axes 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
(
**
kwargs
)
ax
=
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
)
if
ax
not
in
self
.
_localaxes
:
self
.
_localaxes
.
append
(
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
def
subplots
(
self
,
nrows
=
1
,
ncols
=
1
,
*
,
sharex
=
False
,
sharey
=
False
,
squeeze
=
True
,
width_ratios
=
None
,
height_ratios
=
None
,
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 x-axis (*sharex*) or y-axis (*sharey*):
- 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.
Note that it is not possible to unshare axes.
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.
width_ratios : array-like of length *ncols*, optional
Defines the relative widths of the columns. Each column gets a
relative width of ``width_ratios[i] / sum(width_ratios)``.
If not given, all columns will have the same width. Equivalent
to ``gridspec_kw={'width_ratios': [...]}``.
height_ratios : array-like of length *nrows*, optional
Defines the relative heights of the rows. Each row gets a
relative height of ``height_ratios[i] / sum(height_ratios)``.
If not given, all rows will have the same height. Equivalent
to ``gridspec_kw={'height_ratios': [...]}``.
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
fig = 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 an 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)
"""
gridspec_kw
=
dict
(
gridspec_kw
or
{})
if
height_ratios
is
not
None
:
if
'height_ratios'
in
gridspec_kw
:
raise
ValueError
(
"'height_ratios' must not be defined both as "
"parameter and as key in 'gridspec_kw'"
)
gridspec_kw
[
'height_ratios'
]
=
height_ratios
if
width_ratios
is
not
None
:
if
'width_ratios'
in
gridspec_kw
:
raise
ValueError
(
"'width_ratios' must not be defined both as "
"parameter and as key in 'gridspec_kw'"
)
gridspec_kw
[
'width_ratios'
]
=
width_ratios
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.
"""
self
.
_remove_axes
(
ax
,
owners
=
[
self
.
_axstack
,
self
.
_localaxes
])
def
_remove_axes
(
self
,
ax
,
owners
):
"""
Common helper for removal of standard Axes (via delaxes) and of child Axes.
Parameters
----------
ax : `~.AxesBase`
The Axes to remove.
owners
List of objects (list or _AxesStack) "owning" the Axes, from which the Axes
will be remove()d.
"""
for
owner
in
owners
:
owner
.
remove
(
ax
)
self
.
_axobservers
.
process
(
"_axes_change_event"
,
self
)
self
.
stale
=
True
self
.
_root_figure
.
canvas
.
release_mouse
(
ax
)
for
name
in
ax
.
_axis_names
:
# Break link between any shared Axes
grouper
=
ax
.
_shared_axes
[
name
]
siblings
=
grouper
.
get_siblings
(
ax
,
include_self
=
False
)
if
not
siblings
:
# Axes was not shared along this axis; we're done.
continue
grouper
.
remove
(
ax
)
# Formatters and locators may previously have been associated with the now
# removed axis. Update them to point to an axis still there (we can pick
# any of them, and use the first sibling).
remaining_axis
=
siblings
[
0
].
_axis_map
[
name
]
remaining_axis
.
get_major_formatter
().
set_axis
(
remaining_axis
)
remaining_axis
.
get_major_locator
().
set_axis
(
remaining_axis
)
remaining_axis
.
get_minor_formatter
().
set_axis
(
remaining_axis
)
remaining_axis
.
get_minor_locator
().
set_axis
(
remaining_axis
)
ax
.
_twinned_axes
.
remove
(
ax
)
# Break link between any twinned Axes.
def
clear
(
self
,
keep_observers
=
False
):
"""
Clear the figure.
Parameters
----------
keep_observers : bool, default: False
Set *keep_observers* to True if, for example,
a gui widget is tracking the Axes in the figure.
"""
self
.
suppressComposite
=
None
# first clear the Axes in any subfigures
for
subfig
in
self
.
subfigs
:
subfig
.
clear
(
keep_observers
=
keep_observers
)
self
.
subfigs
=
[]
for
ax
in
tuple
(
self
.
axes
):
# Iterate over the copy.
ax
.
clear
()
self
.
delaxes
(
ax
)
# Remove ax from self._axstack.
self
.
artists
=
[]
self
.
lines
=
[]
self
.
patches
=
[]
self
.
texts
=
[]
self
.
images
=
[]
self
.
legends
=
[]
self
.
subplotpars
.
reset
()
if
not
keep_observers
:
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL