Coverage for /usr/lib/python3/dist-packages/matplotlib/pyplot.py: 50%
842 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
1# Note: The first part of this file can be modified in place, but the latter
2# part is autogenerated by the boilerplate.py script.
4"""
5`matplotlib.pyplot` is a state-based interface to matplotlib. It provides
6an implicit, MATLAB-like, way of plotting. It also opens figures on your
7screen, and acts as the figure GUI manager.
9pyplot is mainly intended for interactive plots and simple cases of
10programmatic plot generation::
12 import numpy as np
13 import matplotlib.pyplot as plt
15 x = np.arange(0, 5, 0.1)
16 y = np.sin(x)
17 plt.plot(x, y)
19The explicit object-oriented API is recommended for complex plots, though
20pyplot is still usually used to create the figure and often the axes in the
21figure. See `.pyplot.figure`, `.pyplot.subplots`, and
22`.pyplot.subplot_mosaic` to create figures, and
23:doc:`Axes API </api/axes_api>` for the plotting methods on an Axes::
25 import numpy as np
26 import matplotlib.pyplot as plt
28 x = np.arange(0, 5, 0.1)
29 y = np.sin(x)
30 fig, ax = plt.subplots()
31 ax.plot(x, y)
34See :ref:`api_interfaces` for an explanation of the tradeoffs between the
35implicit and explicit interfaces.
36"""
38from contextlib import ExitStack
39from enum import Enum
40import functools
41import importlib
42import inspect
43import logging
44from numbers import Number
45import re
46import sys
47import threading
48import time
50from cycler import cycler
51import matplotlib
52import matplotlib.colorbar
53import matplotlib.image
54from matplotlib import _api
55from matplotlib import rcsetup, style
56from matplotlib import _pylab_helpers, interactive
57from matplotlib import cbook
58from matplotlib import _docstring
59from matplotlib.backend_bases import FigureCanvasBase, MouseButton
60from matplotlib.figure import Figure, FigureBase, figaspect
61from matplotlib.gridspec import GridSpec, SubplotSpec
62from matplotlib import rcParams, rcParamsDefault, get_backend, rcParamsOrig
63from matplotlib.rcsetup import interactive_bk as _interactive_bk
64from matplotlib.artist import Artist
65from matplotlib.axes import Axes, Subplot
66from matplotlib.projections import PolarAxes
67from matplotlib import mlab # for detrend_none, window_hanning
68from matplotlib.scale import get_scale_names
70from matplotlib import cm
71from matplotlib.cm import _colormaps as colormaps, register_cmap
72from matplotlib.colors import _color_sequences as color_sequences
74import numpy as np
76# We may not need the following imports here:
77from matplotlib.colors import Normalize
78from matplotlib.lines import Line2D
79from matplotlib.text import Text, Annotation
80from matplotlib.patches import Polygon, Rectangle, Circle, Arrow
81from matplotlib.widgets import Button, Slider, Widget
83from .ticker import (
84 TickHelper, Formatter, FixedFormatter, NullFormatter, FuncFormatter,
85 FormatStrFormatter, ScalarFormatter, LogFormatter, LogFormatterExponent,
86 LogFormatterMathtext, Locator, IndexLocator, FixedLocator, NullLocator,
87 LinearLocator, LogLocator, AutoLocator, MultipleLocator, MaxNLocator)
89_log = logging.getLogger(__name__)
92def _copy_docstring_and_deprecators(method, func=None):
93 if func is None:
94 return functools.partial(_copy_docstring_and_deprecators, method)
95 decorators = [_docstring.copy(method)]
96 # Check whether the definition of *method* includes @_api.rename_parameter
97 # or @_api.make_keyword_only decorators; if so, propagate them to the
98 # pyplot wrapper as well.
99 while getattr(method, "__wrapped__", None) is not None:
100 decorator = _api.deprecation.DECORATORS.get(method)
101 if decorator:
102 decorators.append(decorator)
103 method = method.__wrapped__
104 for decorator in decorators[::-1]:
105 func = decorator(func)
106 return func
109## Global ##
112# The state controlled by {,un}install_repl_displayhook().
113_ReplDisplayHook = Enum("_ReplDisplayHook", ["NONE", "PLAIN", "IPYTHON"])
114_REPL_DISPLAYHOOK = _ReplDisplayHook.NONE
117def _draw_all_if_interactive():
118 if matplotlib.is_interactive():
119 draw_all()
122def install_repl_displayhook():
123 """
124 Connect to the display hook of the current shell.
126 The display hook gets called when the read-evaluate-print-loop (REPL) of
127 the shell has finished the execution of a command. We use this callback
128 to be able to automatically update a figure in interactive mode.
130 This works both with IPython and with vanilla python shells.
131 """
132 global _REPL_DISPLAYHOOK
134 if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON:
135 return
137 # See if we have IPython hooks around, if so use them.
138 # Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
139 # entries can also have been explicitly set to None.
140 mod_ipython = sys.modules.get("IPython")
141 if not mod_ipython:
142 _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN
143 return
144 ip = mod_ipython.get_ipython()
145 if not ip:
146 _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN
147 return
149 ip.events.register("post_execute", _draw_all_if_interactive)
150 _REPL_DISPLAYHOOK = _ReplDisplayHook.IPYTHON
152 from IPython.core.pylabtools import backend2gui
153 # trigger IPython's eventloop integration, if available
154 ipython_gui_name = backend2gui.get(get_backend())
155 if ipython_gui_name:
156 ip.enable_gui(ipython_gui_name)
159def uninstall_repl_displayhook():
160 """Disconnect from the display hook of the current shell."""
161 global _REPL_DISPLAYHOOK
162 if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON:
163 from IPython import get_ipython
164 ip = get_ipython()
165 ip.events.unregister("post_execute", _draw_all_if_interactive)
166 _REPL_DISPLAYHOOK = _ReplDisplayHook.NONE
169draw_all = _pylab_helpers.Gcf.draw_all
172@_copy_docstring_and_deprecators(matplotlib.set_loglevel)
173def set_loglevel(*args, **kwargs): # Ensure this appears in the pyplot docs.
174 return matplotlib.set_loglevel(*args, **kwargs)
177@_copy_docstring_and_deprecators(Artist.findobj)
178def findobj(o=None, match=None, include_self=True):
179 if o is None:
180 o = gcf()
181 return o.findobj(match, include_self=include_self)
184def _get_required_interactive_framework(backend_mod):
185 if not hasattr(getattr(backend_mod, "FigureCanvas", None),
186 "required_interactive_framework"):
187 _api.warn_deprecated(
188 "3.6", name="Support for FigureCanvases without a "
189 "required_interactive_framework attribute")
190 return None
191 # Inline this once the deprecation elapses.
192 return backend_mod.FigureCanvas.required_interactive_framework
194_backend_mod = None
197def _get_backend_mod():
198 """
199 Ensure that a backend is selected and return it.
201 This is currently private, but may be made public in the future.
202 """
203 if _backend_mod is None:
204 # Use __getitem__ here to avoid going through the fallback logic (which
205 # will (re)import pyplot and then call switch_backend if we need to
206 # resolve the auto sentinel)
207 switch_backend(dict.__getitem__(rcParams, "backend"))
208 return _backend_mod
211def switch_backend(newbackend):
212 """
213 Close all open figures and set the Matplotlib backend.
215 The argument is case-insensitive. Switching to an interactive backend is
216 possible only if no event loop for another interactive backend has started.
217 Switching to and from non-interactive backends is always possible.
219 Parameters
220 ----------
221 newbackend : str
222 The name of the backend to use.
223 """
224 global _backend_mod
225 # make sure the init is pulled up so we can assign to it later
226 import matplotlib.backends
227 close("all")
229 if newbackend is rcsetup._auto_backend_sentinel:
230 current_framework = cbook._get_running_interactive_framework()
231 mapping = {'qt': 'qtagg',
232 'gtk3': 'gtk3agg',
233 'gtk4': 'gtk4agg',
234 'wx': 'wxagg',
235 'tk': 'tkagg',
236 'macosx': 'macosx',
237 'headless': 'agg'}
239 best_guess = mapping.get(current_framework, None)
240 if best_guess is not None:
241 candidates = [best_guess]
242 else:
243 candidates = []
244 candidates += [
245 "macosx", "qtagg", "gtk4agg", "gtk3agg", "tkagg", "wxagg"]
247 # Don't try to fallback on the cairo-based backends as they each have
248 # an additional dependency (pycairo) over the agg-based backend, and
249 # are of worse quality.
250 for candidate in candidates:
251 try:
252 switch_backend(candidate)
253 except ImportError:
254 continue
255 else:
256 rcParamsOrig['backend'] = candidate
257 return
258 else:
259 # Switching to Agg should always succeed; if it doesn't, let the
260 # exception propagate out.
261 switch_backend("agg")
262 rcParamsOrig["backend"] = "agg"
263 return
265 backend_mod = importlib.import_module(
266 cbook._backend_module_name(newbackend))
268 required_framework = _get_required_interactive_framework(backend_mod)
269 if required_framework is not None:
270 current_framework = cbook._get_running_interactive_framework()
271 if (current_framework and required_framework
272 and current_framework != required_framework):
273 raise ImportError(
274 "Cannot load backend {!r} which requires the {!r} interactive "
275 "framework, as {!r} is currently running".format(
276 newbackend, required_framework, current_framework))
278 # Load the new_figure_manager() and show() functions from the backend.
280 # Classically, backends can directly export these functions. This should
281 # keep working for backcompat.
282 new_figure_manager = getattr(backend_mod, "new_figure_manager", None)
283 # show = getattr(backend_mod, "show", None)
284 # In that classical approach, backends are implemented as modules, but
285 # "inherit" default method implementations from backend_bases._Backend.
286 # This is achieved by creating a "class" that inherits from
287 # backend_bases._Backend and whose body is filled with the module globals.
288 class backend_mod(matplotlib.backend_bases._Backend):
289 locals().update(vars(backend_mod))
291 # However, the newer approach for defining new_figure_manager (and, in
292 # the future, show) is to derive them from canvas methods. In that case,
293 # also update backend_mod accordingly; also, per-backend customization of
294 # draw_if_interactive is disabled.
295 if new_figure_manager is None:
296 # only try to get the canvas class if have opted into the new scheme
297 canvas_class = backend_mod.FigureCanvas
298 def new_figure_manager_given_figure(num, figure):
299 return canvas_class.new_manager(figure, num)
301 def new_figure_manager(num, *args, FigureClass=Figure, **kwargs):
302 fig = FigureClass(*args, **kwargs)
303 return new_figure_manager_given_figure(num, fig)
305 def draw_if_interactive():
306 if matplotlib.is_interactive():
307 manager = _pylab_helpers.Gcf.get_active()
308 if manager:
309 manager.canvas.draw_idle()
311 backend_mod.new_figure_manager_given_figure = \
312 new_figure_manager_given_figure
313 backend_mod.new_figure_manager = new_figure_manager
314 backend_mod.draw_if_interactive = draw_if_interactive
316 _log.debug("Loaded backend %s version %s.",
317 newbackend, backend_mod.backend_version)
319 rcParams['backend'] = rcParamsDefault['backend'] = newbackend
320 _backend_mod = backend_mod
321 for func_name in ["new_figure_manager", "draw_if_interactive", "show"]:
322 globals()[func_name].__signature__ = inspect.signature(
323 getattr(backend_mod, func_name))
325 # Need to keep a global reference to the backend for compatibility reasons.
326 # See https://github.com/matplotlib/matplotlib/issues/6092
327 matplotlib.backends.backend = newbackend
329 # make sure the repl display hook is installed in case we become
330 # interactive
331 install_repl_displayhook()
334def _warn_if_gui_out_of_main_thread():
335 warn = False
336 if _get_required_interactive_framework(_get_backend_mod()):
337 if hasattr(threading, 'get_native_id'):
338 # This compares native thread ids because even if Python-level
339 # Thread objects match, the underlying OS thread (which is what
340 # really matters) may be different on Python implementations with
341 # green threads.
342 if threading.get_native_id() != threading.main_thread().native_id:
343 warn = True
344 else:
345 # Fall back to Python-level Thread if native IDs are unavailable,
346 # mainly for PyPy.
347 if threading.current_thread() is not threading.main_thread():
348 warn = True
349 if warn:
350 _api.warn_external(
351 "Starting a Matplotlib GUI outside of the main thread will likely "
352 "fail.")
355# This function's signature is rewritten upon backend-load by switch_backend.
356def new_figure_manager(*args, **kwargs):
357 """Create a new figure manager instance."""
358 _warn_if_gui_out_of_main_thread()
359 return _get_backend_mod().new_figure_manager(*args, **kwargs)
362# This function's signature is rewritten upon backend-load by switch_backend.
363def draw_if_interactive(*args, **kwargs):
364 """
365 Redraw the current figure if in interactive mode.
367 .. warning::
369 End users will typically not have to call this function because the
370 the interactive mode takes care of this.
371 """
372 return _get_backend_mod().draw_if_interactive(*args, **kwargs)
375# This function's signature is rewritten upon backend-load by switch_backend.
376def show(*args, **kwargs):
377 """
378 Display all open figures.
380 Parameters
381 ----------
382 block : bool, optional
383 Whether to wait for all figures to be closed before returning.
385 If `True` block and run the GUI main loop until all figure windows
386 are closed.
388 If `False` ensure that all figure windows are displayed and return
389 immediately. In this case, you are responsible for ensuring
390 that the event loop is running to have responsive figures.
392 Defaults to True in non-interactive mode and to False in interactive
393 mode (see `.pyplot.isinteractive`).
395 See Also
396 --------
397 ion : Enable interactive mode, which shows / updates the figure after
398 every plotting command, so that calling ``show()`` is not necessary.
399 ioff : Disable interactive mode.
400 savefig : Save the figure to an image file instead of showing it on screen.
402 Notes
403 -----
404 **Saving figures to file and showing a window at the same time**
406 If you want an image file as well as a user interface window, use
407 `.pyplot.savefig` before `.pyplot.show`. At the end of (a blocking)
408 ``show()`` the figure is closed and thus unregistered from pyplot. Calling
409 `.pyplot.savefig` afterwards would save a new and thus empty figure. This
410 limitation of command order does not apply if the show is non-blocking or
411 if you keep a reference to the figure and use `.Figure.savefig`.
413 **Auto-show in jupyter notebooks**
415 The jupyter backends (activated via ``%matplotlib inline``,
416 ``%matplotlib notebook``, or ``%matplotlib widget``), call ``show()`` at
417 the end of every cell by default. Thus, you usually don't have to call it
418 explicitly there.
419 """
420 _warn_if_gui_out_of_main_thread()
421 return _get_backend_mod().show(*args, **kwargs)
424def isinteractive():
425 """
426 Return whether plots are updated after every plotting command.
428 The interactive mode is mainly useful if you build plots from the command
429 line and want to see the effect of each command while you are building the
430 figure.
432 In interactive mode:
434 - newly created figures will be shown immediately;
435 - figures will automatically redraw on change;
436 - `.pyplot.show` will not block by default.
438 In non-interactive mode:
440 - newly created figures and changes to figures will not be reflected until
441 explicitly asked to be;
442 - `.pyplot.show` will block by default.
444 See Also
445 --------
446 ion : Enable interactive mode.
447 ioff : Disable interactive mode.
448 show : Show all figures (and maybe block).
449 pause : Show all figures, and block for a time.
450 """
451 return matplotlib.is_interactive()
454def ioff():
455 """
456 Disable interactive mode.
458 See `.pyplot.isinteractive` for more details.
460 See Also
461 --------
462 ion : Enable interactive mode.
463 isinteractive : Whether interactive mode is enabled.
464 show : Show all figures (and maybe block).
465 pause : Show all figures, and block for a time.
467 Notes
468 -----
469 For a temporary change, this can be used as a context manager::
471 # if interactive mode is on
472 # then figures will be shown on creation
473 plt.ion()
474 # This figure will be shown immediately
475 fig = plt.figure()
477 with plt.ioff():
478 # interactive mode will be off
479 # figures will not automatically be shown
480 fig2 = plt.figure()
481 # ...
483 To enable optional usage as a context manager, this function returns a
484 `~contextlib.ExitStack` object, which is not intended to be stored or
485 accessed by the user.
486 """
487 stack = ExitStack()
488 stack.callback(ion if isinteractive() else ioff)
489 matplotlib.interactive(False)
490 uninstall_repl_displayhook()
491 return stack
494def ion():
495 """
496 Enable interactive mode.
498 See `.pyplot.isinteractive` for more details.
500 See Also
501 --------
502 ioff : Disable interactive mode.
503 isinteractive : Whether interactive mode is enabled.
504 show : Show all figures (and maybe block).
505 pause : Show all figures, and block for a time.
507 Notes
508 -----
509 For a temporary change, this can be used as a context manager::
511 # if interactive mode is off
512 # then figures will not be shown on creation
513 plt.ioff()
514 # This figure will not be shown immediately
515 fig = plt.figure()
517 with plt.ion():
518 # interactive mode will be on
519 # figures will automatically be shown
520 fig2 = plt.figure()
521 # ...
523 To enable optional usage as a context manager, this function returns a
524 `~contextlib.ExitStack` object, which is not intended to be stored or
525 accessed by the user.
526 """
527 stack = ExitStack()
528 stack.callback(ion if isinteractive() else ioff)
529 matplotlib.interactive(True)
530 install_repl_displayhook()
531 return stack
534def pause(interval):
535 """
536 Run the GUI event loop for *interval* seconds.
538 If there is an active figure, it will be updated and displayed before the
539 pause, and the GUI event loop (if any) will run during the pause.
541 This can be used for crude animation. For more complex animation use
542 :mod:`matplotlib.animation`.
544 If there is no active figure, sleep for *interval* seconds instead.
546 See Also
547 --------
548 matplotlib.animation : Proper animations
549 show : Show all figures and optional block until all figures are closed.
550 """
551 manager = _pylab_helpers.Gcf.get_active()
552 if manager is not None:
553 canvas = manager.canvas
554 if canvas.figure.stale:
555 canvas.draw_idle()
556 show(block=False)
557 canvas.start_event_loop(interval)
558 else:
559 time.sleep(interval)
562@_copy_docstring_and_deprecators(matplotlib.rc)
563def rc(group, **kwargs):
564 matplotlib.rc(group, **kwargs)
567@_copy_docstring_and_deprecators(matplotlib.rc_context)
568def rc_context(rc=None, fname=None):
569 return matplotlib.rc_context(rc, fname)
572@_copy_docstring_and_deprecators(matplotlib.rcdefaults)
573def rcdefaults():
574 matplotlib.rcdefaults()
575 if matplotlib.is_interactive():
576 draw_all()
579# getp/get/setp are explicitly reexported so that they show up in pyplot docs.
582@_copy_docstring_and_deprecators(matplotlib.artist.getp)
583def getp(obj, *args, **kwargs):
584 return matplotlib.artist.getp(obj, *args, **kwargs)
587@_copy_docstring_and_deprecators(matplotlib.artist.get)
588def get(obj, *args, **kwargs):
589 return matplotlib.artist.get(obj, *args, **kwargs)
592@_copy_docstring_and_deprecators(matplotlib.artist.setp)
593def setp(obj, *args, **kwargs):
594 return matplotlib.artist.setp(obj, *args, **kwargs)
597def xkcd(scale=1, length=100, randomness=2):
598 """
599 Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode. This will
600 only have effect on things drawn after this function is called.
602 For best results, the "Humor Sans" font should be installed: it is
603 not included with Matplotlib.
605 Parameters
606 ----------
607 scale : float, optional
608 The amplitude of the wiggle perpendicular to the source line.
609 length : float, optional
610 The length of the wiggle along the line.
611 randomness : float, optional
612 The scale factor by which the length is shrunken or expanded.
614 Notes
615 -----
616 This function works by a number of rcParams, so it will probably
617 override others you have set before.
619 If you want the effects of this function to be temporary, it can
620 be used as a context manager, for example::
622 with plt.xkcd():
623 # This figure will be in XKCD-style
624 fig1 = plt.figure()
625 # ...
627 # This figure will be in regular style
628 fig2 = plt.figure()
629 """
630 # This cannot be implemented in terms of contextmanager() or rc_context()
631 # because this needs to work as a non-contextmanager too.
633 if rcParams['text.usetex']:
634 raise RuntimeError(
635 "xkcd mode is not compatible with text.usetex = True")
637 stack = ExitStack()
638 stack.callback(dict.update, rcParams, rcParams.copy())
640 from matplotlib import patheffects
641 rcParams.update({
642 'font.family': ['xkcd', 'xkcd Script', 'Humor Sans', 'Comic Neue',
643 'Comic Sans MS', 'StayPuft'],
644 'font.size': 14.0,
645 'path.sketch': (scale, length, randomness),
646 'path.effects': [
647 patheffects.withStroke(linewidth=4, foreground="w")],
648 'axes.linewidth': 1.5,
649 'lines.linewidth': 2.0,
650 'figure.facecolor': 'white',
651 'grid.linewidth': 0.0,
652 'axes.grid': False,
653 'axes.unicode_minus': False,
654 'axes.edgecolor': 'black',
655 'xtick.major.size': 8,
656 'xtick.major.width': 3,
657 'ytick.major.size': 8,
658 'ytick.major.width': 3,
659 })
661 return stack
664## Figures ##
666@_api.make_keyword_only("3.6", "facecolor")
667def figure(num=None, # autoincrement if None, else integer from 1-N
668 figsize=None, # defaults to rc figure.figsize
669 dpi=None, # defaults to rc figure.dpi
670 facecolor=None, # defaults to rc figure.facecolor
671 edgecolor=None, # defaults to rc figure.edgecolor
672 frameon=True,
673 FigureClass=Figure,
674 clear=False,
675 **kwargs
676 ):
677 """
678 Create a new figure, or activate an existing figure.
680 Parameters
681 ----------
682 num : int or str or `.Figure` or `.SubFigure`, optional
683 A unique identifier for the figure.
685 If a figure with that identifier already exists, this figure is made
686 active and returned. An integer refers to the ``Figure.number``
687 attribute, a string refers to the figure label.
689 If there is no figure with the identifier or *num* is not given, a new
690 figure is created, made active and returned. If *num* is an int, it
691 will be used for the ``Figure.number`` attribute, otherwise, an
692 auto-generated integer value is used (starting at 1 and incremented
693 for each new figure). If *num* is a string, the figure label and the
694 window title is set to this value. If num is a ``SubFigure``, its
695 parent ``Figure`` is activated.
697 figsize : (float, float), default: :rc:`figure.figsize`
698 Width, height in inches.
700 dpi : float, default: :rc:`figure.dpi`
701 The resolution of the figure in dots-per-inch.
703 facecolor : color, default: :rc:`figure.facecolor`
704 The background color.
706 edgecolor : color, default: :rc:`figure.edgecolor`
707 The border color.
709 frameon : bool, default: True
710 If False, suppress drawing the figure frame.
712 FigureClass : subclass of `~matplotlib.figure.Figure`
713 If set, an instance of this subclass will be created, rather than a
714 plain `.Figure`.
716 clear : bool, default: False
717 If True and the figure already exists, then it is cleared.
719 layout : {'constrained', 'tight', `.LayoutEngine`, None}, default: None
720 The layout mechanism for positioning of plot elements to avoid
721 overlapping Axes decorations (labels, ticks, etc). Note that layout
722 managers can measurably slow down figure display. Defaults to *None*
723 (but see the documentation of the `.Figure` constructor regarding the
724 interaction with rcParams).
726 **kwargs
727 Additional keyword arguments are passed to the `.Figure` constructor.
729 Returns
730 -------
731 `~matplotlib.figure.Figure`
733 Notes
734 -----
735 Newly created figures are passed to the `~.FigureCanvasBase.new_manager`
736 method or the `new_figure_manager` function provided by the current
737 backend, which install a canvas and a manager on the figure.
739 If you are creating many figures, make sure you explicitly call
740 `.pyplot.close` on the figures you are not using, because this will
741 enable pyplot to properly clean up the memory.
743 `~matplotlib.rcParams` defines the default values, which can be modified
744 in the matplotlibrc file.
745 """
746 if isinstance(num, FigureBase):
747 if num.canvas.manager is None:
748 raise ValueError("The passed figure is not managed by pyplot")
749 _pylab_helpers.Gcf.set_active(num.canvas.manager)
750 return num.figure
752 allnums = get_fignums()
753 next_num = max(allnums) + 1 if allnums else 1
754 fig_label = ''
755 if num is None:
756 num = next_num
757 elif isinstance(num, str):
758 fig_label = num
759 all_labels = get_figlabels()
760 if fig_label not in all_labels:
761 if fig_label == 'all':
762 _api.warn_external("close('all') closes all existing figures.")
763 num = next_num
764 else:
765 inum = all_labels.index(fig_label)
766 num = allnums[inum]
767 else:
768 num = int(num) # crude validation of num argument
770 manager = _pylab_helpers.Gcf.get_fig_manager(num)
771 if manager is None:
772 max_open_warning = rcParams['figure.max_open_warning']
773 if len(allnums) == max_open_warning >= 1:
774 _api.warn_external(
775 f"More than {max_open_warning} figures have been opened. "
776 f"Figures created through the pyplot interface "
777 f"(`matplotlib.pyplot.figure`) are retained until explicitly "
778 f"closed and may consume too much memory. (To control this "
779 f"warning, see the rcParam `figure.max_open_warning`). "
780 f"Consider using `matplotlib.pyplot.close()`.",
781 RuntimeWarning)
783 manager = new_figure_manager(
784 num, figsize=figsize, dpi=dpi,
785 facecolor=facecolor, edgecolor=edgecolor, frameon=frameon,
786 FigureClass=FigureClass, **kwargs)
787 fig = manager.canvas.figure
788 if fig_label:
789 fig.set_label(fig_label)
791 _pylab_helpers.Gcf._set_new_active_manager(manager)
793 # make sure backends (inline) that we don't ship that expect this
794 # to be called in plotting commands to make the figure call show
795 # still work. There is probably a better way to do this in the
796 # FigureManager base class.
797 draw_if_interactive()
799 if _REPL_DISPLAYHOOK is _ReplDisplayHook.PLAIN:
800 fig.stale_callback = _auto_draw_if_interactive
802 if clear:
803 manager.canvas.figure.clear()
805 return manager.canvas.figure
808def _auto_draw_if_interactive(fig, val):
809 """
810 An internal helper function for making sure that auto-redrawing
811 works as intended in the plain python repl.
813 Parameters
814 ----------
815 fig : Figure
816 A figure object which is assumed to be associated with a canvas
817 """
818 if (val and matplotlib.is_interactive()
819 and not fig.canvas.is_saving()
820 and not fig.canvas._is_idle_drawing):
821 # Some artists can mark themselves as stale in the middle of drawing
822 # (e.g. axes position & tick labels being computed at draw time), but
823 # this shouldn't trigger a redraw because the current redraw will
824 # already take them into account.
825 with fig.canvas._idle_draw_cntx():
826 fig.canvas.draw_idle()
829def gcf():
830 """
831 Get the current figure.
833 If there is currently no figure on the pyplot figure stack, a new one is
834 created using `~.pyplot.figure()`. (To test whether there is currently a
835 figure on the pyplot figure stack, check whether `~.pyplot.get_fignums()`
836 is empty.)
837 """
838 manager = _pylab_helpers.Gcf.get_active()
839 if manager is not None:
840 return manager.canvas.figure
841 else:
842 return figure()
845def fignum_exists(num):
846 """Return whether the figure with the given id exists."""
847 return _pylab_helpers.Gcf.has_fignum(num) or num in get_figlabels()
850def get_fignums():
851 """Return a list of existing figure numbers."""
852 return sorted(_pylab_helpers.Gcf.figs)
855def get_figlabels():
856 """Return a list of existing figure labels."""
857 managers = _pylab_helpers.Gcf.get_all_fig_managers()
858 managers.sort(key=lambda m: m.num)
859 return [m.canvas.figure.get_label() for m in managers]
862def get_current_fig_manager():
863 """
864 Return the figure manager of the current figure.
866 The figure manager is a container for the actual backend-depended window
867 that displays the figure on screen.
869 If no current figure exists, a new one is created, and its figure
870 manager is returned.
872 Returns
873 -------
874 `.FigureManagerBase` or backend-dependent subclass thereof
875 """
876 return gcf().canvas.manager
879@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_connect)
880def connect(s, func):
881 return gcf().canvas.mpl_connect(s, func)
884@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_disconnect)
885def disconnect(cid):
886 return gcf().canvas.mpl_disconnect(cid)
889def close(fig=None):
890 """
891 Close a figure window.
893 Parameters
894 ----------
895 fig : None or int or str or `.Figure`
896 The figure to close. There are a number of ways to specify this:
898 - *None*: the current figure
899 - `.Figure`: the given `.Figure` instance
900 - ``int``: a figure number
901 - ``str``: a figure name
902 - 'all': all figures
904 """
905 if fig is None:
906 manager = _pylab_helpers.Gcf.get_active()
907 if manager is None:
908 return
909 else:
910 _pylab_helpers.Gcf.destroy(manager)
911 elif fig == 'all':
912 _pylab_helpers.Gcf.destroy_all()
913 elif isinstance(fig, int):
914 _pylab_helpers.Gcf.destroy(fig)
915 elif hasattr(fig, 'int'):
916 # if we are dealing with a type UUID, we
917 # can use its integer representation
918 _pylab_helpers.Gcf.destroy(fig.int)
919 elif isinstance(fig, str):
920 all_labels = get_figlabels()
921 if fig in all_labels:
922 num = get_fignums()[all_labels.index(fig)]
923 _pylab_helpers.Gcf.destroy(num)
924 elif isinstance(fig, Figure):
925 _pylab_helpers.Gcf.destroy_fig(fig)
926 else:
927 raise TypeError("close() argument must be a Figure, an int, a string, "
928 "or None, not %s" % type(fig))
931def clf():
932 """Clear the current figure."""
933 gcf().clear()
936def draw():
937 """
938 Redraw the current figure.
940 This is used to update a figure that has been altered, but not
941 automatically re-drawn. If interactive mode is on (via `.ion()`), this
942 should be only rarely needed, but there may be ways to modify the state of
943 a figure without marking it as "stale". Please report these cases as bugs.
945 This is equivalent to calling ``fig.canvas.draw_idle()``, where ``fig`` is
946 the current figure.
948 See Also
949 --------
950 .FigureCanvasBase.draw_idle
951 .FigureCanvasBase.draw
952 """
953 gcf().canvas.draw_idle()
956@_copy_docstring_and_deprecators(Figure.savefig)
957def savefig(*args, **kwargs):
958 fig = gcf()
959 res = fig.savefig(*args, **kwargs)
960 fig.canvas.draw_idle() # Need this if 'transparent=True', to reset colors.
961 return res
964## Putting things in figures ##
967def figlegend(*args, **kwargs):
968 return gcf().legend(*args, **kwargs)
969if Figure.legend.__doc__:
970 figlegend.__doc__ = Figure.legend.__doc__ \
971 .replace(" legend(", " figlegend(") \
972 .replace("fig.legend(", "plt.figlegend(") \
973 .replace("ax.plot(", "plt.plot(")
976## Axes ##
978@_docstring.dedent_interpd
979def axes(arg=None, **kwargs):
980 """
981 Add an Axes to the current figure and make it the current Axes.
983 Call signatures::
985 plt.axes()
986 plt.axes(rect, projection=None, polar=False, **kwargs)
987 plt.axes(ax)
989 Parameters
990 ----------
991 arg : None or 4-tuple
992 The exact behavior of this function depends on the type:
994 - *None*: A new full window Axes is added using
995 ``subplot(**kwargs)``.
996 - 4-tuple of floats *rect* = ``[left, bottom, width, height]``.
997 A new Axes is added with dimensions *rect* in normalized
998 (0, 1) units using `~.Figure.add_axes` on the current figure.
1000 projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
1001'polar', 'rectilinear', str}, optional
1002 The projection type of the `~.axes.Axes`. *str* is the name of
1003 a custom projection, see `~matplotlib.projections`. The default
1004 None results in a 'rectilinear' projection.
1006 polar : bool, default: False
1007 If True, equivalent to projection='polar'.
1009 sharex, sharey : `~.axes.Axes`, optional
1010 Share the x or y `~matplotlib.axis` with sharex and/or sharey.
1011 The axis will have the same limits, ticks, and scale as the axis
1012 of the shared Axes.
1014 label : str
1015 A label for the returned Axes.
1017 Returns
1018 -------
1019 `~.axes.Axes`, or a subclass of `~.axes.Axes`
1020 The returned axes class depends on the projection used. It is
1021 `~.axes.Axes` if rectilinear projection is used and
1022 `.projections.polar.PolarAxes` if polar projection is used.
1024 Other Parameters
1025 ----------------
1026 **kwargs
1027 This method also takes the keyword arguments for
1028 the returned Axes class. The keyword arguments for the
1029 rectilinear Axes class `~.axes.Axes` can be found in
1030 the following table but there might also be other keyword
1031 arguments if another projection is used, see the actual Axes
1032 class.
1034 %(Axes:kwdoc)s
1036 Notes
1037 -----
1038 If the figure already has an Axes with key (*args*,
1039 *kwargs*) then it will simply make that axes current and
1040 return it. This behavior is deprecated. Meanwhile, if you do
1041 not want this behavior (i.e., you want to force the creation of a
1042 new axes), you must use a unique set of args and kwargs. The Axes
1043 *label* attribute has been exposed for this purpose: if you want
1044 two Axes that are otherwise identical to be added to the figure,
1045 make sure you give them unique labels.
1047 See Also
1048 --------
1049 .Figure.add_axes
1050 .pyplot.subplot
1051 .Figure.add_subplot
1052 .Figure.subplots
1053 .pyplot.subplots
1055 Examples
1056 --------
1057 ::
1059 # Creating a new full window Axes
1060 plt.axes()
1062 # Creating a new Axes with specified dimensions and a grey background
1063 plt.axes((left, bottom, width, height), facecolor='grey')
1064 """
1065 fig = gcf()
1066 pos = kwargs.pop('position', None)
1067 if arg is None:
1068 if pos is None:
1069 return fig.add_subplot(**kwargs)
1070 else:
1071 return fig.add_axes(pos, **kwargs)
1072 else:
1073 return fig.add_axes(arg, **kwargs)
1076def delaxes(ax=None):
1077 """
1078 Remove an `~.axes.Axes` (defaulting to the current axes) from its figure.
1079 """
1080 if ax is None:
1081 ax = gca()
1082 ax.remove()
1085def sca(ax):
1086 """
1087 Set the current Axes to *ax* and the current Figure to the parent of *ax*.
1088 """
1089 figure(ax.figure)
1090 ax.figure.sca(ax)
1093def cla():
1094 """Clear the current axes."""
1095 # Not generated via boilerplate.py to allow a different docstring.
1096 return gca().cla()
1099## More ways of creating axes ##
1101@_docstring.dedent_interpd
1102def subplot(*args, **kwargs):
1103 """
1104 Add an Axes to the current figure or retrieve an existing Axes.
1106 This is a wrapper of `.Figure.add_subplot` which provides additional
1107 behavior when working with the implicit API (see the notes section).
1109 Call signatures::
1111 subplot(nrows, ncols, index, **kwargs)
1112 subplot(pos, **kwargs)
1113 subplot(**kwargs)
1114 subplot(ax)
1116 Parameters
1117 ----------
1118 *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
1119 The position of the subplot described by one of
1121 - Three integers (*nrows*, *ncols*, *index*). The subplot will take the
1122 *index* position on a grid with *nrows* rows and *ncols* columns.
1123 *index* starts at 1 in the upper left corner and increases to the
1124 right. *index* can also be a two-tuple specifying the (*first*,
1125 *last*) indices (1-based, and including *last*) of the subplot, e.g.,
1126 ``fig.add_subplot(3, 1, (1, 2))`` makes a subplot that spans the
1127 upper 2/3 of the figure.
1128 - A 3-digit integer. The digits are interpreted as if given separately
1129 as three single-digit integers, i.e. ``fig.add_subplot(235)`` is the
1130 same as ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
1131 if there are no more than 9 subplots.
1132 - A `.SubplotSpec`.
1134 projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
1135'polar', 'rectilinear', str}, optional
1136 The projection type of the subplot (`~.axes.Axes`). *str* is the name
1137 of a custom projection, see `~matplotlib.projections`. The default
1138 None results in a 'rectilinear' projection.
1140 polar : bool, default: False
1141 If True, equivalent to projection='polar'.
1143 sharex, sharey : `~.axes.Axes`, optional
1144 Share the x or y `~matplotlib.axis` with sharex and/or sharey. The
1145 axis will have the same limits, ticks, and scale as the axis of the
1146 shared axes.
1148 label : str
1149 A label for the returned axes.
1151 Returns
1152 -------
1153 `.axes.SubplotBase`, or another subclass of `~.axes.Axes`
1155 The axes of the subplot. The returned axes base class depends on
1156 the projection used. It is `~.axes.Axes` if rectilinear projection
1157 is used and `.projections.polar.PolarAxes` if polar projection
1158 is used. The returned axes is then a subplot subclass of the
1159 base class.
1161 Other Parameters
1162 ----------------
1163 **kwargs
1164 This method also takes the keyword arguments for the returned axes
1165 base class; except for the *figure* argument. The keyword arguments
1166 for the rectilinear base class `~.axes.Axes` can be found in
1167 the following table but there might also be other keyword
1168 arguments if another projection is used.
1170 %(Axes:kwdoc)s
1172 Notes
1173 -----
1174 Creating a new Axes will delete any preexisting Axes that
1175 overlaps with it beyond sharing a boundary::
1177 import matplotlib.pyplot as plt
1178 # plot a line, implicitly creating a subplot(111)
1179 plt.plot([1, 2, 3])
1180 # now create a subplot which represents the top plot of a grid
1181 # with 2 rows and 1 column. Since this subplot will overlap the
1182 # first, the plot (and its axes) previously created, will be removed
1183 plt.subplot(211)
1185 If you do not want this behavior, use the `.Figure.add_subplot` method
1186 or the `.pyplot.axes` function instead.
1188 If no *kwargs* are passed and there exists an Axes in the location
1189 specified by *args* then that Axes will be returned rather than a new
1190 Axes being created.
1192 If *kwargs* are passed and there exists an Axes in the location
1193 specified by *args*, the projection type is the same, and the
1194 *kwargs* match with the existing Axes, then the existing Axes is
1195 returned. Otherwise a new Axes is created with the specified
1196 parameters. We save a reference to the *kwargs* which we use
1197 for this comparison. If any of the values in *kwargs* are
1198 mutable we will not detect the case where they are mutated.
1199 In these cases we suggest using `.Figure.add_subplot` and the
1200 explicit Axes API rather than the implicit pyplot API.
1202 See Also
1203 --------
1204 .Figure.add_subplot
1205 .pyplot.subplots
1206 .pyplot.axes
1207 .Figure.subplots
1209 Examples
1210 --------
1211 ::
1213 plt.subplot(221)
1215 # equivalent but more general
1216 ax1 = plt.subplot(2, 2, 1)
1218 # add a subplot with no frame
1219 ax2 = plt.subplot(222, frameon=False)
1221 # add a polar subplot
1222 plt.subplot(223, projection='polar')
1224 # add a red subplot that shares the x-axis with ax1
1225 plt.subplot(224, sharex=ax1, facecolor='red')
1227 # delete ax2 from the figure
1228 plt.delaxes(ax2)
1230 # add ax2 to the figure again
1231 plt.subplot(ax2)
1233 # make the first axes "current" again
1234 plt.subplot(221)
1236 """
1237 # Here we will only normalize `polar=True` vs `projection='polar'` and let
1238 # downstream code deal with the rest.
1239 unset = object()
1240 projection = kwargs.get('projection', unset)
1241 polar = kwargs.pop('polar', unset)
1242 if polar is not unset and polar:
1243 # if we got mixed messages from the user, raise
1244 if projection is not unset and projection != 'polar':
1245 raise ValueError(
1246 f"polar={polar}, yet projection={projection!r}. "
1247 "Only one of these arguments should be supplied."
1248 )
1249 kwargs['projection'] = projection = 'polar'
1251 # if subplot called without arguments, create subplot(1, 1, 1)
1252 if len(args) == 0:
1253 args = (1, 1, 1)
1255 # This check was added because it is very easy to type subplot(1, 2, False)
1256 # when subplots(1, 2, False) was intended (sharex=False, that is). In most
1257 # cases, no error will ever occur, but mysterious behavior can result
1258 # because what was intended to be the sharex argument is instead treated as
1259 # a subplot index for subplot()
1260 if len(args) >= 3 and isinstance(args[2], bool):
1261 _api.warn_external("The subplot index argument to subplot() appears "
1262 "to be a boolean. Did you intend to use "
1263 "subplots()?")
1264 # Check for nrows and ncols, which are not valid subplot args:
1265 if 'nrows' in kwargs or 'ncols' in kwargs:
1266 raise TypeError("subplot() got an unexpected keyword argument 'ncols' "
1267 "and/or 'nrows'. Did you intend to call subplots()?")
1269 fig = gcf()
1271 # First, search for an existing subplot with a matching spec.
1272 key = SubplotSpec._from_subplot_args(fig, args)
1274 for ax in fig.axes:
1275 # if we found an Axes at the position sort out if we can re-use it
1276 if hasattr(ax, 'get_subplotspec') and ax.get_subplotspec() == key:
1277 # if the user passed no kwargs, re-use
1278 if kwargs == {}:
1279 break
1280 # if the axes class and kwargs are identical, reuse
1281 elif ax._projection_init == fig._process_projection_requirements(
1282 *args, **kwargs
1283 ):
1284 break
1285 else:
1286 # we have exhausted the known Axes and none match, make a new one!
1287 ax = fig.add_subplot(*args, **kwargs)
1289 fig.sca(ax)
1291 axes_to_delete = [other for other in fig.axes
1292 if other != ax and ax.bbox.fully_overlaps(other.bbox)]
1293 if axes_to_delete:
1294 _api.warn_deprecated(
1295 "3.6", message="Auto-removal of overlapping axes is deprecated "
1296 "since %(since)s and will be removed %(removal)s; explicitly call "
1297 "ax.remove() as needed.")
1298 for ax_to_del in axes_to_delete:
1299 delaxes(ax_to_del)
1301 return ax
1304def subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True,
1305 width_ratios=None, height_ratios=None,
1306 subplot_kw=None, gridspec_kw=None, **fig_kw):
1307 """
1308 Create a figure and a set of subplots.
1310 This utility wrapper makes it convenient to create common layouts of
1311 subplots, including the enclosing figure object, in a single call.
1313 Parameters
1314 ----------
1315 nrows, ncols : int, default: 1
1316 Number of rows/columns of the subplot grid.
1318 sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
1319 Controls sharing of properties among x (*sharex*) or y (*sharey*)
1320 axes:
1322 - True or 'all': x- or y-axis will be shared among all subplots.
1323 - False or 'none': each subplot x- or y-axis will be independent.
1324 - 'row': each subplot row will share an x- or y-axis.
1325 - 'col': each subplot column will share an x- or y-axis.
1327 When subplots have a shared x-axis along a column, only the x tick
1328 labels of the bottom subplot are created. Similarly, when subplots
1329 have a shared y-axis along a row, only the y tick labels of the first
1330 column subplot are created. To later turn other subplots' ticklabels
1331 on, use `~matplotlib.axes.Axes.tick_params`.
1333 When subplots have a shared axis that has units, calling
1334 `~matplotlib.axis.Axis.set_units` will update each axis with the
1335 new units.
1337 squeeze : bool, default: True
1338 - If True, extra dimensions are squeezed out from the returned
1339 array of `~matplotlib.axes.Axes`:
1341 - if only one subplot is constructed (nrows=ncols=1), the
1342 resulting single Axes object is returned as a scalar.
1343 - for Nx1 or 1xM subplots, the returned object is a 1D numpy
1344 object array of Axes objects.
1345 - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
1347 - If False, no squeezing at all is done: the returned Axes object is
1348 always a 2D array containing Axes instances, even if it ends up
1349 being 1x1.
1351 width_ratios : array-like of length *ncols*, optional
1352 Defines the relative widths of the columns. Each column gets a
1353 relative width of ``width_ratios[i] / sum(width_ratios)``.
1354 If not given, all columns will have the same width. Equivalent
1355 to ``gridspec_kw={'width_ratios': [...]}``.
1357 height_ratios : array-like of length *nrows*, optional
1358 Defines the relative heights of the rows. Each row gets a
1359 relative height of ``height_ratios[i] / sum(height_ratios)``.
1360 If not given, all rows will have the same height. Convenience
1361 for ``gridspec_kw={'height_ratios': [...]}``.
1363 subplot_kw : dict, optional
1364 Dict with keywords passed to the
1365 `~matplotlib.figure.Figure.add_subplot` call used to create each
1366 subplot.
1368 gridspec_kw : dict, optional
1369 Dict with keywords passed to the `~matplotlib.gridspec.GridSpec`
1370 constructor used to create the grid the subplots are placed on.
1372 **fig_kw
1373 All additional keyword arguments are passed to the
1374 `.pyplot.figure` call.
1376 Returns
1377 -------
1378 fig : `.Figure`
1380 ax : `~.axes.Axes` or array of Axes
1381 *ax* can be either a single `~.axes.Axes` object, or an array of Axes
1382 objects if more than one subplot was created. The dimensions of the
1383 resulting array can be controlled with the squeeze keyword, see above.
1385 Typical idioms for handling the return value are::
1387 # using the variable ax for single a Axes
1388 fig, ax = plt.subplots()
1390 # using the variable axs for multiple Axes
1391 fig, axs = plt.subplots(2, 2)
1393 # using tuple unpacking for multiple Axes
1394 fig, (ax1, ax2) = plt.subplots(1, 2)
1395 fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
1397 The names ``ax`` and pluralized ``axs`` are preferred over ``axes``
1398 because for the latter it's not clear if it refers to a single
1399 `~.axes.Axes` instance or a collection of these.
1401 See Also
1402 --------
1403 .pyplot.figure
1404 .pyplot.subplot
1405 .pyplot.axes
1406 .Figure.subplots
1407 .Figure.add_subplot
1409 Examples
1410 --------
1411 ::
1413 # First create some toy data:
1414 x = np.linspace(0, 2*np.pi, 400)
1415 y = np.sin(x**2)
1417 # Create just a figure and only one subplot
1418 fig, ax = plt.subplots()
1419 ax.plot(x, y)
1420 ax.set_title('Simple plot')
1422 # Create two subplots and unpack the output array immediately
1423 f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
1424 ax1.plot(x, y)
1425 ax1.set_title('Sharing Y axis')
1426 ax2.scatter(x, y)
1428 # Create four polar axes and access them through the returned array
1429 fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
1430 axs[0, 0].plot(x, y)
1431 axs[1, 1].scatter(x, y)
1433 # Share a X axis with each column of subplots
1434 plt.subplots(2, 2, sharex='col')
1436 # Share a Y axis with each row of subplots
1437 plt.subplots(2, 2, sharey='row')
1439 # Share both X and Y axes with all subplots
1440 plt.subplots(2, 2, sharex='all', sharey='all')
1442 # Note that this is the same as
1443 plt.subplots(2, 2, sharex=True, sharey=True)
1445 # Create figure number 10 with a single subplot
1446 # and clears it if it already exists.
1447 fig, ax = plt.subplots(num=10, clear=True)
1449 """
1450 fig = figure(**fig_kw)
1451 axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
1452 squeeze=squeeze, subplot_kw=subplot_kw,
1453 gridspec_kw=gridspec_kw, height_ratios=height_ratios,
1454 width_ratios=width_ratios)
1455 return fig, axs
1458def subplot_mosaic(mosaic, *, sharex=False, sharey=False,
1459 width_ratios=None, height_ratios=None, empty_sentinel='.',
1460 subplot_kw=None, gridspec_kw=None, **fig_kw):
1461 """
1462 Build a layout of Axes based on ASCII art or nested lists.
1464 This is a helper function to build complex GridSpec layouts visually.
1466 .. note::
1468 This API is provisional and may be revised in the future based on
1469 early user feedback.
1471 See :doc:`/tutorials/provisional/mosaic`
1472 for an example and full API documentation
1474 Parameters
1475 ----------
1476 mosaic : list of list of {hashable or nested} or str
1478 A visual layout of how you want your Axes to be arranged
1479 labeled as strings. For example ::
1481 x = [['A panel', 'A panel', 'edge'],
1482 ['C panel', '.', 'edge']]
1484 produces 4 axes:
1486 - 'A panel' which is 1 row high and spans the first two columns
1487 - 'edge' which is 2 rows high and is on the right edge
1488 - 'C panel' which in 1 row and 1 column wide in the bottom left
1489 - a blank space 1 row and 1 column wide in the bottom center
1491 Any of the entries in the layout can be a list of lists
1492 of the same form to create nested layouts.
1494 If input is a str, then it must be of the form ::
1496 '''
1497 AAE
1498 C.E
1499 '''
1501 where each character is a column and each line is a row.
1502 This only allows only single character Axes labels and does
1503 not allow nesting but is very terse.
1505 sharex, sharey : bool, default: False
1506 If True, the x-axis (*sharex*) or y-axis (*sharey*) will be shared
1507 among all subplots. In that case, tick label visibility and axis units
1508 behave as for `subplots`. If False, each subplot's x- or y-axis will
1509 be independent.
1511 width_ratios : array-like of length *ncols*, optional
1512 Defines the relative widths of the columns. Each column gets a
1513 relative width of ``width_ratios[i] / sum(width_ratios)``.
1514 If not given, all columns will have the same width. Convenience
1515 for ``gridspec_kw={'width_ratios': [...]}``.
1517 height_ratios : array-like of length *nrows*, optional
1518 Defines the relative heights of the rows. Each row gets a
1519 relative height of ``height_ratios[i] / sum(height_ratios)``.
1520 If not given, all rows will have the same height. Convenience
1521 for ``gridspec_kw={'height_ratios': [...]}``.
1523 empty_sentinel : object, optional
1524 Entry in the layout to mean "leave this space empty". Defaults
1525 to ``'.'``. Note, if *layout* is a string, it is processed via
1526 `inspect.cleandoc` to remove leading white space, which may
1527 interfere with using white-space as the empty sentinel.
1529 subplot_kw : dict, optional
1530 Dictionary with keywords passed to the `.Figure.add_subplot` call
1531 used to create each subplot.
1533 gridspec_kw : dict, optional
1534 Dictionary with keywords passed to the `.GridSpec` constructor used
1535 to create the grid the subplots are placed on.
1537 **fig_kw
1538 All additional keyword arguments are passed to the
1539 `.pyplot.figure` call.
1541 Returns
1542 -------
1543 fig : `.Figure`
1544 The new figure
1546 dict[label, Axes]
1547 A dictionary mapping the labels to the Axes objects. The order of
1548 the axes is left-to-right and top-to-bottom of their position in the
1549 total layout.
1551 """
1552 fig = figure(**fig_kw)
1553 ax_dict = fig.subplot_mosaic(
1554 mosaic, sharex=sharex, sharey=sharey,
1555 height_ratios=height_ratios, width_ratios=width_ratios,
1556 subplot_kw=subplot_kw, gridspec_kw=gridspec_kw,
1557 empty_sentinel=empty_sentinel
1558 )
1559 return fig, ax_dict
1562def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):
1563 """
1564 Create a subplot at a specific location inside a regular grid.
1566 Parameters
1567 ----------
1568 shape : (int, int)
1569 Number of rows and of columns of the grid in which to place axis.
1570 loc : (int, int)
1571 Row number and column number of the axis location within the grid.
1572 rowspan : int, default: 1
1573 Number of rows for the axis to span downwards.
1574 colspan : int, default: 1
1575 Number of columns for the axis to span to the right.
1576 fig : `.Figure`, optional
1577 Figure to place the subplot in. Defaults to the current figure.
1578 **kwargs
1579 Additional keyword arguments are handed to `~.Figure.add_subplot`.
1581 Returns
1582 -------
1583 `.axes.SubplotBase`, or another subclass of `~.axes.Axes`
1585 The axes of the subplot. The returned axes base class depends on the
1586 projection used. It is `~.axes.Axes` if rectilinear projection is used
1587 and `.projections.polar.PolarAxes` if polar projection is used. The
1588 returned axes is then a subplot subclass of the base class.
1590 Notes
1591 -----
1592 The following call ::
1594 ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan)
1596 is identical to ::
1598 fig = gcf()
1599 gs = fig.add_gridspec(nrows, ncols)
1600 ax = fig.add_subplot(gs[row:row+rowspan, col:col+colspan])
1601 """
1603 if fig is None:
1604 fig = gcf()
1606 rows, cols = shape
1607 gs = GridSpec._check_gridspec_exists(fig, rows, cols)
1609 subplotspec = gs.new_subplotspec(loc, rowspan=rowspan, colspan=colspan)
1610 ax = fig.add_subplot(subplotspec, **kwargs)
1612 axes_to_delete = [other for other in fig.axes
1613 if other != ax and ax.bbox.fully_overlaps(other.bbox)]
1614 if axes_to_delete:
1615 _api.warn_deprecated(
1616 "3.6", message="Auto-removal of overlapping axes is deprecated "
1617 "since %(since)s and will be removed %(removal)s; explicitly call "
1618 "ax.remove() as needed.")
1619 for ax_to_del in axes_to_delete:
1620 delaxes(ax_to_del)
1622 return ax
1625def twinx(ax=None):
1626 """
1627 Make and return a second axes that shares the *x*-axis. The new axes will
1628 overlay *ax* (or the current axes if *ax* is *None*), and its ticks will be
1629 on the right.
1631 Examples
1632 --------
1633 :doc:`/gallery/subplots_axes_and_figures/two_scales`
1634 """
1635 if ax is None:
1636 ax = gca()
1637 ax1 = ax.twinx()
1638 return ax1
1641def twiny(ax=None):
1642 """
1643 Make and return a second axes that shares the *y*-axis. The new axes will
1644 overlay *ax* (or the current axes if *ax* is *None*), and its ticks will be
1645 on the top.
1647 Examples
1648 --------
1649 :doc:`/gallery/subplots_axes_and_figures/two_scales`
1650 """
1651 if ax is None:
1652 ax = gca()
1653 ax1 = ax.twiny()
1654 return ax1
1657def subplot_tool(targetfig=None):
1658 """
1659 Launch a subplot tool window for a figure.
1661 Returns
1662 -------
1663 `matplotlib.widgets.SubplotTool`
1664 """
1665 if targetfig is None:
1666 targetfig = gcf()
1667 tb = targetfig.canvas.manager.toolbar
1668 if hasattr(tb, "configure_subplots"): # toolbar2
1669 return tb.configure_subplots()
1670 elif hasattr(tb, "trigger_tool"): # toolmanager
1671 return tb.trigger_tool("subplots")
1672 else:
1673 raise ValueError("subplot_tool can only be launched for figures with "
1674 "an associated toolbar")
1677def box(on=None):
1678 """
1679 Turn the axes box on or off on the current axes.
1681 Parameters
1682 ----------
1683 on : bool or None
1684 The new `~matplotlib.axes.Axes` box state. If ``None``, toggle
1685 the state.
1687 See Also
1688 --------
1689 :meth:`matplotlib.axes.Axes.set_frame_on`
1690 :meth:`matplotlib.axes.Axes.get_frame_on`
1691 """
1692 ax = gca()
1693 if on is None:
1694 on = not ax.get_frame_on()
1695 ax.set_frame_on(on)
1697## Axis ##
1700def xlim(*args, **kwargs):
1701 """
1702 Get or set the x limits of the current axes.
1704 Call signatures::
1706 left, right = xlim() # return the current xlim
1707 xlim((left, right)) # set the xlim to left, right
1708 xlim(left, right) # set the xlim to left, right
1710 If you do not specify args, you can pass *left* or *right* as kwargs,
1711 i.e.::
1713 xlim(right=3) # adjust the right leaving left unchanged
1714 xlim(left=1) # adjust the left leaving right unchanged
1716 Setting limits turns autoscaling off for the x-axis.
1718 Returns
1719 -------
1720 left, right
1721 A tuple of the new x-axis limits.
1723 Notes
1724 -----
1725 Calling this function with no arguments (e.g. ``xlim()``) is the pyplot
1726 equivalent of calling `~.Axes.get_xlim` on the current axes.
1727 Calling this function with arguments is the pyplot equivalent of calling
1728 `~.Axes.set_xlim` on the current axes. All arguments are passed though.
1729 """
1730 ax = gca()
1731 if not args and not kwargs:
1732 return ax.get_xlim()
1733 ret = ax.set_xlim(*args, **kwargs)
1734 return ret
1737def ylim(*args, **kwargs):
1738 """
1739 Get or set the y-limits of the current axes.
1741 Call signatures::
1743 bottom, top = ylim() # return the current ylim
1744 ylim((bottom, top)) # set the ylim to bottom, top
1745 ylim(bottom, top) # set the ylim to bottom, top
1747 If you do not specify args, you can alternatively pass *bottom* or
1748 *top* as kwargs, i.e.::
1750 ylim(top=3) # adjust the top leaving bottom unchanged
1751 ylim(bottom=1) # adjust the bottom leaving top unchanged
1753 Setting limits turns autoscaling off for the y-axis.
1755 Returns
1756 -------
1757 bottom, top
1758 A tuple of the new y-axis limits.
1760 Notes
1761 -----
1762 Calling this function with no arguments (e.g. ``ylim()``) is the pyplot
1763 equivalent of calling `~.Axes.get_ylim` on the current axes.
1764 Calling this function with arguments is the pyplot equivalent of calling
1765 `~.Axes.set_ylim` on the current axes. All arguments are passed though.
1766 """
1767 ax = gca()
1768 if not args and not kwargs:
1769 return ax.get_ylim()
1770 ret = ax.set_ylim(*args, **kwargs)
1771 return ret
1774def xticks(ticks=None, labels=None, *, minor=False, **kwargs):
1775 """
1776 Get or set the current tick locations and labels of the x-axis.
1778 Pass no arguments to return the current values without modifying them.
1780 Parameters
1781 ----------
1782 ticks : array-like, optional
1783 The list of xtick locations. Passing an empty list removes all xticks.
1784 labels : array-like, optional
1785 The labels to place at the given *ticks* locations. This argument can
1786 only be passed if *ticks* is passed as well.
1787 minor : bool, default: False
1788 If ``False``, get/set the major ticks/labels; if ``True``, the minor
1789 ticks/labels.
1790 **kwargs
1791 `.Text` properties can be used to control the appearance of the labels.
1793 Returns
1794 -------
1795 locs
1796 The list of xtick locations.
1797 labels
1798 The list of xlabel `.Text` objects.
1800 Notes
1801 -----
1802 Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
1803 equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
1804 the current axes.
1805 Calling this function with arguments is the pyplot equivalent of calling
1806 `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
1808 Examples
1809 --------
1810 >>> locs, labels = xticks() # Get the current locations and labels.
1811 >>> xticks(np.arange(0, 1, step=0.2)) # Set label locations.
1812 >>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
1813 >>> xticks([0, 1, 2], ['January', 'February', 'March'],
1814 ... rotation=20) # Set text labels and properties.
1815 >>> xticks([]) # Disable xticks.
1816 """
1817 ax = gca()
1819 if ticks is None:
1820 locs = ax.get_xticks(minor=minor)
1821 if labels is not None:
1822 raise TypeError("xticks(): Parameter 'labels' can't be set "
1823 "without setting 'ticks'")
1824 else:
1825 locs = ax.set_xticks(ticks, minor=minor)
1827 if labels is None:
1828 labels = ax.get_xticklabels(minor=minor)
1829 for l in labels:
1830 l._internal_update(kwargs)
1831 else:
1832 labels = ax.set_xticklabels(labels, minor=minor, **kwargs)
1834 return locs, labels
1837def yticks(ticks=None, labels=None, *, minor=False, **kwargs):
1838 """
1839 Get or set the current tick locations and labels of the y-axis.
1841 Pass no arguments to return the current values without modifying them.
1843 Parameters
1844 ----------
1845 ticks : array-like, optional
1846 The list of ytick locations. Passing an empty list removes all yticks.
1847 labels : array-like, optional
1848 The labels to place at the given *ticks* locations. This argument can
1849 only be passed if *ticks* is passed as well.
1850 minor : bool, default: False
1851 If ``False``, get/set the major ticks/labels; if ``True``, the minor
1852 ticks/labels.
1853 **kwargs
1854 `.Text` properties can be used to control the appearance of the labels.
1856 Returns
1857 -------
1858 locs
1859 The list of ytick locations.
1860 labels
1861 The list of ylabel `.Text` objects.
1863 Notes
1864 -----
1865 Calling this function with no arguments (e.g. ``yticks()``) is the pyplot
1866 equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on
1867 the current axes.
1868 Calling this function with arguments is the pyplot equivalent of calling
1869 `~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current axes.
1871 Examples
1872 --------
1873 >>> locs, labels = yticks() # Get the current locations and labels.
1874 >>> yticks(np.arange(0, 1, step=0.2)) # Set label locations.
1875 >>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
1876 >>> yticks([0, 1, 2], ['January', 'February', 'March'],
1877 ... rotation=45) # Set text labels and properties.
1878 >>> yticks([]) # Disable yticks.
1879 """
1880 ax = gca()
1882 if ticks is None:
1883 locs = ax.get_yticks(minor=minor)
1884 if labels is not None:
1885 raise TypeError("yticks(): Parameter 'labels' can't be set "
1886 "without setting 'ticks'")
1887 else:
1888 locs = ax.set_yticks(ticks, minor=minor)
1890 if labels is None:
1891 labels = ax.get_yticklabels(minor=minor)
1892 for l in labels:
1893 l._internal_update(kwargs)
1894 else:
1895 labels = ax.set_yticklabels(labels, minor=minor, **kwargs)
1897 return locs, labels
1900def rgrids(radii=None, labels=None, angle=None, fmt=None, **kwargs):
1901 """
1902 Get or set the radial gridlines on the current polar plot.
1904 Call signatures::
1906 lines, labels = rgrids()
1907 lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs)
1909 When called with no arguments, `.rgrids` simply returns the tuple
1910 (*lines*, *labels*). When called with arguments, the labels will
1911 appear at the specified radial distances and angle.
1913 Parameters
1914 ----------
1915 radii : tuple with floats
1916 The radii for the radial gridlines
1918 labels : tuple with strings or None
1919 The labels to use at each radial gridline. The
1920 `matplotlib.ticker.ScalarFormatter` will be used if None.
1922 angle : float
1923 The angular position of the radius labels in degrees.
1925 fmt : str or None
1926 Format string used in `matplotlib.ticker.FormatStrFormatter`.
1927 For example '%f'.
1929 Returns
1930 -------
1931 lines : list of `.lines.Line2D`
1932 The radial gridlines.
1934 labels : list of `.text.Text`
1935 The tick labels.
1937 Other Parameters
1938 ----------------
1939 **kwargs
1940 *kwargs* are optional `.Text` properties for the labels.
1942 See Also
1943 --------
1944 .pyplot.thetagrids
1945 .projections.polar.PolarAxes.set_rgrids
1946 .Axis.get_gridlines
1947 .Axis.get_ticklabels
1949 Examples
1950 --------
1951 ::
1953 # set the locations of the radial gridlines
1954 lines, labels = rgrids( (0.25, 0.5, 1.0) )
1956 # set the locations and labels of the radial gridlines
1957 lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ))
1958 """
1959 ax = gca()
1960 if not isinstance(ax, PolarAxes):
1961 raise RuntimeError('rgrids only defined for polar axes')
1962 if all(p is None for p in [radii, labels, angle, fmt]) and not kwargs:
1963 lines = ax.yaxis.get_gridlines()
1964 labels = ax.yaxis.get_ticklabels()
1965 else:
1966 lines, labels = ax.set_rgrids(
1967 radii, labels=labels, angle=angle, fmt=fmt, **kwargs)
1968 return lines, labels
1971def thetagrids(angles=None, labels=None, fmt=None, **kwargs):
1972 """
1973 Get or set the theta gridlines on the current polar plot.
1975 Call signatures::
1977 lines, labels = thetagrids()
1978 lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs)
1980 When called with no arguments, `.thetagrids` simply returns the tuple
1981 (*lines*, *labels*). When called with arguments, the labels will
1982 appear at the specified angles.
1984 Parameters
1985 ----------
1986 angles : tuple with floats, degrees
1987 The angles of the theta gridlines.
1989 labels : tuple with strings or None
1990 The labels to use at each radial gridline. The
1991 `.projections.polar.ThetaFormatter` will be used if None.
1993 fmt : str or None
1994 Format string used in `matplotlib.ticker.FormatStrFormatter`.
1995 For example '%f'. Note that the angle in radians will be used.
1997 Returns
1998 -------
1999 lines : list of `.lines.Line2D`
2000 The theta gridlines.
2002 labels : list of `.text.Text`
2003 The tick labels.
2005 Other Parameters
2006 ----------------
2007 **kwargs
2008 *kwargs* are optional `.Text` properties for the labels.
2010 See Also
2011 --------
2012 .pyplot.rgrids
2013 .projections.polar.PolarAxes.set_thetagrids
2014 .Axis.get_gridlines
2015 .Axis.get_ticklabels
2017 Examples
2018 --------
2019 ::
2021 # set the locations of the angular gridlines
2022 lines, labels = thetagrids(range(45, 360, 90))
2024 # set the locations and labels of the angular gridlines
2025 lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE'))
2026 """
2027 ax = gca()
2028 if not isinstance(ax, PolarAxes):
2029 raise RuntimeError('thetagrids only defined for polar axes')
2030 if all(param is None for param in [angles, labels, fmt]) and not kwargs:
2031 lines = ax.xaxis.get_ticklines()
2032 labels = ax.xaxis.get_ticklabels()
2033 else:
2034 lines, labels = ax.set_thetagrids(angles,
2035 labels=labels, fmt=fmt, **kwargs)
2036 return lines, labels
2039_NON_PLOT_COMMANDS = {
2040 'connect', 'disconnect', 'get_current_fig_manager', 'ginput',
2041 'new_figure_manager', 'waitforbuttonpress'}
2044def get_plot_commands():
2045 """
2046 Get a sorted list of all of the plotting commands.
2047 """
2048 # This works by searching for all functions in this module and removing
2049 # a few hard-coded exclusions, as well as all of the colormap-setting
2050 # functions, and anything marked as private with a preceding underscore.
2051 exclude = {'colormaps', 'colors', 'get_plot_commands',
2052 *_NON_PLOT_COMMANDS, *colormaps}
2053 this_module = inspect.getmodule(get_plot_commands)
2054 return sorted(
2055 name for name, obj in globals().items()
2056 if not name.startswith('_') and name not in exclude
2057 and inspect.isfunction(obj)
2058 and inspect.getmodule(obj) is this_module)
2061## Plotting part 1: manually generated functions and wrappers ##
2064@_copy_docstring_and_deprecators(Figure.colorbar)
2065def colorbar(mappable=None, cax=None, ax=None, **kwargs):
2066 if mappable is None:
2067 mappable = gci()
2068 if mappable is None:
2069 raise RuntimeError('No mappable was found to use for colorbar '
2070 'creation. First define a mappable such as '
2071 'an image (with imshow) or a contour set ('
2072 'with contourf).')
2073 ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kwargs)
2074 return ret
2077def clim(vmin=None, vmax=None):
2078 """
2079 Set the color limits of the current image.
2081 If either *vmin* or *vmax* is None, the image min/max respectively
2082 will be used for color scaling.
2084 If you want to set the clim of multiple images, use
2085 `~.ScalarMappable.set_clim` on every image, for example::
2087 for im in gca().get_images():
2088 im.set_clim(0, 0.5)
2090 """
2091 im = gci()
2092 if im is None:
2093 raise RuntimeError('You must first define an image, e.g., with imshow')
2095 im.set_clim(vmin, vmax)
2098# eventually this implementation should move here, use indirection for now to
2099# avoid having two copies of the code floating around.
2100def get_cmap(name=None, lut=None):
2101 return cm._get_cmap(name=name, lut=lut)
2102get_cmap.__doc__ = cm._get_cmap.__doc__
2105def set_cmap(cmap):
2106 """
2107 Set the default colormap, and applies it to the current image if any.
2109 Parameters
2110 ----------
2111 cmap : `~matplotlib.colors.Colormap` or str
2112 A colormap instance or the name of a registered colormap.
2114 See Also
2115 --------
2116 colormaps
2117 matplotlib.cm.register_cmap
2118 matplotlib.cm.get_cmap
2119 """
2120 cmap = get_cmap(cmap)
2122 rc('image', cmap=cmap.name)
2123 im = gci()
2125 if im is not None:
2126 im.set_cmap(cmap)
2129@_copy_docstring_and_deprecators(matplotlib.image.imread)
2130def imread(fname, format=None):
2131 return matplotlib.image.imread(fname, format)
2134@_copy_docstring_and_deprecators(matplotlib.image.imsave)
2135def imsave(fname, arr, **kwargs):
2136 return matplotlib.image.imsave(fname, arr, **kwargs)
2139def matshow(A, fignum=None, **kwargs):
2140 """
2141 Display an array as a matrix in a new figure window.
2143 The origin is set at the upper left hand corner and rows (first
2144 dimension of the array) are displayed horizontally. The aspect
2145 ratio of the figure window is that of the array, unless this would
2146 make an excessively short or narrow figure.
2148 Tick labels for the xaxis are placed on top.
2150 Parameters
2151 ----------
2152 A : 2D array-like
2153 The matrix to be displayed.
2155 fignum : None or int or False
2156 If *None*, create a new figure window with automatic numbering.
2158 If a nonzero integer, draw into the figure with the given number
2159 (create it if it does not exist).
2161 If 0, use the current axes (or create one if it does not exist).
2163 .. note::
2165 Because of how `.Axes.matshow` tries to set the figure aspect
2166 ratio to be the one of the array, strange things may happen if you
2167 reuse an existing figure.
2169 Returns
2170 -------
2171 `~matplotlib.image.AxesImage`
2173 Other Parameters
2174 ----------------
2175 **kwargs : `~matplotlib.axes.Axes.imshow` arguments
2177 """
2178 A = np.asanyarray(A)
2179 if fignum == 0:
2180 ax = gca()
2181 else:
2182 # Extract actual aspect ratio of array and make appropriately sized
2183 # figure.
2184 fig = figure(fignum, figsize=figaspect(A))
2185 ax = fig.add_axes([0.15, 0.09, 0.775, 0.775])
2186 im = ax.matshow(A, **kwargs)
2187 sci(im)
2188 return im
2191def polar(*args, **kwargs):
2192 """
2193 Make a polar plot.
2195 call signature::
2197 polar(theta, r, **kwargs)
2199 Multiple *theta*, *r* arguments are supported, with format strings, as in
2200 `plot`.
2201 """
2202 # If an axis already exists, check if it has a polar projection
2203 if gcf().get_axes():
2204 ax = gca()
2205 if not isinstance(ax, PolarAxes):
2206 _api.warn_external('Trying to create polar plot on an Axes '
2207 'that does not have a polar projection.')
2208 else:
2209 ax = axes(projection="polar")
2210 return ax.plot(*args, **kwargs)
2213# If rcParams['backend_fallback'] is true, and an interactive backend is
2214# requested, ignore rcParams['backend'] and force selection of a backend that
2215# is compatible with the current running interactive framework.
2216if (rcParams["backend_fallback"]
2217 and rcParams._get_backend_or_none() in (
2218 set(_interactive_bk) - {'WebAgg', 'nbAgg'})
2219 and cbook._get_running_interactive_framework()):
2220 dict.__setitem__(rcParams, "backend", rcsetup._auto_backend_sentinel)
2223################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
2226# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2227@_copy_docstring_and_deprecators(Figure.figimage)
2228def figimage(
2229 X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None,
2230 vmax=None, origin=None, resize=False, **kwargs):
2231 return gcf().figimage(
2232 X, xo=xo, yo=yo, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
2233 vmax=vmax, origin=origin, resize=resize, **kwargs)
2236# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2237@_copy_docstring_and_deprecators(Figure.text)
2238def figtext(x, y, s, fontdict=None, **kwargs):
2239 return gcf().text(x, y, s, fontdict=fontdict, **kwargs)
2242# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2243@_copy_docstring_and_deprecators(Figure.gca)
2244def gca():
2245 return gcf().gca()
2248# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2249@_copy_docstring_and_deprecators(Figure._gci)
2250def gci():
2251 return gcf()._gci()
2254# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2255@_copy_docstring_and_deprecators(Figure.ginput)
2256def ginput(
2257 n=1, timeout=30, show_clicks=True,
2258 mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT,
2259 mouse_stop=MouseButton.MIDDLE):
2260 return gcf().ginput(
2261 n=n, timeout=timeout, show_clicks=show_clicks,
2262 mouse_add=mouse_add, mouse_pop=mouse_pop,
2263 mouse_stop=mouse_stop)
2266# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2267@_copy_docstring_and_deprecators(Figure.subplots_adjust)
2268def subplots_adjust(
2269 left=None, bottom=None, right=None, top=None, wspace=None,
2270 hspace=None):
2271 return gcf().subplots_adjust(
2272 left=left, bottom=bottom, right=right, top=top, wspace=wspace,
2273 hspace=hspace)
2276# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2277@_copy_docstring_and_deprecators(Figure.suptitle)
2278def suptitle(t, **kwargs):
2279 return gcf().suptitle(t, **kwargs)
2282# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2283@_copy_docstring_and_deprecators(Figure.tight_layout)
2284def tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None):
2285 return gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
2288# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2289@_copy_docstring_and_deprecators(Figure.waitforbuttonpress)
2290def waitforbuttonpress(timeout=-1):
2291 return gcf().waitforbuttonpress(timeout=timeout)
2294# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2295@_copy_docstring_and_deprecators(Axes.acorr)
2296def acorr(x, *, data=None, **kwargs):
2297 return gca().acorr(
2298 x, **({"data": data} if data is not None else {}), **kwargs)
2301# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2302@_copy_docstring_and_deprecators(Axes.angle_spectrum)
2303def angle_spectrum(
2304 x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
2305 data=None, **kwargs):
2306 return gca().angle_spectrum(
2307 x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
2308 **({"data": data} if data is not None else {}), **kwargs)
2311# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2312@_copy_docstring_and_deprecators(Axes.annotate)
2313def annotate(
2314 text, xy, xytext=None, xycoords='data', textcoords=None,
2315 arrowprops=None, annotation_clip=None, **kwargs):
2316 return gca().annotate(
2317 text, xy, xytext=xytext, xycoords=xycoords,
2318 textcoords=textcoords, arrowprops=arrowprops,
2319 annotation_clip=annotation_clip, **kwargs)
2322# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2323@_copy_docstring_and_deprecators(Axes.arrow)
2324def arrow(x, y, dx, dy, **kwargs):
2325 return gca().arrow(x, y, dx, dy, **kwargs)
2328# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2329@_copy_docstring_and_deprecators(Axes.autoscale)
2330def autoscale(enable=True, axis='both', tight=None):
2331 return gca().autoscale(enable=enable, axis=axis, tight=tight)
2334# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2335@_copy_docstring_and_deprecators(Axes.axhline)
2336def axhline(y=0, xmin=0, xmax=1, **kwargs):
2337 return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs)
2340# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2341@_copy_docstring_and_deprecators(Axes.axhspan)
2342def axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs):
2343 return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs)
2346# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2347@_copy_docstring_and_deprecators(Axes.axis)
2348def axis(*args, emit=True, **kwargs):
2349 return gca().axis(*args, emit=emit, **kwargs)
2352# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2353@_copy_docstring_and_deprecators(Axes.axline)
2354def axline(xy1, xy2=None, *, slope=None, **kwargs):
2355 return gca().axline(xy1, xy2=xy2, slope=slope, **kwargs)
2358# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2359@_copy_docstring_and_deprecators(Axes.axvline)
2360def axvline(x=0, ymin=0, ymax=1, **kwargs):
2361 return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs)
2364# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2365@_copy_docstring_and_deprecators(Axes.axvspan)
2366def axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs):
2367 return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)
2370# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2371@_copy_docstring_and_deprecators(Axes.bar)
2372def bar(
2373 x, height, width=0.8, bottom=None, *, align='center',
2374 data=None, **kwargs):
2375 return gca().bar(
2376 x, height, width=width, bottom=bottom, align=align,
2377 **({"data": data} if data is not None else {}), **kwargs)
2380# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2381@_copy_docstring_and_deprecators(Axes.barbs)
2382def barbs(*args, data=None, **kwargs):
2383 return gca().barbs(
2384 *args, **({"data": data} if data is not None else {}),
2385 **kwargs)
2388# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2389@_copy_docstring_and_deprecators(Axes.barh)
2390def barh(
2391 y, width, height=0.8, left=None, *, align='center',
2392 data=None, **kwargs):
2393 return gca().barh(
2394 y, width, height=height, left=left, align=align,
2395 **({"data": data} if data is not None else {}), **kwargs)
2398# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2399@_copy_docstring_and_deprecators(Axes.bar_label)
2400def bar_label(
2401 container, labels=None, *, fmt='%g', label_type='edge',
2402 padding=0, **kwargs):
2403 return gca().bar_label(
2404 container, labels=labels, fmt=fmt, label_type=label_type,
2405 padding=padding, **kwargs)
2408# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2409@_copy_docstring_and_deprecators(Axes.boxplot)
2410def boxplot(
2411 x, notch=None, sym=None, vert=None, whis=None,
2412 positions=None, widths=None, patch_artist=None,
2413 bootstrap=None, usermedians=None, conf_intervals=None,
2414 meanline=None, showmeans=None, showcaps=None, showbox=None,
2415 showfliers=None, boxprops=None, labels=None, flierprops=None,
2416 medianprops=None, meanprops=None, capprops=None,
2417 whiskerprops=None, manage_ticks=True, autorange=False,
2418 zorder=None, capwidths=None, *, data=None):
2419 return gca().boxplot(
2420 x, notch=notch, sym=sym, vert=vert, whis=whis,
2421 positions=positions, widths=widths, patch_artist=patch_artist,
2422 bootstrap=bootstrap, usermedians=usermedians,
2423 conf_intervals=conf_intervals, meanline=meanline,
2424 showmeans=showmeans, showcaps=showcaps, showbox=showbox,
2425 showfliers=showfliers, boxprops=boxprops, labels=labels,
2426 flierprops=flierprops, medianprops=medianprops,
2427 meanprops=meanprops, capprops=capprops,
2428 whiskerprops=whiskerprops, manage_ticks=manage_ticks,
2429 autorange=autorange, zorder=zorder, capwidths=capwidths,
2430 **({"data": data} if data is not None else {}))
2433# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2434@_copy_docstring_and_deprecators(Axes.broken_barh)
2435def broken_barh(xranges, yrange, *, data=None, **kwargs):
2436 return gca().broken_barh(
2437 xranges, yrange,
2438 **({"data": data} if data is not None else {}), **kwargs)
2441# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2442@_copy_docstring_and_deprecators(Axes.clabel)
2443def clabel(CS, levels=None, **kwargs):
2444 return gca().clabel(CS, levels=levels, **kwargs)
2447# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2448@_copy_docstring_and_deprecators(Axes.cohere)
2449def cohere(
2450 x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
2451 window=mlab.window_hanning, noverlap=0, pad_to=None,
2452 sides='default', scale_by_freq=None, *, data=None, **kwargs):
2453 return gca().cohere(
2454 x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
2455 noverlap=noverlap, pad_to=pad_to, sides=sides,
2456 scale_by_freq=scale_by_freq,
2457 **({"data": data} if data is not None else {}), **kwargs)
2460# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2461@_copy_docstring_and_deprecators(Axes.contour)
2462def contour(*args, data=None, **kwargs):
2463 __ret = gca().contour(
2464 *args, **({"data": data} if data is not None else {}),
2465 **kwargs)
2466 if __ret._A is not None: sci(__ret) # noqa
2467 return __ret
2470# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2471@_copy_docstring_and_deprecators(Axes.contourf)
2472def contourf(*args, data=None, **kwargs):
2473 __ret = gca().contourf(
2474 *args, **({"data": data} if data is not None else {}),
2475 **kwargs)
2476 if __ret._A is not None: sci(__ret) # noqa
2477 return __ret
2480# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2481@_copy_docstring_and_deprecators(Axes.csd)
2482def csd(
2483 x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
2484 noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
2485 return_line=None, *, data=None, **kwargs):
2486 return gca().csd(
2487 x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
2488 noverlap=noverlap, pad_to=pad_to, sides=sides,
2489 scale_by_freq=scale_by_freq, return_line=return_line,
2490 **({"data": data} if data is not None else {}), **kwargs)
2493# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2494@_copy_docstring_and_deprecators(Axes.errorbar)
2495def errorbar(
2496 x, y, yerr=None, xerr=None, fmt='', ecolor=None,
2497 elinewidth=None, capsize=None, barsabove=False, lolims=False,
2498 uplims=False, xlolims=False, xuplims=False, errorevery=1,
2499 capthick=None, *, data=None, **kwargs):
2500 return gca().errorbar(
2501 x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor,
2502 elinewidth=elinewidth, capsize=capsize, barsabove=barsabove,
2503 lolims=lolims, uplims=uplims, xlolims=xlolims,
2504 xuplims=xuplims, errorevery=errorevery, capthick=capthick,
2505 **({"data": data} if data is not None else {}), **kwargs)
2508# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2509@_copy_docstring_and_deprecators(Axes.eventplot)
2510def eventplot(
2511 positions, orientation='horizontal', lineoffsets=1,
2512 linelengths=1, linewidths=None, colors=None,
2513 linestyles='solid', *, data=None, **kwargs):
2514 return gca().eventplot(
2515 positions, orientation=orientation, lineoffsets=lineoffsets,
2516 linelengths=linelengths, linewidths=linewidths, colors=colors,
2517 linestyles=linestyles,
2518 **({"data": data} if data is not None else {}), **kwargs)
2521# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2522@_copy_docstring_and_deprecators(Axes.fill)
2523def fill(*args, data=None, **kwargs):
2524 return gca().fill(
2525 *args, **({"data": data} if data is not None else {}),
2526 **kwargs)
2529# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2530@_copy_docstring_and_deprecators(Axes.fill_between)
2531def fill_between(
2532 x, y1, y2=0, where=None, interpolate=False, step=None, *,
2533 data=None, **kwargs):
2534 return gca().fill_between(
2535 x, y1, y2=y2, where=where, interpolate=interpolate, step=step,
2536 **({"data": data} if data is not None else {}), **kwargs)
2539# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2540@_copy_docstring_and_deprecators(Axes.fill_betweenx)
2541def fill_betweenx(
2542 y, x1, x2=0, where=None, step=None, interpolate=False, *,
2543 data=None, **kwargs):
2544 return gca().fill_betweenx(
2545 y, x1, x2=x2, where=where, step=step, interpolate=interpolate,
2546 **({"data": data} if data is not None else {}), **kwargs)
2549# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2550@_copy_docstring_and_deprecators(Axes.grid)
2551def grid(visible=None, which='major', axis='both', **kwargs):
2552 return gca().grid(visible=visible, which=which, axis=axis, **kwargs)
2555# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2556@_copy_docstring_and_deprecators(Axes.hexbin)
2557def hexbin(
2558 x, y, C=None, gridsize=100, bins=None, xscale='linear',
2559 yscale='linear', extent=None, cmap=None, norm=None, vmin=None,
2560 vmax=None, alpha=None, linewidths=None, edgecolors='face',
2561 reduce_C_function=np.mean, mincnt=None, marginals=False, *,
2562 data=None, **kwargs):
2563 __ret = gca().hexbin(
2564 x, y, C=C, gridsize=gridsize, bins=bins, xscale=xscale,
2565 yscale=yscale, extent=extent, cmap=cmap, norm=norm, vmin=vmin,
2566 vmax=vmax, alpha=alpha, linewidths=linewidths,
2567 edgecolors=edgecolors, reduce_C_function=reduce_C_function,
2568 mincnt=mincnt, marginals=marginals,
2569 **({"data": data} if data is not None else {}), **kwargs)
2570 sci(__ret)
2571 return __ret
2574# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2575@_copy_docstring_and_deprecators(Axes.hist)
2576def hist(
2577 x, bins=None, range=None, density=False, weights=None,
2578 cumulative=False, bottom=None, histtype='bar', align='mid',
2579 orientation='vertical', rwidth=None, log=False, color=None,
2580 label=None, stacked=False, *, data=None, **kwargs):
2581 return gca().hist(
2582 x, bins=bins, range=range, density=density, weights=weights,
2583 cumulative=cumulative, bottom=bottom, histtype=histtype,
2584 align=align, orientation=orientation, rwidth=rwidth, log=log,
2585 color=color, label=label, stacked=stacked,
2586 **({"data": data} if data is not None else {}), **kwargs)
2589# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2590@_copy_docstring_and_deprecators(Axes.stairs)
2591def stairs(
2592 values, edges=None, *, orientation='vertical', baseline=0,
2593 fill=False, data=None, **kwargs):
2594 return gca().stairs(
2595 values, edges=edges, orientation=orientation,
2596 baseline=baseline, fill=fill,
2597 **({"data": data} if data is not None else {}), **kwargs)
2600# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2601@_copy_docstring_and_deprecators(Axes.hist2d)
2602def hist2d(
2603 x, y, bins=10, range=None, density=False, weights=None,
2604 cmin=None, cmax=None, *, data=None, **kwargs):
2605 __ret = gca().hist2d(
2606 x, y, bins=bins, range=range, density=density,
2607 weights=weights, cmin=cmin, cmax=cmax,
2608 **({"data": data} if data is not None else {}), **kwargs)
2609 sci(__ret[-1])
2610 return __ret
2613# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2614@_copy_docstring_and_deprecators(Axes.hlines)
2615def hlines(
2616 y, xmin, xmax, colors=None, linestyles='solid', label='', *,
2617 data=None, **kwargs):
2618 return gca().hlines(
2619 y, xmin, xmax, colors=colors, linestyles=linestyles,
2620 label=label, **({"data": data} if data is not None else {}),
2621 **kwargs)
2624# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2625@_copy_docstring_and_deprecators(Axes.imshow)
2626def imshow(
2627 X, cmap=None, norm=None, aspect=None, interpolation=None,
2628 alpha=None, vmin=None, vmax=None, origin=None, extent=None, *,
2629 interpolation_stage=None, filternorm=True, filterrad=4.0,
2630 resample=None, url=None, data=None, **kwargs):
2631 __ret = gca().imshow(
2632 X, cmap=cmap, norm=norm, aspect=aspect,
2633 interpolation=interpolation, alpha=alpha, vmin=vmin,
2634 vmax=vmax, origin=origin, extent=extent,
2635 interpolation_stage=interpolation_stage,
2636 filternorm=filternorm, filterrad=filterrad, resample=resample,
2637 url=url, **({"data": data} if data is not None else {}),
2638 **kwargs)
2639 sci(__ret)
2640 return __ret
2643# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2644@_copy_docstring_and_deprecators(Axes.legend)
2645def legend(*args, **kwargs):
2646 return gca().legend(*args, **kwargs)
2649# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2650@_copy_docstring_and_deprecators(Axes.locator_params)
2651def locator_params(axis='both', tight=None, **kwargs):
2652 return gca().locator_params(axis=axis, tight=tight, **kwargs)
2655# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2656@_copy_docstring_and_deprecators(Axes.loglog)
2657def loglog(*args, **kwargs):
2658 return gca().loglog(*args, **kwargs)
2661# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2662@_copy_docstring_and_deprecators(Axes.magnitude_spectrum)
2663def magnitude_spectrum(
2664 x, Fs=None, Fc=None, window=None, pad_to=None, sides=None,
2665 scale=None, *, data=None, **kwargs):
2666 return gca().magnitude_spectrum(
2667 x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
2668 scale=scale, **({"data": data} if data is not None else {}),
2669 **kwargs)
2672# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2673@_copy_docstring_and_deprecators(Axes.margins)
2674def margins(*margins, x=None, y=None, tight=True):
2675 return gca().margins(*margins, x=x, y=y, tight=tight)
2678# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2679@_copy_docstring_and_deprecators(Axes.minorticks_off)
2680def minorticks_off():
2681 return gca().minorticks_off()
2684# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2685@_copy_docstring_and_deprecators(Axes.minorticks_on)
2686def minorticks_on():
2687 return gca().minorticks_on()
2690# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2691@_copy_docstring_and_deprecators(Axes.pcolor)
2692def pcolor(
2693 *args, shading=None, alpha=None, norm=None, cmap=None,
2694 vmin=None, vmax=None, data=None, **kwargs):
2695 __ret = gca().pcolor(
2696 *args, shading=shading, alpha=alpha, norm=norm, cmap=cmap,
2697 vmin=vmin, vmax=vmax,
2698 **({"data": data} if data is not None else {}), **kwargs)
2699 sci(__ret)
2700 return __ret
2703# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2704@_copy_docstring_and_deprecators(Axes.pcolormesh)
2705def pcolormesh(
2706 *args, alpha=None, norm=None, cmap=None, vmin=None,
2707 vmax=None, shading=None, antialiased=False, data=None,
2708 **kwargs):
2709 __ret = gca().pcolormesh(
2710 *args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
2711 vmax=vmax, shading=shading, antialiased=antialiased,
2712 **({"data": data} if data is not None else {}), **kwargs)
2713 sci(__ret)
2714 return __ret
2717# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2718@_copy_docstring_and_deprecators(Axes.phase_spectrum)
2719def phase_spectrum(
2720 x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
2721 data=None, **kwargs):
2722 return gca().phase_spectrum(
2723 x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
2724 **({"data": data} if data is not None else {}), **kwargs)
2727# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2728@_copy_docstring_and_deprecators(Axes.pie)
2729def pie(
2730 x, explode=None, labels=None, colors=None, autopct=None,
2731 pctdistance=0.6, shadow=False, labeldistance=1.1,
2732 startangle=0, radius=1, counterclock=True, wedgeprops=None,
2733 textprops=None, center=(0, 0), frame=False,
2734 rotatelabels=False, *, normalize=True, data=None):
2735 return gca().pie(
2736 x, explode=explode, labels=labels, colors=colors,
2737 autopct=autopct, pctdistance=pctdistance, shadow=shadow,
2738 labeldistance=labeldistance, startangle=startangle,
2739 radius=radius, counterclock=counterclock,
2740 wedgeprops=wedgeprops, textprops=textprops, center=center,
2741 frame=frame, rotatelabels=rotatelabels, normalize=normalize,
2742 **({"data": data} if data is not None else {}))
2745# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2746@_copy_docstring_and_deprecators(Axes.plot)
2747def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
2748 return gca().plot(
2749 *args, scalex=scalex, scaley=scaley,
2750 **({"data": data} if data is not None else {}), **kwargs)
2753# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2754@_copy_docstring_and_deprecators(Axes.plot_date)
2755def plot_date(
2756 x, y, fmt='o', tz=None, xdate=True, ydate=False, *,
2757 data=None, **kwargs):
2758 return gca().plot_date(
2759 x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate,
2760 **({"data": data} if data is not None else {}), **kwargs)
2763# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2764@_copy_docstring_and_deprecators(Axes.psd)
2765def psd(
2766 x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
2767 noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
2768 return_line=None, *, data=None, **kwargs):
2769 return gca().psd(
2770 x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
2771 noverlap=noverlap, pad_to=pad_to, sides=sides,
2772 scale_by_freq=scale_by_freq, return_line=return_line,
2773 **({"data": data} if data is not None else {}), **kwargs)
2776# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2777@_copy_docstring_and_deprecators(Axes.quiver)
2778def quiver(*args, data=None, **kwargs):
2779 __ret = gca().quiver(
2780 *args, **({"data": data} if data is not None else {}),
2781 **kwargs)
2782 sci(__ret)
2783 return __ret
2786# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2787@_copy_docstring_and_deprecators(Axes.quiverkey)
2788def quiverkey(Q, X, Y, U, label, **kwargs):
2789 return gca().quiverkey(Q, X, Y, U, label, **kwargs)
2792# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2793@_copy_docstring_and_deprecators(Axes.scatter)
2794def scatter(
2795 x, y, s=None, c=None, marker=None, cmap=None, norm=None,
2796 vmin=None, vmax=None, alpha=None, linewidths=None, *,
2797 edgecolors=None, plotnonfinite=False, data=None, **kwargs):
2798 __ret = gca().scatter(
2799 x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
2800 vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
2801 edgecolors=edgecolors, plotnonfinite=plotnonfinite,
2802 **({"data": data} if data is not None else {}), **kwargs)
2803 sci(__ret)
2804 return __ret
2807# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2808@_copy_docstring_and_deprecators(Axes.semilogx)
2809def semilogx(*args, **kwargs):
2810 return gca().semilogx(*args, **kwargs)
2813# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2814@_copy_docstring_and_deprecators(Axes.semilogy)
2815def semilogy(*args, **kwargs):
2816 return gca().semilogy(*args, **kwargs)
2819# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2820@_copy_docstring_and_deprecators(Axes.specgram)
2821def specgram(
2822 x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
2823 noverlap=None, cmap=None, xextent=None, pad_to=None,
2824 sides=None, scale_by_freq=None, mode=None, scale=None,
2825 vmin=None, vmax=None, *, data=None, **kwargs):
2826 __ret = gca().specgram(
2827 x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
2828 noverlap=noverlap, cmap=cmap, xextent=xextent, pad_to=pad_to,
2829 sides=sides, scale_by_freq=scale_by_freq, mode=mode,
2830 scale=scale, vmin=vmin, vmax=vmax,
2831 **({"data": data} if data is not None else {}), **kwargs)
2832 sci(__ret[-1])
2833 return __ret
2836# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2837@_copy_docstring_and_deprecators(Axes.spy)
2838def spy(
2839 Z, precision=0, marker=None, markersize=None, aspect='equal',
2840 origin='upper', **kwargs):
2841 __ret = gca().spy(
2842 Z, precision=precision, marker=marker, markersize=markersize,
2843 aspect=aspect, origin=origin, **kwargs)
2844 if isinstance(__ret, cm.ScalarMappable): sci(__ret) # noqa
2845 return __ret
2848# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2849@_copy_docstring_and_deprecators(Axes.stackplot)
2850def stackplot(
2851 x, *args, labels=(), colors=None, baseline='zero', data=None,
2852 **kwargs):
2853 return gca().stackplot(
2854 x, *args, labels=labels, colors=colors, baseline=baseline,
2855 **({"data": data} if data is not None else {}), **kwargs)
2858# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2859@_copy_docstring_and_deprecators(Axes.stem)
2860def stem(
2861 *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
2862 label=None,
2863 use_line_collection=_api.deprecation._deprecated_parameter,
2864 orientation='vertical', data=None):
2865 return gca().stem(
2866 *args, linefmt=linefmt, markerfmt=markerfmt, basefmt=basefmt,
2867 bottom=bottom, label=label,
2868 use_line_collection=use_line_collection,
2869 orientation=orientation,
2870 **({"data": data} if data is not None else {}))
2873# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2874@_copy_docstring_and_deprecators(Axes.step)
2875def step(x, y, *args, where='pre', data=None, **kwargs):
2876 return gca().step(
2877 x, y, *args, where=where,
2878 **({"data": data} if data is not None else {}), **kwargs)
2881# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2882@_copy_docstring_and_deprecators(Axes.streamplot)
2883def streamplot(
2884 x, y, u, v, density=1, linewidth=None, color=None, cmap=None,
2885 norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1,
2886 transform=None, zorder=None, start_points=None, maxlength=4.0,
2887 integration_direction='both', broken_streamlines=True, *,
2888 data=None):
2889 __ret = gca().streamplot(
2890 x, y, u, v, density=density, linewidth=linewidth, color=color,
2891 cmap=cmap, norm=norm, arrowsize=arrowsize,
2892 arrowstyle=arrowstyle, minlength=minlength,
2893 transform=transform, zorder=zorder, start_points=start_points,
2894 maxlength=maxlength,
2895 integration_direction=integration_direction,
2896 broken_streamlines=broken_streamlines,
2897 **({"data": data} if data is not None else {}))
2898 sci(__ret.lines)
2899 return __ret
2902# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2903@_copy_docstring_and_deprecators(Axes.table)
2904def table(
2905 cellText=None, cellColours=None, cellLoc='right',
2906 colWidths=None, rowLabels=None, rowColours=None,
2907 rowLoc='left', colLabels=None, colColours=None,
2908 colLoc='center', loc='bottom', bbox=None, edges='closed',
2909 **kwargs):
2910 return gca().table(
2911 cellText=cellText, cellColours=cellColours, cellLoc=cellLoc,
2912 colWidths=colWidths, rowLabels=rowLabels,
2913 rowColours=rowColours, rowLoc=rowLoc, colLabels=colLabels,
2914 colColours=colColours, colLoc=colLoc, loc=loc, bbox=bbox,
2915 edges=edges, **kwargs)
2918# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2919@_copy_docstring_and_deprecators(Axes.text)
2920def text(x, y, s, fontdict=None, **kwargs):
2921 return gca().text(x, y, s, fontdict=fontdict, **kwargs)
2924# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2925@_copy_docstring_and_deprecators(Axes.tick_params)
2926def tick_params(axis='both', **kwargs):
2927 return gca().tick_params(axis=axis, **kwargs)
2930# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2931@_copy_docstring_and_deprecators(Axes.ticklabel_format)
2932def ticklabel_format(
2933 *, axis='both', style='', scilimits=None, useOffset=None,
2934 useLocale=None, useMathText=None):
2935 return gca().ticklabel_format(
2936 axis=axis, style=style, scilimits=scilimits,
2937 useOffset=useOffset, useLocale=useLocale,
2938 useMathText=useMathText)
2941# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2942@_copy_docstring_and_deprecators(Axes.tricontour)
2943def tricontour(*args, **kwargs):
2944 __ret = gca().tricontour(*args, **kwargs)
2945 if __ret._A is not None: sci(__ret) # noqa
2946 return __ret
2949# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2950@_copy_docstring_and_deprecators(Axes.tricontourf)
2951def tricontourf(*args, **kwargs):
2952 __ret = gca().tricontourf(*args, **kwargs)
2953 if __ret._A is not None: sci(__ret) # noqa
2954 return __ret
2957# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2958@_copy_docstring_and_deprecators(Axes.tripcolor)
2959def tripcolor(
2960 *args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None,
2961 shading='flat', facecolors=None, **kwargs):
2962 __ret = gca().tripcolor(
2963 *args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
2964 vmax=vmax, shading=shading, facecolors=facecolors, **kwargs)
2965 sci(__ret)
2966 return __ret
2969# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2970@_copy_docstring_and_deprecators(Axes.triplot)
2971def triplot(*args, **kwargs):
2972 return gca().triplot(*args, **kwargs)
2975# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2976@_copy_docstring_and_deprecators(Axes.violinplot)
2977def violinplot(
2978 dataset, positions=None, vert=True, widths=0.5,
2979 showmeans=False, showextrema=True, showmedians=False,
2980 quantiles=None, points=100, bw_method=None, *, data=None):
2981 return gca().violinplot(
2982 dataset, positions=positions, vert=vert, widths=widths,
2983 showmeans=showmeans, showextrema=showextrema,
2984 showmedians=showmedians, quantiles=quantiles, points=points,
2985 bw_method=bw_method,
2986 **({"data": data} if data is not None else {}))
2989# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2990@_copy_docstring_and_deprecators(Axes.vlines)
2991def vlines(
2992 x, ymin, ymax, colors=None, linestyles='solid', label='', *,
2993 data=None, **kwargs):
2994 return gca().vlines(
2995 x, ymin, ymax, colors=colors, linestyles=linestyles,
2996 label=label, **({"data": data} if data is not None else {}),
2997 **kwargs)
3000# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3001@_copy_docstring_and_deprecators(Axes.xcorr)
3002def xcorr(
3003 x, y, normed=True, detrend=mlab.detrend_none, usevlines=True,
3004 maxlags=10, *, data=None, **kwargs):
3005 return gca().xcorr(
3006 x, y, normed=normed, detrend=detrend, usevlines=usevlines,
3007 maxlags=maxlags,
3008 **({"data": data} if data is not None else {}), **kwargs)
3011# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3012@_copy_docstring_and_deprecators(Axes._sci)
3013def sci(im):
3014 return gca()._sci(im)
3017# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3018@_copy_docstring_and_deprecators(Axes.set_title)
3019def title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs):
3020 return gca().set_title(
3021 label, fontdict=fontdict, loc=loc, pad=pad, y=y, **kwargs)
3024# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3025@_copy_docstring_and_deprecators(Axes.set_xlabel)
3026def xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):
3027 return gca().set_xlabel(
3028 xlabel, fontdict=fontdict, labelpad=labelpad, loc=loc,
3029 **kwargs)
3032# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3033@_copy_docstring_and_deprecators(Axes.set_ylabel)
3034def ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):
3035 return gca().set_ylabel(
3036 ylabel, fontdict=fontdict, labelpad=labelpad, loc=loc,
3037 **kwargs)
3040# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3041@_copy_docstring_and_deprecators(Axes.set_xscale)
3042def xscale(value, **kwargs):
3043 return gca().set_xscale(value, **kwargs)
3046# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3047@_copy_docstring_and_deprecators(Axes.set_yscale)
3048def yscale(value, **kwargs):
3049 return gca().set_yscale(value, **kwargs)
3052# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3053def autumn():
3054 """
3055 Set the colormap to 'autumn'.
3057 This changes the default colormap as well as the colormap of the current
3058 image if there is one. See ``help(colormaps)`` for more information.
3059 """
3060 set_cmap('autumn')
3063# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3064def bone():
3065 """
3066 Set the colormap to 'bone'.
3068 This changes the default colormap as well as the colormap of the current
3069 image if there is one. See ``help(colormaps)`` for more information.
3070 """
3071 set_cmap('bone')
3074# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3075def cool():
3076 """
3077 Set the colormap to 'cool'.
3079 This changes the default colormap as well as the colormap of the current
3080 image if there is one. See ``help(colormaps)`` for more information.
3081 """
3082 set_cmap('cool')
3085# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3086def copper():
3087 """
3088 Set the colormap to 'copper'.
3090 This changes the default colormap as well as the colormap of the current
3091 image if there is one. See ``help(colormaps)`` for more information.
3092 """
3093 set_cmap('copper')
3096# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3097def flag():
3098 """
3099 Set the colormap to 'flag'.
3101 This changes the default colormap as well as the colormap of the current
3102 image if there is one. See ``help(colormaps)`` for more information.
3103 """
3104 set_cmap('flag')
3107# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3108def gray():
3109 """
3110 Set the colormap to 'gray'.
3112 This changes the default colormap as well as the colormap of the current
3113 image if there is one. See ``help(colormaps)`` for more information.
3114 """
3115 set_cmap('gray')
3118# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3119def hot():
3120 """
3121 Set the colormap to 'hot'.
3123 This changes the default colormap as well as the colormap of the current
3124 image if there is one. See ``help(colormaps)`` for more information.
3125 """
3126 set_cmap('hot')
3129# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3130def hsv():
3131 """
3132 Set the colormap to 'hsv'.
3134 This changes the default colormap as well as the colormap of the current
3135 image if there is one. See ``help(colormaps)`` for more information.
3136 """
3137 set_cmap('hsv')
3140# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3141def jet():
3142 """
3143 Set the colormap to 'jet'.
3145 This changes the default colormap as well as the colormap of the current
3146 image if there is one. See ``help(colormaps)`` for more information.
3147 """
3148 set_cmap('jet')
3151# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3152def pink():
3153 """
3154 Set the colormap to 'pink'.
3156 This changes the default colormap as well as the colormap of the current
3157 image if there is one. See ``help(colormaps)`` for more information.
3158 """
3159 set_cmap('pink')
3162# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3163def prism():
3164 """
3165 Set the colormap to 'prism'.
3167 This changes the default colormap as well as the colormap of the current
3168 image if there is one. See ``help(colormaps)`` for more information.
3169 """
3170 set_cmap('prism')
3173# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3174def spring():
3175 """
3176 Set the colormap to 'spring'.
3178 This changes the default colormap as well as the colormap of the current
3179 image if there is one. See ``help(colormaps)`` for more information.
3180 """
3181 set_cmap('spring')
3184# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3185def summer():
3186 """
3187 Set the colormap to 'summer'.
3189 This changes the default colormap as well as the colormap of the current
3190 image if there is one. See ``help(colormaps)`` for more information.
3191 """
3192 set_cmap('summer')
3195# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3196def winter():
3197 """
3198 Set the colormap to 'winter'.
3200 This changes the default colormap as well as the colormap of the current
3201 image if there is one. See ``help(colormaps)`` for more information.
3202 """
3203 set_cmap('winter')
3206# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3207def magma():
3208 """
3209 Set the colormap to 'magma'.
3211 This changes the default colormap as well as the colormap of the current
3212 image if there is one. See ``help(colormaps)`` for more information.
3213 """
3214 set_cmap('magma')
3217# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3218def inferno():
3219 """
3220 Set the colormap to 'inferno'.
3222 This changes the default colormap as well as the colormap of the current
3223 image if there is one. See ``help(colormaps)`` for more information.
3224 """
3225 set_cmap('inferno')
3228# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3229def plasma():
3230 """
3231 Set the colormap to 'plasma'.
3233 This changes the default colormap as well as the colormap of the current
3234 image if there is one. See ``help(colormaps)`` for more information.
3235 """
3236 set_cmap('plasma')
3239# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3240def viridis():
3241 """
3242 Set the colormap to 'viridis'.
3244 This changes the default colormap as well as the colormap of the current
3245 image if there is one. See ``help(colormaps)`` for more information.
3246 """
3247 set_cmap('viridis')
3250# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3251def nipy_spectral():
3252 """
3253 Set the colormap to 'nipy_spectral'.
3255 This changes the default colormap as well as the colormap of the current
3256 image if there is one. See ``help(colormaps)`` for more information.
3257 """
3258 set_cmap('nipy_spectral')