FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
matplotlib/lib/matplotlib/pyplot.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
430
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
/
pyplot.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
4831 lines (4025 loc) · 152 KB
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
pyplot.py
Copy path
File metadata and controls
4831 lines (4025 loc) · 152 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
# Note: The first part of this file is hand-written and must be edited
# in-place. The second part, starting with
# ### REMAINING CONTENT GENERATED BY boilerplate.py ###
# is generated by the script boilerplate.py. It must not be edited here
# because all changes will be overwritten by the next run of the script.
# For more information see the description in boilerplate.py.
"""
`matplotlib.pyplot` is a state-based interface to matplotlib. It provides
an implicit, MATLAB-like, way of plotting. It also opens figures on your
screen, and acts as the figure GUI manager.
pyplot is mainly intended for interactive plots and simple cases of
programmatic plot generation::
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
The explicit object-oriented API is recommended for complex plots, though
pyplot is still usually used to create the figure and often the Axes in the
figure. See `.pyplot.figure`, `.pyplot.subplots`, and
`.pyplot.subplot_mosaic` to create figures, and
:doc:`Axes API </api/axes_api>` for the plotting methods on an Axes::
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
See :ref:`api_interfaces` for an explanation of the tradeoffs between the
implicit and explicit interfaces.
"""
# fmt: off
from
__future__
import
annotations
from
contextlib
import
AbstractContextManager
,
ExitStack
from
enum
import
Enum
import
functools
import
importlib
import
inspect
import
logging
import
sys
import
threading
import
time
from
typing
import
IO
,
TYPE_CHECKING
,
cast
,
overload
from
cycler
import
cycler
# noqa: F401
import
matplotlib
import
matplotlib
.
image
from
matplotlib
import
_api
# Re-exported (import x as x) for typing.
from
matplotlib
import
get_backend
as
get_backend
,
rcParams
as
rcParams
from
matplotlib
import
cm
as
cm
# noqa: F401
from
matplotlib
import
style
as
style
# noqa: F401
from
matplotlib
import
_pylab_helpers
from
matplotlib
import
interactive
# noqa: F401
from
matplotlib
import
cbook
from
matplotlib
import
_docstring
from
matplotlib
.
backend_bases
import
(
FigureCanvasBase
,
FigureManagerBase
,
MouseButton
)
from
matplotlib
.
figure
import
Figure
,
FigureBase
,
figaspect
from
matplotlib
.
gridspec
import
GridSpec
,
SubplotSpec
from
matplotlib
import
rcsetup
,
rcParamsDefault
,
rcParamsOrig
from
matplotlib
.
artist
import
Artist
from
matplotlib
.
axes
import
Axes
from
matplotlib
.
axes
import
Subplot
# noqa: F401
from
matplotlib
.
backends
import
BackendFilter
,
backend_registry
from
matplotlib
.
projections
import
PolarAxes
from
matplotlib
.
colorizer
import
_ColorizerInterface
,
ColorizingArtist
,
Colorizer
from
matplotlib
import
mlab
# for detrend_none, window_hanning
from
matplotlib
.
scale
import
get_scale_names
# noqa: F401
from
matplotlib
.
cm
import
_colormaps
from
matplotlib
.
colors
import
_color_sequences
,
Colormap
import
numpy
as
np
if
TYPE_CHECKING
:
from
collections
.
abc
import
Callable
,
Hashable
,
Iterable
,
Sequence
import
pathlib
import
os
from
typing
import
Any
,
BinaryIO
,
Literal
,
TypeVar
from
typing_extensions
import
ParamSpec
import
PIL
.
Image
from
numpy
.
typing
import
ArrayLike
import
pandas
as
pd
import
matplotlib
.
axes
import
matplotlib
.
artist
import
matplotlib
.
backend_bases
from
matplotlib
.
axis
import
Tick
from
matplotlib
.
axes
.
_base
import
_AxesBase
from
matplotlib
.
backend_bases
import
(
CloseEvent
,
DrawEvent
,
KeyEvent
,
MouseEvent
,
PickEvent
,
ResizeEvent
,
)
from
matplotlib
.
cm
import
ScalarMappable
from
matplotlib
.
contour
import
ContourSet
,
QuadContourSet
from
matplotlib
.
collections
import
(
Collection
,
FillBetweenPolyCollection
,
LineCollection
,
PolyCollection
,
PathCollection
,
EventCollection
,
QuadMesh
,
)
from
matplotlib
.
colorbar
import
Colorbar
from
matplotlib
.
container
import
(
BarContainer
,
ErrorbarContainer
,
PieContainer
,
StemContainer
,
)
from
matplotlib
.
figure
import
SubFigure
from
matplotlib
.
legend
import
Legend
from
matplotlib
.
mlab
import
GaussianKDE
from
matplotlib
.
image
import
AxesImage
,
FigureImage
from
matplotlib
.
patches
import
FancyArrow
,
StepPatch
from
matplotlib
.
quiver
import
Barbs
,
Quiver
,
QuiverKey
from
matplotlib
.
scale
import
ScaleBase
from
matplotlib
.
typing
import
(
CloseEventType
,
ColorType
,
CoordsType
,
DataParamType
,
DrawEventType
,
HashableList
,
KeyEventType
,
LineStyleType
,
MarkerType
,
MouseEventType
,
PickEventType
,
RcGroupKeyType
,
RcKeyType
,
ResizeEventType
,
LogLevel
)
from
matplotlib
.
widgets
import
SubplotTool
_P
=
ParamSpec
(
'_P'
)
_R
=
TypeVar
(
'_R'
)
_T
=
TypeVar
(
'_T'
)
# We may not need the following imports here:
from
matplotlib
.
colors
import
Normalize
from
matplotlib
.
lines
import
Line2D
,
AxLine
from
matplotlib
.
text
import
Text
,
Annotation
from
matplotlib
.
patches
import
Arrow
,
Circle
,
Rectangle
# noqa: F401
from
matplotlib
.
patches
import
Polygon
from
matplotlib
.
widgets
import
Button
,
Slider
,
Widget
# noqa: F401
from
.
ticker
import
(
# noqa: F401
TickHelper
,
Formatter
,
FixedFormatter
,
NullFormatter
,
FuncFormatter
,
FormatStrFormatter
,
ScalarFormatter
,
LogFormatter
,
LogFormatterExponent
,
LogFormatterMathtext
,
Locator
,
IndexLocator
,
FixedLocator
,
NullLocator
,
LinearLocator
,
LogLocator
,
AutoLocator
,
MultipleLocator
,
MaxNLocator
)
_log
=
logging
.
getLogger
(
__name__
)
# Explicit rename instead of import-as for typing's sake.
colormaps
=
_colormaps
color_sequences
=
_color_sequences
@
overload
def
_copy_docstring_and_deprecators
(
method
:
Any
,
func
:
Literal
[
None
]
=
None
)
->
Callable
[[
Callable
[
_P
,
_R
]],
Callable
[
_P
,
_R
]]: ...
@
overload
def
_copy_docstring_and_deprecators
(
method
:
Any
,
func
:
Callable
[
_P
,
_R
])
->
Callable
[
_P
,
_R
]: ...
def
_copy_docstring_and_deprecators
(
method
:
Any
,
func
:
Callable
[
_P
,
_R
]
|
None
=
None
)
->
Callable
[[
Callable
[
_P
,
_R
]],
Callable
[
_P
,
_R
]]
|
Callable
[
_P
,
_R
]:
if
func
is
None
:
return
cast
(
'Callable[[Callable[_P, _R]], Callable[_P, _R]]'
,
functools
.
partial
(
_copy_docstring_and_deprecators
,
method
))
decorators
:
list
[
Callable
[[
Callable
[
_P
,
_R
]],
Callable
[
_P
,
_R
]]]
=
[
_docstring
.
copy
(
method
)
]
# Check whether the definition of *method* includes @_api.rename_parameter
# or @_api.make_keyword_only decorators; if so, propagate them to the
# pyplot wrapper as well.
while
hasattr
(
method
,
"__wrapped__"
):
potential_decorator
=
_api
.
deprecation
.
DECORATORS
.
get
(
method
)
if
potential_decorator
:
decorators
.
append
(
potential_decorator
)
method
=
method
.
__wrapped__
for
decorator
in
decorators
[::
-
1
]:
func
=
decorator
(
func
)
_add_pyplot_note
(
func
,
method
)
return
func
_NO_PYPLOT_NOTE
=
[
'FigureBase._gci'
,
# wrapped_func is private
'_AxesBase._sci'
,
# wrapped_func is private
'Artist.findobj'
,
# not a standard pyplot wrapper because it does not operate
# on the current Figure / Axes. Explanation of relation would
# be more complex and is not too important.
]
def
_add_pyplot_note
(
func
,
wrapped_func
):
"""
Add a note to the docstring of *func* that it is a pyplot wrapper.
The note is added to the "Notes" section of the docstring. If that does
not exist, a "Notes" section is created. In numpydoc, the "Notes"
section is the third last possible section, only potentially followed by
"References" and "Examples".
"""
if
not
func
.
__doc__
:
return
# nothing to do
qualname
=
wrapped_func
.
__qualname__
if
qualname
in
_NO_PYPLOT_NOTE
:
return
wrapped_func_is_method
=
True
if
"."
not
in
qualname
:
# method qualnames are prefixed by the class and ".", e.g. "Axes.plot"
wrapped_func_is_method
=
False
link
=
f"
{
wrapped_func
.
__module__
}
.
{
qualname
}
"
elif
qualname
.
startswith
(
"Axes."
):
# e.g. "Axes.plot"
link
=
".axes."
+
qualname
elif
qualname
.
startswith
(
"_AxesBase."
):
# e.g. "_AxesBase.set_xlabel"
link
=
".axes.Axes"
+
qualname
[
9
:]
elif
qualname
.
startswith
(
"Figure."
):
# e.g. "Figure.figimage"
link
=
"."
+
qualname
elif
qualname
.
startswith
(
"FigureBase."
):
# e.g. "FigureBase.gca"
link
=
".Figure"
+
qualname
[
10
:]
elif
qualname
.
startswith
(
"FigureCanvasBase."
):
# "FigureBaseCanvas.mpl_connect"
link
=
"."
+
qualname
else
:
raise
RuntimeError
(
f"Wrapped method from unexpected class:
{
qualname
}
"
)
if
wrapped_func_is_method
:
message
=
f"This is the :ref:`pyplot wrapper <pyplot_interface>` for `
{
link
}
`."
else
:
message
=
f"This is equivalent to `
{
link
}
`."
# Find the correct insert position:
# - either we already have a "Notes" section into which we can insert
# - or we create one before the next present section. Note that in numpydoc, the
# "Notes" section is the third last possible section, only potentially followed
# by "References" and "Examples".
# - or we append a new "Notes" section at the end.
doc
=
inspect
.
cleandoc
(
func
.
__doc__
)
if
"
\n
Notes
\n
-----"
in
doc
:
before
,
after
=
doc
.
split
(
"
\n
Notes
\n
-----"
,
1
)
elif
(
index
:=
doc
.
find
(
"
\n
References
\n
----------"
))
!=
-
1
:
before
,
after
=
doc
[:
index
],
doc
[
index
:]
elif
(
index
:=
doc
.
find
(
"
\n
Examples
\n
--------"
))
!=
-
1
:
before
,
after
=
doc
[:
index
],
doc
[
index
:]
else
:
# No "Notes", "References", or "Examples" --> append to the end.
before
=
doc
+
"
\n
"
after
=
""
func
.
__doc__
=
f"
{
before
}
\n
Notes
\n
-----
\n
\n
.. note::
\n
\n
{
message
}
\n
{
after
}
"
## Global ##
# The state controlled by {,un}install_repl_displayhook().
_ReplDisplayHook
=
Enum
(
"_ReplDisplayHook"
, [
"NONE"
,
"PLAIN"
,
"IPYTHON"
])
_REPL_DISPLAYHOOK
=
_ReplDisplayHook
.
NONE
def
_draw_all_if_interactive
()
->
None
:
if
matplotlib
.
is_interactive
():
draw_all
()
def
install_repl_displayhook
()
->
None
:
"""
Connect to the display hook of the current shell.
The display hook gets called when the read-evaluate-print-loop (REPL) of
the shell has finished the execution of a command. We use this callback
to be able to automatically update a figure in interactive mode.
This works both with IPython and with vanilla python shells.
"""
global
_REPL_DISPLAYHOOK
if
_REPL_DISPLAYHOOK
is
_ReplDisplayHook
.
IPYTHON
:
return
# See if we have IPython hooks around, if so use them.
# Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
# entries can also have been explicitly set to None.
mod_ipython
=
sys
.
modules
.
get
(
"IPython"
)
if
not
mod_ipython
:
_REPL_DISPLAYHOOK
=
_ReplDisplayHook
.
PLAIN
return
ip
=
mod_ipython
.
get_ipython
()
if
not
ip
:
_REPL_DISPLAYHOOK
=
_ReplDisplayHook
.
PLAIN
return
ip
.
events
.
register
(
"post_execute"
,
_draw_all_if_interactive
)
_REPL_DISPLAYHOOK
=
_ReplDisplayHook
.
IPYTHON
if
mod_ipython
.
version_info
[:
2
]
<
(
8
,
24
):
# Use of backend2gui is not needed for IPython >= 8.24 as that functionality
# has been moved to Matplotlib.
# This code can be removed when Python 3.12, the latest version supported by
# IPython < 8.24, reaches end-of-life in late 2028.
from
IPython
.
core
.
pylabtools
import
backend2gui
ipython_gui_name
=
backend2gui
.
get
(
get_backend
())
else
:
_
,
ipython_gui_name
=
backend_registry
.
resolve_backend
(
get_backend
())
# trigger IPython's eventloop integration, if available
if
ipython_gui_name
:
ip
.
enable_gui
(
ipython_gui_name
)
def
uninstall_repl_displayhook
()
->
None
:
"""Disconnect from the display hook of the current shell."""
global
_REPL_DISPLAYHOOK
if
_REPL_DISPLAYHOOK
is
_ReplDisplayHook
.
IPYTHON
:
from
IPython
import
get_ipython
ip
=
get_ipython
()
ip
.
events
.
unregister
(
"post_execute"
,
_draw_all_if_interactive
)
_REPL_DISPLAYHOOK
=
_ReplDisplayHook
.
NONE
draw_all
=
_pylab_helpers
.
Gcf
.
draw_all
# Ensure this appears in the pyplot docs.
@
_copy_docstring_and_deprecators
(
matplotlib
.
set_loglevel
)
def
set_loglevel
(
level
:
LogLevel
)
->
None
:
return
matplotlib
.
set_loglevel
(
level
)
@
_copy_docstring_and_deprecators
(
Artist
.
findobj
)
def
findobj
(
o
:
Artist
|
None
=
None
,
match
:
Callable
[[
Artist
],
bool
]
|
type
[
Artist
]
|
None
=
None
,
include_self
:
bool
=
True
)
->
list
[
Artist
]:
if
o
is
None
:
o
=
gcf
()
return
o
.
findobj
(
match
,
include_self
=
include_self
)
_backend_mod
:
type
[
matplotlib
.
backend_bases
.
_Backend
]
|
None
=
None
def
_get_backend_mod
()
->
type
[
matplotlib
.
backend_bases
.
_Backend
]:
"""
Ensure that a backend is selected and return it.
This is currently private, but may be made public in the future.
"""
if
_backend_mod
is
None
:
# Use rcParams._get("backend") to avoid going through the fallback
# logic (which will (re)import pyplot and then call switch_backend if
# we need to resolve the auto sentinel)
switch_backend
(
rcParams
.
_get
(
"backend"
))
return
cast
(
type
[
matplotlib
.
backend_bases
.
_Backend
],
_backend_mod
)
def
switch_backend
(
newbackend
:
str
)
->
None
:
"""
Set the pyplot backend.
Switching to an interactive backend is possible only if no event loop for
another interactive backend has started. Switching to and from
non-interactive backends is always possible.
Parameters
----------
newbackend : str
The case-insensitive name of the backend to use.
"""
global
_backend_mod
# make sure the init is pulled up so we can assign to it later
import
matplotlib
.
backends
if
newbackend
is
rcsetup
.
_auto_backend_sentinel
:
current_framework
=
cbook
.
_get_running_interactive_framework
()
if
(
current_framework
and
(
backend
:=
backend_registry
.
backend_for_gui_framework
(
current_framework
))):
candidates
=
[
backend
]
else
:
candidates
=
[]
candidates
+=
[
"macosx"
,
"qtagg"
,
"gtk4agg"
,
"gtk3agg"
,
"tkagg"
,
"wxagg"
]
# Don't try to fallback on the cairo-based backends as they each have
# an additional dependency (pycairo) over the agg-based backend, and
# are of worse quality.
for
candidate
in
candidates
:
try
:
switch_backend
(
candidate
)
except
ImportError
:
_log
.
debug
(
"Skipping backend candidate %r as loading failed."
,
candidate
,
exc_info
=
True
)
continue
else
:
rcParamsOrig
[
'backend'
]
=
candidate
return
else
:
# Switching to Agg should always succeed; if it doesn't, let the
# exception propagate out.
switch_backend
(
"agg"
)
rcParamsOrig
[
"backend"
]
=
"agg"
return
old_backend
=
rcParams
.
_get
(
'backend'
)
# get without triggering backend resolution
module
=
backend_registry
.
load_backend_module
(
newbackend
)
canvas_class
=
module
.
FigureCanvas
required_framework
=
canvas_class
.
required_interactive_framework
if
required_framework
is
not
None
:
current_framework
=
cbook
.
_get_running_interactive_framework
()
if
(
current_framework
and
required_framework
and
current_framework
!=
required_framework
):
raise
ImportError
(
"Cannot load backend {!r} which requires the {!r} interactive "
"framework, as {!r} is currently running"
.
format
(
newbackend
,
required_framework
,
current_framework
))
# Load the new_figure_manager() and show() functions from the backend.
# Classically, backends can directly export these functions. This should
# keep working for backcompat.
new_figure_manager
=
getattr
(
module
,
"new_figure_manager"
,
None
)
show
=
getattr
(
module
,
"show"
,
None
)
# In that classical approach, backends are implemented as modules, but
# "inherit" default method implementations from backend_bases._Backend.
# This is achieved by creating a "class" that inherits from
# backend_bases._Backend and whose body is filled with the module globals.
class
backend_mod
(
matplotlib
.
backend_bases
.
_Backend
):
locals
().
update
(
vars
(
module
))
# However, the newer approach for defining new_figure_manager and
# show is to derive them from canvas methods. In that case, also
# update backend_mod accordingly; also, per-backend customization of
# draw_if_interactive is disabled.
if
new_figure_manager
is
None
:
def
new_figure_manager_given_figure
(
num
,
figure
):
return
canvas_class
.
new_manager
(
figure
,
num
)
def
new_figure_manager
(
num
,
*
args
,
FigureClass
=
Figure
,
**
kwargs
):
fig
=
FigureClass
(
*
args
,
**
kwargs
)
return
new_figure_manager_given_figure
(
num
,
fig
)
def
draw_if_interactive
()
->
None
:
if
matplotlib
.
is_interactive
():
manager
=
_pylab_helpers
.
Gcf
.
get_active
()
if
manager
:
manager
.
canvas
.
draw_idle
()
backend_mod
.
new_figure_manager_given_figure
=
(
# type: ignore[method-assign]
new_figure_manager_given_figure
)
backend_mod
.
new_figure_manager
=
(
# type: ignore[method-assign]
new_figure_manager
)
backend_mod
.
draw_if_interactive
=
(
# type: ignore[method-assign]
draw_if_interactive
)
# If the manager explicitly overrides pyplot_show, use it even if a global
# show is already present, as the latter may be here for backcompat.
manager_class
=
getattr
(
canvas_class
,
"manager_class"
,
None
)
# We can't compare directly manager_class.pyplot_show and FMB.pyplot_show because
# pyplot_show is a classmethod so the above constructs are bound classmethods, and
# thus always different (being bound to different classes). We also have to use
# getattr_static instead of vars as manager_class could have no __dict__.
manager_pyplot_show
=
inspect
.
getattr_static
(
manager_class
,
"pyplot_show"
,
None
)
base_pyplot_show
=
inspect
.
getattr_static
(
FigureManagerBase
,
"pyplot_show"
,
None
)
if
(
show
is
None
or
(
manager_pyplot_show
is
not
None
and
manager_pyplot_show
!=
base_pyplot_show
)):
if
not
manager_pyplot_show
:
raise
ValueError
(
f"Backend
{
newbackend
}
defines neither FigureCanvas.manager_class nor "
f"a toplevel show function"
)
_pyplot_show
=
cast
(
'Any'
,
manager_class
).
pyplot_show
backend_mod
.
show
=
_pyplot_show
# type: ignore[method-assign]
_log
.
debug
(
"Loaded backend %s version %s."
,
newbackend
,
backend_mod
.
backend_version
)
if
newbackend
in
(
"ipympl"
,
"widget"
):
# ipympl < 0.9.4 expects rcParams["backend"] to be the fully-qualified backend
# name "module://ipympl.backend_nbagg" not short names "ipympl" or "widget".
import
importlib
.
metadata
as
im
from
matplotlib
import
_parse_to_version_info
# type: ignore[attr-defined]
try
:
module_version
=
im
.
version
(
"ipympl"
)
if
_parse_to_version_info
(
module_version
)
<
(
0
,
9
,
4
):
newbackend
=
"module://ipympl.backend_nbagg"
except
im
.
PackageNotFoundError
:
pass
rcParams
[
'backend'
]
=
rcParamsDefault
[
'backend'
]
=
newbackend
_backend_mod
=
backend_mod
for
func_name
in
[
"new_figure_manager"
,
"draw_if_interactive"
,
"show"
]:
globals
()[
func_name
].
__signature__
=
inspect
.
signature
(
getattr
(
backend_mod
,
func_name
))
# Need to keep a global reference to the backend for compatibility reasons.
# See https://github.com/matplotlib/matplotlib/issues/6092
matplotlib
.
backends
.
backend
=
newbackend
# type: ignore[attr-defined]
# Make sure the repl display hook is installed in case we become interactive.
try
:
install_repl_displayhook
()
except
NotImplementedError
as
err
:
_log
.
warning
(
"Fallback to a different backend"
)
raise
ImportError
from
err
def
_warn_if_gui_out_of_main_thread
()
->
None
:
warn
=
False
canvas_class
=
cast
(
type
[
FigureCanvasBase
],
_get_backend_mod
().
FigureCanvas
)
if
canvas_class
.
required_interactive_framework
:
if
hasattr
(
threading
,
'get_native_id'
):
# This compares native thread ids because even if Python-level
# Thread objects match, the underlying OS thread (which is what
# really matters) may be different on Python implementations with
# green threads.
if
threading
.
get_native_id
()
!=
threading
.
main_thread
().
native_id
:
warn
=
True
else
:
# Fall back to Python-level Thread if native IDs are unavailable,
# mainly for PyPy.
if
threading
.
current_thread
()
is
not
threading
.
main_thread
():
warn
=
True
if
warn
:
_api
.
warn_external
(
"Starting a Matplotlib GUI outside of the main thread will likely "
"fail."
)
# This function's signature is rewritten upon backend-load by switch_backend.
def
new_figure_manager
(
*
args
,
**
kwargs
):
"""Create a new figure manager instance."""
_warn_if_gui_out_of_main_thread
()
return
_get_backend_mod
().
new_figure_manager
(
*
args
,
**
kwargs
)
# This function's signature is rewritten upon backend-load by switch_backend.
def
draw_if_interactive
(
*
args
,
**
kwargs
):
"""
Redraw the current figure if in interactive mode.
.. warning::
End users will typically not have to call this function because the
the interactive mode takes care of this.
"""
return
_get_backend_mod
().
draw_if_interactive
(
*
args
,
**
kwargs
)
@
overload
def
show
(
*
,
block
:
bool
,
**
kwargs
)
->
None
: ...
@
overload
def
show
(
*
args
:
Any
,
**
kwargs
:
Any
)
->
None
: ...
# This function's signature is rewritten upon backend-load by switch_backend.
def
show
(
*
args
,
**
kwargs
)
->
None
:
"""
Display all open figures.
Parameters
----------
block : bool, optional
Whether to wait for all figures to be closed before returning.
If `True` block and run the GUI main loop until all figure windows
are closed.
If `False` ensure that all figure windows are displayed and return
immediately. In this case, you are responsible for ensuring
that the event loop is running to have responsive figures.
Defaults to True in non-interactive mode and to False in interactive
mode (see `.pyplot.isinteractive`).
See Also
--------
ion : Enable interactive mode, which shows / updates the figure after
every plotting command, so that calling ``show()`` is not necessary.
ioff : Disable interactive mode.
savefig : Save the figure to an image file instead of showing it on screen.
Notes
-----
**Saving figures to file and showing a window at the same time**
If you want an image file as well as a user interface window, use
`.pyplot.savefig` before `.pyplot.show`. At the end of (a blocking)
``show()`` the figure is closed and thus unregistered from pyplot. Calling
`.pyplot.savefig` afterwards would save a new and thus empty figure. This
limitation of command order does not apply if the show is non-blocking or
if you keep a reference to the figure and use `.Figure.savefig`.
**Auto-show in jupyter notebooks**
The jupyter backends (activated via ``%matplotlib inline``,
``%matplotlib notebook``, or ``%matplotlib widget``), call ``show()`` at
the end of every cell by default. Thus, you usually don't have to call it
explicitly there.
"""
_warn_if_gui_out_of_main_thread
()
return
_get_backend_mod
().
show
(
*
args
,
**
kwargs
)
def
isinteractive
()
->
bool
:
"""
Return whether plots are updated after every plotting command.
The interactive mode is mainly useful if you build plots from the command
line and want to see the effect of each command while you are building the
figure.
In interactive mode:
- newly created figures will be shown immediately;
- figures will automatically redraw on change;
- `.pyplot.show` will not block by default.
In non-interactive mode:
- newly created figures and changes to figures will not be reflected until
explicitly asked to be;
- `.pyplot.show` will block by default.
See Also
--------
ion : Enable interactive mode.
ioff : Disable interactive mode.
show : Show all figures (and maybe block).
pause : Show all figures, and block for a time.
"""
return
matplotlib
.
is_interactive
()
# Note: The return type of ioff being AbstractContextManager
# instead of ExitStack is deliberate.
# See https://github.com/matplotlib/matplotlib/issues/27659
# and https://github.com/matplotlib/matplotlib/pull/27667 for more info.
def
ioff
()
->
AbstractContextManager
:
"""
Disable interactive mode.
See `.pyplot.isinteractive` for more details.
See Also
--------
ion : Enable interactive mode.
isinteractive : Whether interactive mode is enabled.
show : Show all figures (and maybe block).
pause : Show all figures, and block for a time.
Notes
-----
For a temporary change, this can be used as a context manager::
# if interactive mode is on
# then figures will be shown on creation
plt.ion()
# This figure will be shown immediately
fig = plt.figure()
with plt.ioff():
# interactive mode will be off
# figures will not automatically be shown
fig2 = plt.figure()
# ...
To enable optional usage as a context manager, this function returns a
context manager object, which is not intended to be stored or
accessed by the user.
"""
stack
=
ExitStack
()
stack
.
callback
(
ion
if
isinteractive
()
else
ioff
)
matplotlib
.
interactive
(
False
)
uninstall_repl_displayhook
()
return
stack
# Note: The return type of ion being AbstractContextManager
# instead of ExitStack is deliberate.
# See https://github.com/matplotlib/matplotlib/issues/27659
# and https://github.com/matplotlib/matplotlib/pull/27667 for more info.
def
ion
()
->
AbstractContextManager
:
"""
Enable interactive mode.
See `.pyplot.isinteractive` for more details.
See Also
--------
ioff : Disable interactive mode.
isinteractive : Whether interactive mode is enabled.
show : Show all figures (and maybe block).
pause : Show all figures, and block for a time.
Notes
-----
For a temporary change, this can be used as a context manager::
# if interactive mode is off
# then figures will not be shown on creation
plt.ioff()
# This figure will not be shown immediately
fig = plt.figure()
with plt.ion():
# interactive mode will be on
# figures will automatically be shown
fig2 = plt.figure()
# ...
To enable optional usage as a context manager, this function returns a
context manager object, which is not intended to be stored or
accessed by the user.
"""
stack
=
ExitStack
()
stack
.
callback
(
ion
if
isinteractive
()
else
ioff
)
matplotlib
.
interactive
(
True
)
install_repl_displayhook
()
return
stack
def
pause
(
interval
:
float
)
->
None
:
"""
Run the GUI event loop for *interval* seconds.
If there is an active figure, it will be updated and displayed before the
pause, and the GUI event loop (if any) will run during the pause.
This can be used for crude animation. For more complex animation use
:mod:`matplotlib.animation`.
If there is no active figure, sleep for *interval* seconds instead.
See Also
--------
matplotlib.animation : Proper animations
show : Show all figures and optional block until all figures are closed.
"""
manager
=
_pylab_helpers
.
Gcf
.
get_active
()
if
manager
is
not
None
:
canvas
=
manager
.
canvas
if
canvas
.
figure
.
stale
:
canvas
.
draw_idle
()
show
(
block
=
False
)
canvas
.
start_event_loop
(
interval
)
else
:
time
.
sleep
(
interval
)
@
_copy_docstring_and_deprecators
(
matplotlib
.
rc
)
def
rc
(
group
:
RcGroupKeyType
,
**
kwargs
)
->
None
:
matplotlib
.
rc
(
group
,
**
kwargs
)
@
_copy_docstring_and_deprecators
(
matplotlib
.
rc_context
)
def
rc_context
(
rc
:
dict
[
RcKeyType
,
Any
]
|
None
=
None
,
fname
:
str
|
pathlib
.
Path
|
os
.
PathLike
|
None
=
None
,
)
->
AbstractContextManager
[
None
]:
return
matplotlib
.
rc_context
(
rc
,
fname
)
@
_copy_docstring_and_deprecators
(
matplotlib
.
rcdefaults
)
def
rcdefaults
()
->
None
:
matplotlib
.
rcdefaults
()
if
matplotlib
.
is_interactive
():
draw_all
()
# getp/get/setp are explicitly reexported so that they show up in pyplot docs.
@
_copy_docstring_and_deprecators
(
matplotlib
.
artist
.
getp
)
def
getp
(
obj
,
*
args
,
**
kwargs
):
return
matplotlib
.
artist
.
getp
(
obj
,
*
args
,
**
kwargs
)
@
_copy_docstring_and_deprecators
(
matplotlib
.
artist
.
get
)
def
get
(
obj
,
*
args
,
**
kwargs
):
return
matplotlib
.
artist
.
get
(
obj
,
*
args
,
**
kwargs
)
@
_copy_docstring_and_deprecators
(
matplotlib
.
artist
.
setp
)
def
setp
(
obj
,
*
args
,
**
kwargs
):
return
matplotlib
.
artist
.
setp
(
obj
,
*
args
,
**
kwargs
)
def
xkcd
(
scale
:
float
=
1
,
length
:
float
=
100
,
randomness
:
float
=
2
)
->
ExitStack
:
"""
Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode.
This will only have an effect on things drawn after this function is called.
For best results, install the `xkcd script <https://github.com/ipython/xkcd-font/>`_
font; xkcd fonts are not packaged with Matplotlib.
Parameters
----------
scale : float, optional
The amplitude of the wiggle perpendicular to the source line.
length : float, optional
The length of the wiggle along the line.
randomness : float, optional
The scale factor by which the length is shrunken or expanded.
Notes
-----
This function works by a number of rcParams, overriding those set before.
If you want the effects of this function to be temporary, it can
be used as a context manager, for example::
with plt.xkcd():
# This figure will be in XKCD-style
fig1 = plt.figure()
# ...
# This figure will be in regular style
fig2 = plt.figure()
"""
# This cannot be implemented in terms of contextmanager() or rc_context()
# because this needs to work as a non-contextmanager too.
if
rcParams
[
'text.usetex'
]:
raise
RuntimeError
(
"xkcd mode is not compatible with text.usetex = True"
)
stack
=
ExitStack
()
stack
.
callback
(
rcParams
.
_update_raw
,
rcParams
.
copy
())
from
matplotlib
import
patheffects
rcParams
.
update
({
'font.family'
: [
'xkcd'
,
'xkcd Script'
,
'Comic Neue'
,
'Comic Sans MS'
],
'font.size'
:
14.0
,
'path.sketch'
: (
scale
,
length
,
randomness
),
'path.effects'
: [
patheffects
.
withStroke
(
linewidth
=
4
,
foreground
=
"w"
)],
'axes.linewidth'
:
1.5
,
'lines.linewidth'
:
2.0
,
'figure.facecolor'
:
'white'
,
'grid.linewidth'
:
0.0
,
'axes.grid'
:
False
,
'axes.unicode_minus'
:
False
,
'axes.edgecolor'
:
'black'
,
'xtick.major.size'
:
8
,
'xtick.major.width'
:
3
,
'ytick.major.size'
:
8
,
'ytick.major.width'
:
3
,
})
return
stack
## Figures ##
def
figure
(
# autoincrement if None, else integer from 1-N
num
:
int
|
str
|
Figure
|
SubFigure
|
None
=
None
,
# defaults to rc figure.figsize
figsize
:
ArrayLike
# a 2-element ndarray is accepted as well
|
tuple
[
float
,
float
,
Literal
[
"in"
,
"cm"
,
"px"
]]
|
None
=
None
,
# defaults to rc figure.dpi
dpi
:
float
|
None
=
None
,
*
,
# defaults to rc figure.facecolor
facecolor
:
ColorType
|
None
=
None
,
# defaults to rc figure.edgecolor
edgecolor
:
ColorType
|
None
=
None
,
frameon
:
bool
=
True
,
FigureClass
:
type
[
Figure
]
=
Figure
,
clear
:
bool
=
False
,
**
kwargs
)
->
Figure
:
"""
Create a new figure, or activate an existing figure.
Parameters
----------
num : int or str or `.Figure` or `.SubFigure`, optional
A unique identifier for the figure.
If a figure with that identifier already exists, this figure is made
active and returned. An integer refers to the ``Figure.number``
attribute, a string refers to the figure label.
If there is no figure with the identifier or *num* is not given, a new
figure is created, made active and returned. If *num* is an int, it
will be used for the ``Figure.number`` attribute, otherwise, an
auto-generated integer value is used (starting at 1 and incremented
for each new figure). If *num* is a string, the figure label and the
window title is set to this value. If num is a ``SubFigure``, its
parent ``Figure`` is activated.
If *num* is a Figure instance that is already tracked in pyplot, it is
activated. If *num* is a Figure instance that is not tracked in pyplot,
it is added to the tracked figures and activated.
figsize : (float, float) or (float, float, str), default: :rc:`figure.figsize`
The figure dimensions. This can be
- a tuple ``(width, height, unit)``, where *unit* is one of "in", "cm",
"px".
- a tuple ``(x, y)``, which is interpreted as ``(x, y, "in")``.
One of *width* or *height* may be ``None``; the respective value is taken
from :rc:`figure.figsize`.
dpi : float, default: :rc:`figure.dpi`
The resolution of the figure in dots-per-inch.
facecolor : :mpltype:`color`, default: :rc:`figure.facecolor`
The background color.
edgecolor : :mpltype:`color`, default: :rc:`figure.edgecolor`
The border color.
frameon : bool, default: True
If False, suppress drawing the figure frame.
FigureClass : subclass of `~matplotlib.figure.Figure`
If set, an instance of this subclass will be created, rather than a
plain `.Figure`.
clear : bool, default: False
If True and the figure already exists, then it is cleared.
layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None},
\
default: None
The layout mechanism for positioning of plot elements to avoid
overlapping Axes decorations (labels, ticks, etc). Note that layout
managers can measurably slow down figure display.
- 'constrained': The constrained layout solver adjusts Axes sizes
to avoid overlapping Axes decorations. Can handle complex plot
layouts and colorbars, and is thus recommended.
See :ref:`constrainedlayout_guide`
for examples.
- 'compressed': uses the same algorithm as 'constrained', but
removes extra space between fixed-aspect-ratio Axes. Best for
simple grids of Axes.
- 'tight': Use the tight layout mechanism. This is a relatively
simple algorithm that adjusts the subplot parameters so that
decorations do not overlap. See `.Figure.set_tight_layout` for
further details.
- 'none': Do not use a layout engine.
- A `.LayoutEngine` instance. Builtin layout classes are
`.ConstrainedLayoutEngine` and `.TightLayoutEngine`, more easily
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL