-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
pyplot.py
3322 lines (2604 loc) · 113 KB
/
pyplot.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
# Note: The first part of this file can be modified in place, but the latter
# part is autogenerated by the boilerplate.py script.
"""
`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)
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)
See :ref:`api_interfaces` for an explanation of the tradeoffs between the
implicit and explicit interfaces.
"""
from contextlib import ExitStack
from enum import Enum
import functools
import importlib
import inspect
import logging
from numbers import Number
import re
import sys
import threading
import time
from cycler import cycler
import matplotlib
import matplotlib.colorbar
import matplotlib.image
from matplotlib import _api
from matplotlib import rcsetup, style
from matplotlib import _pylab_helpers, interactive
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 rcParams, rcParamsDefault, get_backend, rcParamsOrig
from matplotlib.rcsetup import interactive_bk as _interactive_bk
from matplotlib.artist import Artist
from matplotlib.axes import Axes, Subplot
from matplotlib.projections import PolarAxes
from matplotlib import mlab # for detrend_none, window_hanning
from matplotlib.scale import get_scale_names
from matplotlib import cm
from matplotlib.cm import _colormaps as colormaps, register_cmap
from matplotlib.colors import _color_sequences as color_sequences
import numpy as np
# We may not need the following imports here:
from matplotlib.colors import Normalize
from matplotlib.lines import Line2D
from matplotlib.text import Text, Annotation
from matplotlib.patches import Polygon, Rectangle, Circle, Arrow
from matplotlib.widgets import Button, Slider, Widget
from .ticker import (
TickHelper, Formatter, FixedFormatter, NullFormatter, FuncFormatter,
FormatStrFormatter, ScalarFormatter, LogFormatter, LogFormatterExponent,
LogFormatterMathtext, Locator, IndexLocator, FixedLocator, NullLocator,
LinearLocator, LogLocator, AutoLocator, MultipleLocator, MaxNLocator)
_log = logging.getLogger(__name__)
def _copy_docstring_and_deprecators(method, func=None):
if func is None:
return functools.partial(_copy_docstring_and_deprecators, method)
decorators = [_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 getattr(method, "__wrapped__", None) is not None:
decorator = _api.deprecation.DECORATORS.get(method)
if decorator:
decorators.append(decorator)
method = method.__wrapped__
for decorator in decorators[::-1]:
func = decorator(func)
return func
## Global ##
# The state controlled by {,un}install_repl_displayhook().
_ReplDisplayHook = Enum("_ReplDisplayHook", ["NONE", "PLAIN", "IPYTHON"])
_REPL_DISPLAYHOOK = _ReplDisplayHook.NONE
def _draw_all_if_interactive():
if matplotlib.is_interactive():
draw_all()
def install_repl_displayhook():
"""
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
from IPython.core.pylabtools import backend2gui
# trigger IPython's eventloop integration, if available
ipython_gui_name = backend2gui.get(get_backend())
if ipython_gui_name:
ip.enable_gui(ipython_gui_name)
def uninstall_repl_displayhook():
"""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
@_copy_docstring_and_deprecators(matplotlib.set_loglevel)
def set_loglevel(*args, **kwargs): # Ensure this appears in the pyplot docs.
return matplotlib.set_loglevel(*args, **kwargs)
@_copy_docstring_and_deprecators(Artist.findobj)
def findobj(o=None, match=None, include_self=True):
if o is None:
o = gcf()
return o.findobj(match, include_self=include_self)
def _get_required_interactive_framework(backend_mod):
if not hasattr(getattr(backend_mod, "FigureCanvas", None),
"required_interactive_framework"):
_api.warn_deprecated(
"3.6", name="Support for FigureCanvases without a "
"required_interactive_framework attribute")
return None
# Inline this once the deprecation elapses.
return backend_mod.FigureCanvas.required_interactive_framework
_backend_mod = None
def _get_backend_mod():
"""
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 _backend_mod
def switch_backend(newbackend):
"""
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.
If the new backend is different than the current backend then all open
Figures will be closed via ``plt.close('all')``.
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()
mapping = {'qt': 'qtagg',
'gtk3': 'gtk3agg',
'gtk4': 'gtk4agg',
'wx': 'wxagg',
'tk': 'tkagg',
'macosx': 'macosx',
'headless': 'agg'}
best_guess = mapping.get(current_framework, None)
if best_guess is not None:
candidates = [best_guess]
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:
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
# have to escape the switch on access logic
old_backend = dict.__getitem__(rcParams, 'backend')
backend_mod = importlib.import_module(
cbook._backend_module_name(newbackend))
required_framework = _get_required_interactive_framework(backend_mod)
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(backend_mod, "new_figure_manager", None)
show = getattr(backend_mod, "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(backend_mod))
# 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:
# Only try to get the canvas class if have opted into the new scheme.
canvas_class = backend_mod.FigureCanvas
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():
if matplotlib.is_interactive():
manager = _pylab_helpers.Gcf.get_active()
if manager:
manager.canvas.draw_idle()
backend_mod.new_figure_manager_given_figure = \
new_figure_manager_given_figure
backend_mod.new_figure_manager = new_figure_manager
backend_mod.draw_if_interactive = 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(getattr(backend_mod, "FigureCanvas", None),
"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)):
backend_mod.show = manager_class.pyplot_show
_log.debug("Loaded backend %s version %s.",
newbackend, backend_mod.backend_version)
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
if not cbook._str_equal(old_backend, newbackend):
close("all")
# make sure the repl display hook is installed in case we become
# interactive
install_repl_displayhook()
def _warn_if_gui_out_of_main_thread():
warn = False
if _get_required_interactive_framework(_get_backend_mod()):
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)
# This function's signature is rewritten upon backend-load by switch_backend.
def show(*args, **kwargs):
"""
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():
"""
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()
def ioff():
"""
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
`~contextlib.ExitStack` 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
def ion():
"""
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
`~contextlib.ExitStack` 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):
"""
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, **kwargs):
matplotlib.rc(group, **kwargs)
@_copy_docstring_and_deprecators(matplotlib.rc_context)
def rc_context(rc=None, fname=None):
return matplotlib.rc_context(rc, fname)
@_copy_docstring_and_deprecators(matplotlib.rcdefaults)
def rcdefaults():
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=1, length=100, randomness=2):
"""
Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode. This will
only have effect on things drawn after this function is called.
For best results, the "Humor Sans" font should be installed: it is
not included 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, so it will probably
override others you have 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(dict.update, rcParams, rcParams.copy())
from matplotlib import patheffects
rcParams.update({
'font.family': ['xkcd', 'xkcd Script', 'Humor Sans', '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 ##
@_api.make_keyword_only("3.6", "facecolor")
def figure(num=None, # autoincrement if None, else integer from 1-N
figsize=None, # defaults to rc figure.figsize
dpi=None, # defaults to rc figure.dpi
facecolor=None, # defaults to rc figure.facecolor
edgecolor=None, # defaults to rc figure.edgecolor
frameon=True,
FigureClass=Figure,
clear=False,
**kwargs
):
"""
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.
figsize : (float, float), default: :rc:`figure.figsize`
Width, height in inches.
dpi : float, default: :rc:`figure.dpi`
The resolution of the figure in dots-per-inch.
facecolor : color, default: :rc:`figure.facecolor`
The background color.
edgecolor : 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 :doc:`/tutorials/intermediate/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
accessible by 'constrained' and 'tight'. Passing an instance
allows third parties to provide their own layout engine.
If not given, fall back to using the parameters *tight_layout* and
*constrained_layout*, including their config defaults
:rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`.
**kwargs
Additional keyword arguments are passed to the `.Figure` constructor.
Returns
-------
`~matplotlib.figure.Figure`
Notes
-----
A newly created figure is passed to the `~.FigureCanvasBase.new_manager`
method or the `new_figure_manager` function provided by the current
backend, which install a canvas and a manager on the figure.
Once this is done, :rc:`figure.hooks` are called, one at a time, on the
figure; these hooks allow arbitrary customization of the figure (e.g.,
attaching callbacks) or of associated elements (e.g., modifying the
toolbar). See :doc:`/gallery/user_interfaces/mplcvd` for an example of
toolbar customization.
If you are creating many figures, make sure you explicitly call
`.pyplot.close` on the figures you are not using, because this will
enable pyplot to properly clean up the memory.
`~matplotlib.rcParams` defines the default values, which can be modified
in the matplotlibrc file.
"""
if isinstance(num, FigureBase):
if num.canvas.manager is None:
raise ValueError("The passed figure is not managed by pyplot")
_pylab_helpers.Gcf.set_active(num.canvas.manager)
return num.figure
allnums = get_fignums()
next_num = max(allnums) + 1 if allnums else 1
fig_label = ''
if num is None:
num = next_num
elif isinstance(num, str):
fig_label = num
all_labels = get_figlabels()
if fig_label not in all_labels:
if fig_label == 'all':
_api.warn_external("close('all') closes all existing figures.")
num = next_num
else:
inum = all_labels.index(fig_label)
num = allnums[inum]
else:
num = int(num) # crude validation of num argument
manager = _pylab_helpers.Gcf.get_fig_manager(num)
if manager is None:
max_open_warning = rcParams['figure.max_open_warning']
if len(allnums) == max_open_warning >= 1:
_api.warn_external(
f"More than {max_open_warning} figures have been opened. "
f"Figures created through the pyplot interface "
f"(`matplotlib.pyplot.figure`) are retained until explicitly "
f"closed and may consume too much memory. (To control this "
f"warning, see the rcParam `figure.max_open_warning`). "
f"Consider using `matplotlib.pyplot.close()`.",
RuntimeWarning)
manager = new_figure_manager(
num, figsize=figsize, dpi=dpi,
facecolor=facecolor, edgecolor=edgecolor, frameon=frameon,
FigureClass=FigureClass, **kwargs)
fig = manager.canvas.figure
if fig_label:
fig.set_label(fig_label)
for hookspecs in rcParams["figure.hooks"]:
module_name, dotted_name = hookspecs.split(":")
obj = importlib.import_module(module_name)
for part in dotted_name.split("."):
obj = getattr(obj, part)
obj(fig)
_pylab_helpers.Gcf._set_new_active_manager(manager)
# make sure backends (inline) that we don't ship that expect this
# to be called in plotting commands to make the figure call show
# still work. There is probably a better way to do this in the
# FigureManager base class.
draw_if_interactive()
if _REPL_DISPLAYHOOK is _ReplDisplayHook.PLAIN:
fig.stale_callback = _auto_draw_if_interactive
if clear:
manager.canvas.figure.clear()
return manager.canvas.figure
def _auto_draw_if_interactive(fig, val):
"""
An internal helper function for making sure that auto-redrawing
works as intended in the plain python repl.
Parameters
----------
fig : Figure
A figure object which is assumed to be associated with a canvas
"""
if (val and matplotlib.is_interactive()
and not fig.canvas.is_saving()
and not fig.canvas._is_idle_drawing):
# Some artists can mark themselves as stale in the middle of drawing
# (e.g. axes position & tick labels being computed at draw time), but
# this shouldn't trigger a redraw because the current redraw will
# already take them into account.
with fig.canvas._idle_draw_cntx():
fig.canvas.draw_idle()
def gcf():
"""
Get the current figure.
If there is currently no figure on the pyplot figure stack, a new one is
created using `~.pyplot.figure()`. (To test whether there is currently a
figure on the pyplot figure stack, check whether `~.pyplot.get_fignums()`
is empty.)
"""
manager = _pylab_helpers.Gcf.get_active()
if manager is not None:
return manager.canvas.figure
else:
return figure()
def fignum_exists(num):
"""Return whether the figure with the given id exists."""
return _pylab_helpers.Gcf.has_fignum(num) or num in get_figlabels()
def get_fignums():
"""Return a list of existing figure numbers."""
return sorted(_pylab_helpers.Gcf.figs)
def get_figlabels():
"""Return a list of existing figure labels."""
managers = _pylab_helpers.Gcf.get_all_fig_managers()
managers.sort(key=lambda m: m.num)
return [m.canvas.figure.get_label() for m in managers]
def get_current_fig_manager():
"""
Return the figure manager of the current figure.
The figure manager is a container for the actual backend-depended window
that displays the figure on screen.
If no current figure exists, a new one is created, and its figure
manager is returned.
Returns
-------
`.FigureManagerBase` or backend-dependent subclass thereof
"""
return gcf().canvas.manager
@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_connect)
def connect(s, func):
return gcf().canvas.mpl_connect(s, func)
@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_disconnect)
def disconnect(cid):
return gcf().canvas.mpl_disconnect(cid)
def close(fig=None):
"""
Close a figure window.
Parameters
----------
fig : None or int or str or `.Figure`
The figure to close. There are a number of ways to specify this:
- *None*: the current figure
- `.Figure`: the given `.Figure` instance
- ``int``: a figure number
- ``str``: a figure name
- 'all': all figures
"""
if fig is None:
manager = _pylab_helpers.Gcf.get_active()
if manager is None:
return
else:
_pylab_helpers.Gcf.destroy(manager)
elif fig == 'all':
_pylab_helpers.Gcf.destroy_all()
elif isinstance(fig, int):
_pylab_helpers.Gcf.destroy(fig)
elif hasattr(fig, 'int'):
# if we are dealing with a type UUID, we
# can use its integer representation
_pylab_helpers.Gcf.destroy(fig.int)
elif isinstance(fig, str):
all_labels = get_figlabels()
if fig in all_labels:
num = get_fignums()[all_labels.index(fig)]
_pylab_helpers.Gcf.destroy(num)
elif isinstance(fig, Figure):
_pylab_helpers.Gcf.destroy_fig(fig)
else:
raise TypeError("close() argument must be a Figure, an int, a string, "
"or None, not %s" % type(fig))
def clf():
"""Clear the current figure."""
gcf().clear()
def draw():