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.
3
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.
8
9pyplot is mainly intended for interactive plots and simple cases of
10programmatic plot generation::
11
12 import numpy as np
13 import matplotlib.pyplot as plt
14
15 x = np.arange(0, 5, 0.1)
16 y = np.sin(x)
17 plt.plot(x, y)
18
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::
24
25 import numpy as np
26 import matplotlib.pyplot as plt
27
28 x = np.arange(0, 5, 0.1)
29 y = np.sin(x)
30 fig, ax = plt.subplots()
31 ax.plot(x, y)
32
33
34See :ref:`api_interfaces` for an explanation of the tradeoffs between the
35implicit and explicit interfaces.
36"""
37
38# fmt: off
39
40from __future__ import annotations
41
42from contextlib import AbstractContextManager, ExitStack
43from enum import Enum
44import functools
45import importlib
46import inspect
47import logging
48import sys
49import threading
50import time
51from typing import TYPE_CHECKING, cast, overload
52
53from cycler import cycler # noqa: F401
54import matplotlib
55import matplotlib.colorbar
56import matplotlib.image
57from matplotlib import _api
58from matplotlib import ( # noqa: F401 Re-exported for typing.
59 cm as cm, get_backend as get_backend, rcParams as rcParams, style as style)
60from matplotlib import _pylab_helpers
61from matplotlib import interactive # noqa: F401
62from matplotlib import cbook
63from matplotlib import _docstring
64from matplotlib.backend_bases import (
65 FigureCanvasBase, FigureManagerBase, MouseButton)
66from matplotlib.figure import Figure, FigureBase, figaspect
67from matplotlib.gridspec import GridSpec, SubplotSpec
68from matplotlib import rcsetup, rcParamsDefault, rcParamsOrig
69from matplotlib.artist import Artist
70from matplotlib.axes import Axes
71from matplotlib.axes import Subplot # noqa: F401
72from matplotlib.backends import BackendFilter, backend_registry
73from matplotlib.projections import PolarAxes
74from matplotlib import mlab # for detrend_none, window_hanning
75from matplotlib.scale import get_scale_names # noqa: F401
76
77from matplotlib.cm import _colormaps
78from matplotlib.colors import _color_sequences, Colormap
79
80import numpy as np
81
82if TYPE_CHECKING:
83 from collections.abc import Callable, Hashable, Iterable, Sequence
84 import datetime
85 import pathlib
86 import os
87 from typing import Any, BinaryIO, Literal, TypeVar
88 from typing_extensions import ParamSpec
89
90 import PIL.Image
91 from numpy.typing import ArrayLike
92
93 import matplotlib.axes
94 import matplotlib.artist
95 import matplotlib.backend_bases
96 from matplotlib.axis import Tick
97 from matplotlib.axes._base import _AxesBase
98 from matplotlib.backend_bases import RendererBase, Event
99 from matplotlib.cm import ScalarMappable
100 from matplotlib.contour import ContourSet, QuadContourSet
101 from matplotlib.collections import (
102 Collection,
103 LineCollection,
104 PolyCollection,
105 PathCollection,
106 EventCollection,
107 QuadMesh,
108 )
109 from matplotlib.colorbar import Colorbar
110 from matplotlib.container import (
111 BarContainer,
112 ErrorbarContainer,
113 StemContainer,
114 )
115 from matplotlib.figure import SubFigure
116 from matplotlib.legend import Legend
117 from matplotlib.mlab import GaussianKDE
118 from matplotlib.image import AxesImage, FigureImage
119 from matplotlib.patches import FancyArrow, StepPatch, Wedge
120 from matplotlib.quiver import Barbs, Quiver, QuiverKey
121 from matplotlib.scale import ScaleBase
122 from matplotlib.transforms import Transform, Bbox
123 from matplotlib.typing import ColorType, LineStyleType, MarkerType, HashableList
124 from matplotlib.widgets import SubplotTool
125
126 _P = ParamSpec('_P')
127 _R = TypeVar('_R')
128 _T = TypeVar('_T')
129
130
131# We may not need the following imports here:
132from matplotlib.colors import Normalize
133from matplotlib.lines import Line2D, AxLine
134from matplotlib.text import Text, Annotation
135from matplotlib.patches import Arrow, Circle, Rectangle # noqa: F401
136from matplotlib.patches import Polygon
137from matplotlib.widgets import Button, Slider, Widget # noqa: F401
138
139from .ticker import ( # noqa: F401
140 TickHelper, Formatter, FixedFormatter, NullFormatter, FuncFormatter,
141 FormatStrFormatter, ScalarFormatter, LogFormatter, LogFormatterExponent,
142 LogFormatterMathtext, Locator, IndexLocator, FixedLocator, NullLocator,
143 LinearLocator, LogLocator, AutoLocator, MultipleLocator, MaxNLocator)
144
145_log = logging.getLogger(__name__)
146
147
148# Explicit rename instead of import-as for typing's sake.
149colormaps = _colormaps
150color_sequences = _color_sequences
151
152
153@overload
154def _copy_docstring_and_deprecators(
155 method: Any,
156 func: Literal[None] = None
157) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...
158
159
160@overload
161def _copy_docstring_and_deprecators(
162 method: Any, func: Callable[_P, _R]) -> Callable[_P, _R]: ...
163
164
165def _copy_docstring_and_deprecators(
166 method: Any,
167 func: Callable[_P, _R] | None = None
168) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[_P, _R]:
169 if func is None:
170 return cast('Callable[[Callable[_P, _R]], Callable[_P, _R]]',
171 functools.partial(_copy_docstring_and_deprecators, method))
172 decorators: list[Callable[[Callable[_P, _R]], Callable[_P, _R]]] = [
173 _docstring.copy(method)
174 ]
175 # Check whether the definition of *method* includes @_api.rename_parameter
176 # or @_api.make_keyword_only decorators; if so, propagate them to the
177 # pyplot wrapper as well.
178 while hasattr(method, "__wrapped__"):
179 potential_decorator = _api.deprecation.DECORATORS.get(method)
180 if potential_decorator:
181 decorators.append(potential_decorator)
182 method = method.__wrapped__
183 for decorator in decorators[::-1]:
184 func = decorator(func)
185 _add_pyplot_note(func, method)
186 return func
187
188
189_NO_PYPLOT_NOTE = [
190 'FigureBase._gci', # wrapped_func is private
191 '_AxesBase._sci', # wrapped_func is private
192 'Artist.findobj', # not a standard pyplot wrapper because it does not operate
193 # on the current Figure / Axes. Explanation of relation would
194 # be more complex and is not too important.
195]
196
197
198def _add_pyplot_note(func, wrapped_func):
199 """
200 Add a note to the docstring of *func* that it is a pyplot wrapper.
201
202 The note is added to the "Notes" section of the docstring. If that does
203 not exist, a "Notes" section is created. In numpydoc, the "Notes"
204 section is the third last possible section, only potentially followed by
205 "References" and "Examples".
206 """
207 if not func.__doc__:
208 return # nothing to do
209
210 qualname = wrapped_func.__qualname__
211 if qualname in _NO_PYPLOT_NOTE:
212 return
213
214 wrapped_func_is_method = True
215 if "." not in qualname:
216 # method qualnames are prefixed by the class and ".", e.g. "Axes.plot"
217 wrapped_func_is_method = False
218 link = f"{wrapped_func.__module__}.{qualname}"
219 elif qualname.startswith("Axes."): # e.g. "Axes.plot"
220 link = ".axes." + qualname
221 elif qualname.startswith("_AxesBase."): # e.g. "_AxesBase.set_xlabel"
222 link = ".axes.Axes" + qualname[9:]
223 elif qualname.startswith("Figure."): # e.g. "Figure.figimage"
224 link = "." + qualname
225 elif qualname.startswith("FigureBase."): # e.g. "FigureBase.gca"
226 link = ".Figure" + qualname[10:]
227 elif qualname.startswith("FigureCanvasBase."): # "FigureBaseCanvas.mpl_connect"
228 link = "." + qualname
229 else:
230 raise RuntimeError(f"Wrapped method from unexpected class: {qualname}")
231
232 if wrapped_func_is_method:
233 message = f"This is the :ref:`pyplot wrapper <pyplot_interface>` for `{link}`."
234 else:
235 message = f"This is equivalent to `{link}`."
236
237 # Find the correct insert position:
238 # - either we already have a "Notes" section into which we can insert
239 # - or we create one before the next present section. Note that in numpydoc, the
240 # "Notes" section is the third last possible section, only potentially followed
241 # by "References" and "Examples".
242 # - or we append a new "Notes" section at the end.
243 doc = inspect.cleandoc(func.__doc__)
244 if "\nNotes\n-----" in doc:
245 before, after = doc.split("\nNotes\n-----", 1)
246 elif (index := doc.find("\nReferences\n----------")) != -1:
247 before, after = doc[:index], doc[index:]
248 elif (index := doc.find("\nExamples\n--------")) != -1:
249 before, after = doc[:index], doc[index:]
250 else:
251 # No "Notes", "References", or "Examples" --> append to the end.
252 before = doc + "\n"
253 after = ""
254
255 func.__doc__ = f"{before}\nNotes\n-----\n\n.. note::\n\n {message}\n{after}"
256
257
258## Global ##
259
260
261# The state controlled by {,un}install_repl_displayhook().
262_ReplDisplayHook = Enum("_ReplDisplayHook", ["NONE", "PLAIN", "IPYTHON"])
263_REPL_DISPLAYHOOK = _ReplDisplayHook.NONE
264
265
266def _draw_all_if_interactive() -> None:
267 if matplotlib.is_interactive():
268 draw_all()
269
270
271def install_repl_displayhook() -> None:
272 """
273 Connect to the display hook of the current shell.
274
275 The display hook gets called when the read-evaluate-print-loop (REPL) of
276 the shell has finished the execution of a command. We use this callback
277 to be able to automatically update a figure in interactive mode.
278
279 This works both with IPython and with vanilla python shells.
280 """
281 global _REPL_DISPLAYHOOK
282
283 if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON:
284 return
285
286 # See if we have IPython hooks around, if so use them.
287 # Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
288 # entries can also have been explicitly set to None.
289 mod_ipython = sys.modules.get("IPython")
290 if not mod_ipython:
291 _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN
292 return
293 ip = mod_ipython.get_ipython()
294 if not ip:
295 _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN
296 return
297
298 ip.events.register("post_execute", _draw_all_if_interactive)
299 _REPL_DISPLAYHOOK = _ReplDisplayHook.IPYTHON
300
301 if mod_ipython.version_info[:2] < (8, 24):
302 # Use of backend2gui is not needed for IPython >= 8.24 as that functionality
303 # has been moved to Matplotlib.
304 # This code can be removed when Python 3.12, the latest version supported by
305 # IPython < 8.24, reaches end-of-life in late 2028.
306 from IPython.core.pylabtools import backend2gui
307 ipython_gui_name = backend2gui.get(get_backend())
308 else:
309 _, ipython_gui_name = backend_registry.resolve_backend(get_backend())
310 # trigger IPython's eventloop integration, if available
311 if ipython_gui_name:
312 ip.enable_gui(ipython_gui_name)
313
314
315def uninstall_repl_displayhook() -> None:
316 """Disconnect from the display hook of the current shell."""
317 global _REPL_DISPLAYHOOK
318 if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON:
319 from IPython import get_ipython
320 ip = get_ipython()
321 ip.events.unregister("post_execute", _draw_all_if_interactive)
322 _REPL_DISPLAYHOOK = _ReplDisplayHook.NONE
323
324
325draw_all = _pylab_helpers.Gcf.draw_all
326
327
328# Ensure this appears in the pyplot docs.
329@_copy_docstring_and_deprecators(matplotlib.set_loglevel)
330def set_loglevel(*args, **kwargs) -> None:
331 return matplotlib.set_loglevel(*args, **kwargs)
332
333
334@_copy_docstring_and_deprecators(Artist.findobj)
335def findobj(
336 o: Artist | None = None,
337 match: Callable[[Artist], bool] | type[Artist] | None = None,
338 include_self: bool = True
339) -> list[Artist]:
340 if o is None:
341 o = gcf()
342 return o.findobj(match, include_self=include_self)
343
344
345_backend_mod: type[matplotlib.backend_bases._Backend] | None = None
346
347
348def _get_backend_mod() -> type[matplotlib.backend_bases._Backend]:
349 """
350 Ensure that a backend is selected and return it.
351
352 This is currently private, but may be made public in the future.
353 """
354 if _backend_mod is None:
355 # Use rcParams._get("backend") to avoid going through the fallback
356 # logic (which will (re)import pyplot and then call switch_backend if
357 # we need to resolve the auto sentinel)
358 switch_backend(rcParams._get("backend"))
359 return cast(type[matplotlib.backend_bases._Backend], _backend_mod)
360
361
362def switch_backend(newbackend: str) -> None:
363 """
364 Set the pyplot backend.
365
366 Switching to an interactive backend is possible only if no event loop for
367 another interactive backend has started. Switching to and from
368 non-interactive backends is always possible.
369
370 If the new backend is different than the current backend then all open
371 Figures will be closed via ``plt.close('all')``.
372
373 Parameters
374 ----------
375 newbackend : str
376 The case-insensitive name of the backend to use.
377
378 """
379 global _backend_mod
380 # make sure the init is pulled up so we can assign to it later
381 import matplotlib.backends
382
383 if newbackend is rcsetup._auto_backend_sentinel:
384 current_framework = cbook._get_running_interactive_framework()
385
386 if (current_framework and
387 (backend := backend_registry.backend_for_gui_framework(
388 current_framework))):
389 candidates = [backend]
390 else:
391 candidates = []
392 candidates += [
393 "macosx", "qtagg", "gtk4agg", "gtk3agg", "tkagg", "wxagg"]
394
395 # Don't try to fallback on the cairo-based backends as they each have
396 # an additional dependency (pycairo) over the agg-based backend, and
397 # are of worse quality.
398 for candidate in candidates:
399 try:
400 switch_backend(candidate)
401 except ImportError:
402 continue
403 else:
404 rcParamsOrig['backend'] = candidate
405 return
406 else:
407 # Switching to Agg should always succeed; if it doesn't, let the
408 # exception propagate out.
409 switch_backend("agg")
410 rcParamsOrig["backend"] = "agg"
411 return
412 # have to escape the switch on access logic
413 old_backend = dict.__getitem__(rcParams, 'backend')
414
415 module = backend_registry.load_backend_module(newbackend)
416 canvas_class = module.FigureCanvas
417
418 required_framework = canvas_class.required_interactive_framework
419 if required_framework is not None:
420 current_framework = cbook._get_running_interactive_framework()
421 if (current_framework and required_framework
422 and current_framework != required_framework):
423 raise ImportError(
424 "Cannot load backend {!r} which requires the {!r} interactive "
425 "framework, as {!r} is currently running".format(
426 newbackend, required_framework, current_framework))
427
428 # Load the new_figure_manager() and show() functions from the backend.
429
430 # Classically, backends can directly export these functions. This should
431 # keep working for backcompat.
432 new_figure_manager = getattr(module, "new_figure_manager", None)
433 show = getattr(module, "show", None)
434
435 # In that classical approach, backends are implemented as modules, but
436 # "inherit" default method implementations from backend_bases._Backend.
437 # This is achieved by creating a "class" that inherits from
438 # backend_bases._Backend and whose body is filled with the module globals.
439 class backend_mod(matplotlib.backend_bases._Backend):
440 locals().update(vars(module))
441
442 # However, the newer approach for defining new_figure_manager and
443 # show is to derive them from canvas methods. In that case, also
444 # update backend_mod accordingly; also, per-backend customization of
445 # draw_if_interactive is disabled.
446 if new_figure_manager is None:
447
448 def new_figure_manager_given_figure(num, figure):
449 return canvas_class.new_manager(figure, num)
450
451 def new_figure_manager(num, *args, FigureClass=Figure, **kwargs):
452 fig = FigureClass(*args, **kwargs)
453 return new_figure_manager_given_figure(num, fig)
454
455 def draw_if_interactive() -> None:
456 if matplotlib.is_interactive():
457 manager = _pylab_helpers.Gcf.get_active()
458 if manager:
459 manager.canvas.draw_idle()
460
461 backend_mod.new_figure_manager_given_figure = ( # type: ignore[method-assign]
462 new_figure_manager_given_figure)
463 backend_mod.new_figure_manager = ( # type: ignore[method-assign]
464 new_figure_manager)
465 backend_mod.draw_if_interactive = ( # type: ignore[method-assign]
466 draw_if_interactive)
467
468 # If the manager explicitly overrides pyplot_show, use it even if a global
469 # show is already present, as the latter may be here for backcompat.
470 manager_class = getattr(canvas_class, "manager_class", None)
471 # We can't compare directly manager_class.pyplot_show and FMB.pyplot_show because
472 # pyplot_show is a classmethod so the above constructs are bound classmethods, and
473 # thus always different (being bound to different classes). We also have to use
474 # getattr_static instead of vars as manager_class could have no __dict__.
475 manager_pyplot_show = inspect.getattr_static(manager_class, "pyplot_show", None)
476 base_pyplot_show = inspect.getattr_static(FigureManagerBase, "pyplot_show", None)
477 if (show is None
478 or (manager_pyplot_show is not None
479 and manager_pyplot_show != base_pyplot_show)):
480 if not manager_pyplot_show:
481 raise ValueError(
482 f"Backend {newbackend} defines neither FigureCanvas.manager_class nor "
483 f"a toplevel show function")
484 _pyplot_show = cast('Any', manager_class).pyplot_show
485 backend_mod.show = _pyplot_show # type: ignore[method-assign]
486
487 _log.debug("Loaded backend %s version %s.",
488 newbackend, backend_mod.backend_version)
489
490 if newbackend in ("ipympl", "widget"):
491 # ipympl < 0.9.4 expects rcParams["backend"] to be the fully-qualified backend
492 # name "module://ipympl.backend_nbagg" not short names "ipympl" or "widget".
493 import importlib.metadata as im
494 from matplotlib import _parse_to_version_info # type: ignore[attr-defined]
495 try:
496 module_version = im.version("ipympl")
497 if _parse_to_version_info(module_version) < (0, 9, 4):
498 newbackend = "module://ipympl.backend_nbagg"
499 except im.PackageNotFoundError:
500 pass
501
502 rcParams['backend'] = rcParamsDefault['backend'] = newbackend
503 _backend_mod = backend_mod
504 for func_name in ["new_figure_manager", "draw_if_interactive", "show"]:
505 globals()[func_name].__signature__ = inspect.signature(
506 getattr(backend_mod, func_name))
507
508 # Need to keep a global reference to the backend for compatibility reasons.
509 # See https://github.com/matplotlib/matplotlib/issues/6092
510 matplotlib.backends.backend = newbackend # type: ignore[attr-defined]
511
512 if not cbook._str_equal(old_backend, newbackend):
513 if get_fignums():
514 _api.warn_deprecated("3.8", message=(
515 "Auto-close()ing of figures upon backend switching is deprecated since "
516 "%(since)s and will be removed %(removal)s. To suppress this warning, "
517 "explicitly call plt.close('all') first."))
518 close("all")
519
520 # Make sure the repl display hook is installed in case we become interactive.
521 install_repl_displayhook()
522
523
524def _warn_if_gui_out_of_main_thread() -> None:
525 warn = False
526 canvas_class = cast(type[FigureCanvasBase], _get_backend_mod().FigureCanvas)
527 if canvas_class.required_interactive_framework:
528 if hasattr(threading, 'get_native_id'):
529 # This compares native thread ids because even if Python-level
530 # Thread objects match, the underlying OS thread (which is what
531 # really matters) may be different on Python implementations with
532 # green threads.
533 if threading.get_native_id() != threading.main_thread().native_id:
534 warn = True
535 else:
536 # Fall back to Python-level Thread if native IDs are unavailable,
537 # mainly for PyPy.
538 if threading.current_thread() is not threading.main_thread():
539 warn = True
540 if warn:
541 _api.warn_external(
542 "Starting a Matplotlib GUI outside of the main thread will likely "
543 "fail.")
544
545
546# This function's signature is rewritten upon backend-load by switch_backend.
547def new_figure_manager(*args, **kwargs):
548 """Create a new figure manager instance."""
549 _warn_if_gui_out_of_main_thread()
550 return _get_backend_mod().new_figure_manager(*args, **kwargs)
551
552
553# This function's signature is rewritten upon backend-load by switch_backend.
554def draw_if_interactive(*args, **kwargs):
555 """
556 Redraw the current figure if in interactive mode.
557
558 .. warning::
559
560 End users will typically not have to call this function because the
561 the interactive mode takes care of this.
562 """
563 return _get_backend_mod().draw_if_interactive(*args, **kwargs)
564
565
566# This function's signature is rewritten upon backend-load by switch_backend.
567def show(*args, **kwargs) -> None:
568 """
569 Display all open figures.
570
571 Parameters
572 ----------
573 block : bool, optional
574 Whether to wait for all figures to be closed before returning.
575
576 If `True` block and run the GUI main loop until all figure windows
577 are closed.
578
579 If `False` ensure that all figure windows are displayed and return
580 immediately. In this case, you are responsible for ensuring
581 that the event loop is running to have responsive figures.
582
583 Defaults to True in non-interactive mode and to False in interactive
584 mode (see `.pyplot.isinteractive`).
585
586 See Also
587 --------
588 ion : Enable interactive mode, which shows / updates the figure after
589 every plotting command, so that calling ``show()`` is not necessary.
590 ioff : Disable interactive mode.
591 savefig : Save the figure to an image file instead of showing it on screen.
592
593 Notes
594 -----
595 **Saving figures to file and showing a window at the same time**
596
597 If you want an image file as well as a user interface window, use
598 `.pyplot.savefig` before `.pyplot.show`. At the end of (a blocking)
599 ``show()`` the figure is closed and thus unregistered from pyplot. Calling
600 `.pyplot.savefig` afterwards would save a new and thus empty figure. This
601 limitation of command order does not apply if the show is non-blocking or
602 if you keep a reference to the figure and use `.Figure.savefig`.
603
604 **Auto-show in jupyter notebooks**
605
606 The jupyter backends (activated via ``%matplotlib inline``,
607 ``%matplotlib notebook``, or ``%matplotlib widget``), call ``show()`` at
608 the end of every cell by default. Thus, you usually don't have to call it
609 explicitly there.
610 """
611 _warn_if_gui_out_of_main_thread()
612 return _get_backend_mod().show(*args, **kwargs)
613
614
615def isinteractive() -> bool:
616 """
617 Return whether plots are updated after every plotting command.
618
619 The interactive mode is mainly useful if you build plots from the command
620 line and want to see the effect of each command while you are building the
621 figure.
622
623 In interactive mode:
624
625 - newly created figures will be shown immediately;
626 - figures will automatically redraw on change;
627 - `.pyplot.show` will not block by default.
628
629 In non-interactive mode:
630
631 - newly created figures and changes to figures will not be reflected until
632 explicitly asked to be;
633 - `.pyplot.show` will block by default.
634
635 See Also
636 --------
637 ion : Enable interactive mode.
638 ioff : Disable interactive mode.
639 show : Show all figures (and maybe block).
640 pause : Show all figures, and block for a time.
641 """
642 return matplotlib.is_interactive()
643
644
645# Note: The return type of ioff being AbstractContextManager
646# instead of ExitStack is deliberate.
647# See https://github.com/matplotlib/matplotlib/issues/27659
648# and https://github.com/matplotlib/matplotlib/pull/27667 for more info.
649def ioff() -> AbstractContextManager:
650 """
651 Disable interactive mode.
652
653 See `.pyplot.isinteractive` for more details.
654
655 See Also
656 --------
657 ion : Enable interactive mode.
658 isinteractive : Whether interactive mode is enabled.
659 show : Show all figures (and maybe block).
660 pause : Show all figures, and block for a time.
661
662 Notes
663 -----
664 For a temporary change, this can be used as a context manager::
665
666 # if interactive mode is on
667 # then figures will be shown on creation
668 plt.ion()
669 # This figure will be shown immediately
670 fig = plt.figure()
671
672 with plt.ioff():
673 # interactive mode will be off
674 # figures will not automatically be shown
675 fig2 = plt.figure()
676 # ...
677
678 To enable optional usage as a context manager, this function returns a
679 context manager object, which is not intended to be stored or
680 accessed by the user.
681 """
682 stack = ExitStack()
683 stack.callback(ion if isinteractive() else ioff)
684 matplotlib.interactive(False)
685 uninstall_repl_displayhook()
686 return stack
687
688
689# Note: The return type of ion being AbstractContextManager
690# instead of ExitStack is deliberate.
691# See https://github.com/matplotlib/matplotlib/issues/27659
692# and https://github.com/matplotlib/matplotlib/pull/27667 for more info.
693def ion() -> AbstractContextManager:
694 """
695 Enable interactive mode.
696
697 See `.pyplot.isinteractive` for more details.
698
699 See Also
700 --------
701 ioff : Disable interactive mode.
702 isinteractive : Whether interactive mode is enabled.
703 show : Show all figures (and maybe block).
704 pause : Show all figures, and block for a time.
705
706 Notes
707 -----
708 For a temporary change, this can be used as a context manager::
709
710 # if interactive mode is off
711 # then figures will not be shown on creation
712 plt.ioff()
713 # This figure will not be shown immediately
714 fig = plt.figure()
715
716 with plt.ion():
717 # interactive mode will be on
718 # figures will automatically be shown
719 fig2 = plt.figure()
720 # ...
721
722 To enable optional usage as a context manager, this function returns a
723 context manager object, which is not intended to be stored or
724 accessed by the user.
725 """
726 stack = ExitStack()
727 stack.callback(ion if isinteractive() else ioff)
728 matplotlib.interactive(True)
729 install_repl_displayhook()
730 return stack
731
732
733def pause(interval: float) -> None:
734 """
735 Run the GUI event loop for *interval* seconds.
736
737 If there is an active figure, it will be updated and displayed before the
738 pause, and the GUI event loop (if any) will run during the pause.
739
740 This can be used for crude animation. For more complex animation use
741 :mod:`matplotlib.animation`.
742
743 If there is no active figure, sleep for *interval* seconds instead.
744
745 See Also
746 --------
747 matplotlib.animation : Proper animations
748 show : Show all figures and optional block until all figures are closed.
749 """
750 manager = _pylab_helpers.Gcf.get_active()
751 if manager is not None:
752 canvas = manager.canvas
753 if canvas.figure.stale:
754 canvas.draw_idle()
755 show(block=False)
756 canvas.start_event_loop(interval)
757 else:
758 time.sleep(interval)
759
760
761@_copy_docstring_and_deprecators(matplotlib.rc)
762def rc(group: str, **kwargs) -> None:
763 matplotlib.rc(group, **kwargs)
764
765
766@_copy_docstring_and_deprecators(matplotlib.rc_context)
767def rc_context(
768 rc: dict[str, Any] | None = None,
769 fname: str | pathlib.Path | os.PathLike | None = None,
770) -> AbstractContextManager[None]:
771 return matplotlib.rc_context(rc, fname)
772
773
774@_copy_docstring_and_deprecators(matplotlib.rcdefaults)
775def rcdefaults() -> None:
776 matplotlib.rcdefaults()
777 if matplotlib.is_interactive():
778 draw_all()
779
780
781# getp/get/setp are explicitly reexported so that they show up in pyplot docs.
782
783
784@_copy_docstring_and_deprecators(matplotlib.artist.getp)
785def getp(obj, *args, **kwargs):
786 return matplotlib.artist.getp(obj, *args, **kwargs)
787
788
789@_copy_docstring_and_deprecators(matplotlib.artist.get)
790def get(obj, *args, **kwargs):
791 return matplotlib.artist.get(obj, *args, **kwargs)
792
793
794@_copy_docstring_and_deprecators(matplotlib.artist.setp)
795def setp(obj, *args, **kwargs):
796 return matplotlib.artist.setp(obj, *args, **kwargs)
797
798
799def xkcd(
800 scale: float = 1, length: float = 100, randomness: float = 2
801) -> ExitStack:
802 """
803 Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode.
804
805 This will only have an effect on things drawn after this function is called.
806
807 For best results, install the `xkcd script <https://github.com/ipython/xkcd-font/>`_
808 font; xkcd fonts are not packaged with Matplotlib.
809
810 Parameters
811 ----------
812 scale : float, optional
813 The amplitude of the wiggle perpendicular to the source line.
814 length : float, optional
815 The length of the wiggle along the line.
816 randomness : float, optional
817 The scale factor by which the length is shrunken or expanded.
818
819 Notes
820 -----
821 This function works by a number of rcParams, so it will probably
822 override others you have set before.
823
824 If you want the effects of this function to be temporary, it can
825 be used as a context manager, for example::
826
827 with plt.xkcd():
828 # This figure will be in XKCD-style
829 fig1 = plt.figure()
830 # ...
831
832 # This figure will be in regular style
833 fig2 = plt.figure()
834 """
835 # This cannot be implemented in terms of contextmanager() or rc_context()
836 # because this needs to work as a non-contextmanager too.
837
838 if rcParams['text.usetex']:
839 raise RuntimeError(
840 "xkcd mode is not compatible with text.usetex = True")
841
842 stack = ExitStack()
843 stack.callback(dict.update, rcParams, rcParams.copy()) # type: ignore[arg-type]
844
845 from matplotlib import patheffects
846 rcParams.update({
847 'font.family': ['xkcd', 'xkcd Script', 'Comic Neue', 'Comic Sans MS'],
848 'font.size': 14.0,
849 'path.sketch': (scale, length, randomness),
850 'path.effects': [
851 patheffects.withStroke(linewidth=4, foreground="w")],
852 'axes.linewidth': 1.5,
853 'lines.linewidth': 2.0,
854 'figure.facecolor': 'white',
855 'grid.linewidth': 0.0,
856 'axes.grid': False,
857 'axes.unicode_minus': False,
858 'axes.edgecolor': 'black',
859 'xtick.major.size': 8,
860 'xtick.major.width': 3,
861 'ytick.major.size': 8,
862 'ytick.major.width': 3,
863 })
864
865 return stack
866
867
868## Figures ##
869
870def figure(
871 # autoincrement if None, else integer from 1-N
872 num: int | str | Figure | SubFigure | None = None,
873 # defaults to rc figure.figsize
874 figsize: tuple[float, float] | None = None,
875 # defaults to rc figure.dpi
876 dpi: float | None = None,
877 *,
878 # defaults to rc figure.facecolor
879 facecolor: ColorType | None = None,
880 # defaults to rc figure.edgecolor
881 edgecolor: ColorType | None = None,
882 frameon: bool = True,
883 FigureClass: type[Figure] = Figure,
884 clear: bool = False,
885 **kwargs
886) -> Figure:
887 """
888 Create a new figure, or activate an existing figure.
889
890 Parameters
891 ----------
892 num : int or str or `.Figure` or `.SubFigure`, optional
893 A unique identifier for the figure.
894
895 If a figure with that identifier already exists, this figure is made
896 active and returned. An integer refers to the ``Figure.number``
897 attribute, a string refers to the figure label.
898
899 If there is no figure with the identifier or *num* is not given, a new
900 figure is created, made active and returned. If *num* is an int, it
901 will be used for the ``Figure.number`` attribute, otherwise, an
902 auto-generated integer value is used (starting at 1 and incremented
903 for each new figure). If *num* is a string, the figure label and the
904 window title is set to this value. If num is a ``SubFigure``, its
905 parent ``Figure`` is activated.
906
907 figsize : (float, float), default: :rc:`figure.figsize`
908 Width, height in inches.
909
910 dpi : float, default: :rc:`figure.dpi`
911 The resolution of the figure in dots-per-inch.
912
913 facecolor : :mpltype:`color`, default: :rc:`figure.facecolor`
914 The background color.
915
916 edgecolor : :mpltype:`color`, default: :rc:`figure.edgecolor`
917 The border color.
918
919 frameon : bool, default: True
920 If False, suppress drawing the figure frame.
921
922 FigureClass : subclass of `~matplotlib.figure.Figure`
923 If set, an instance of this subclass will be created, rather than a
924 plain `.Figure`.
925
926 clear : bool, default: False
927 If True and the figure already exists, then it is cleared.
928
929 layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None}, \
930default: None
931 The layout mechanism for positioning of plot elements to avoid
932 overlapping Axes decorations (labels, ticks, etc). Note that layout
933 managers can measurably slow down figure display.
934
935 - 'constrained': The constrained layout solver adjusts Axes sizes
936 to avoid overlapping Axes decorations. Can handle complex plot
937 layouts and colorbars, and is thus recommended.
938
939 See :ref:`constrainedlayout_guide`
940 for examples.
941
942 - 'compressed': uses the same algorithm as 'constrained', but
943 removes extra space between fixed-aspect-ratio Axes. Best for
944 simple grids of Axes.
945
946 - 'tight': Use the tight layout mechanism. This is a relatively
947 simple algorithm that adjusts the subplot parameters so that
948 decorations do not overlap. See `.Figure.set_tight_layout` for
949 further details.
950
951 - 'none': Do not use a layout engine.
952
953 - A `.LayoutEngine` instance. Builtin layout classes are
954 `.ConstrainedLayoutEngine` and `.TightLayoutEngine`, more easily
955 accessible by 'constrained' and 'tight'. Passing an instance
956 allows third parties to provide their own layout engine.
957
958 If not given, fall back to using the parameters *tight_layout* and
959 *constrained_layout*, including their config defaults
960 :rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`.
961
962 **kwargs
963 Additional keyword arguments are passed to the `.Figure` constructor.
964
965 Returns
966 -------
967 `~matplotlib.figure.Figure`
968
969 Notes
970 -----
971 A newly created figure is passed to the `~.FigureCanvasBase.new_manager`
972 method or the `new_figure_manager` function provided by the current
973 backend, which install a canvas and a manager on the figure.
974
975 Once this is done, :rc:`figure.hooks` are called, one at a time, on the
976 figure; these hooks allow arbitrary customization of the figure (e.g.,
977 attaching callbacks) or of associated elements (e.g., modifying the
978 toolbar). See :doc:`/gallery/user_interfaces/mplcvd` for an example of
979 toolbar customization.
980
981 If you are creating many figures, make sure you explicitly call
982 `.pyplot.close` on the figures you are not using, because this will
983 enable pyplot to properly clean up the memory.
984
985 `~matplotlib.rcParams` defines the default values, which can be modified
986 in the matplotlibrc file.
987 """
988 if isinstance(num, FigureBase):
989 # type narrowed to `Figure | SubFigure` by combination of input and isinstance
990 if num.canvas.manager is None:
991 raise ValueError("The passed figure is not managed by pyplot")
992 _pylab_helpers.Gcf.set_active(num.canvas.manager)
993 return num.figure
994
995 allnums = get_fignums()
996 next_num = max(allnums) + 1 if allnums else 1
997 fig_label = ''
998 if num is None:
999 num = next_num
1000 elif isinstance(num, str):
1001 fig_label = num
1002 all_labels = get_figlabels()
1003 if fig_label not in all_labels:
1004 if fig_label == 'all':
1005 _api.warn_external("close('all') closes all existing figures.")
1006 num = next_num
1007 else:
1008 inum = all_labels.index(fig_label)
1009 num = allnums[inum]
1010 else:
1011 num = int(num) # crude validation of num argument
1012
1013 # Type of "num" has narrowed to int, but mypy can't quite see it
1014 manager = _pylab_helpers.Gcf.get_fig_manager(num) # type: ignore[arg-type]
1015 if manager is None:
1016 max_open_warning = rcParams['figure.max_open_warning']
1017 if len(allnums) == max_open_warning >= 1:
1018 _api.warn_external(
1019 f"More than {max_open_warning} figures have been opened. "
1020 f"Figures created through the pyplot interface "
1021 f"(`matplotlib.pyplot.figure`) are retained until explicitly "
1022 f"closed and may consume too much memory. (To control this "
1023 f"warning, see the rcParam `figure.max_open_warning`). "
1024 f"Consider using `matplotlib.pyplot.close()`.",
1025 RuntimeWarning)
1026
1027 manager = new_figure_manager(
1028 num, figsize=figsize, dpi=dpi,
1029 facecolor=facecolor, edgecolor=edgecolor, frameon=frameon,
1030 FigureClass=FigureClass, **kwargs)
1031 fig = manager.canvas.figure
1032 if fig_label:
1033 fig.set_label(fig_label)
1034
1035 for hookspecs in rcParams["figure.hooks"]:
1036 module_name, dotted_name = hookspecs.split(":")
1037 obj: Any = importlib.import_module(module_name)
1038 for part in dotted_name.split("."):
1039 obj = getattr(obj, part)
1040 obj(fig)
1041
1042 _pylab_helpers.Gcf._set_new_active_manager(manager)
1043
1044 # make sure backends (inline) that we don't ship that expect this
1045 # to be called in plotting commands to make the figure call show
1046 # still work. There is probably a better way to do this in the
1047 # FigureManager base class.
1048 draw_if_interactive()
1049
1050 if _REPL_DISPLAYHOOK is _ReplDisplayHook.PLAIN:
1051 fig.stale_callback = _auto_draw_if_interactive
1052
1053 if clear:
1054 manager.canvas.figure.clear()
1055
1056 return manager.canvas.figure
1057
1058
1059def _auto_draw_if_interactive(fig, val):
1060 """
1061 An internal helper function for making sure that auto-redrawing
1062 works as intended in the plain python repl.
1063
1064 Parameters
1065 ----------
1066 fig : Figure
1067 A figure object which is assumed to be associated with a canvas
1068 """
1069 if (val and matplotlib.is_interactive()
1070 and not fig.canvas.is_saving()
1071 and not fig.canvas._is_idle_drawing):
1072 # Some artists can mark themselves as stale in the middle of drawing
1073 # (e.g. axes position & tick labels being computed at draw time), but
1074 # this shouldn't trigger a redraw because the current redraw will
1075 # already take them into account.
1076 with fig.canvas._idle_draw_cntx():
1077 fig.canvas.draw_idle()
1078
1079
1080def gcf() -> Figure:
1081 """
1082 Get the current figure.
1083
1084 If there is currently no figure on the pyplot figure stack, a new one is
1085 created using `~.pyplot.figure()`. (To test whether there is currently a
1086 figure on the pyplot figure stack, check whether `~.pyplot.get_fignums()`
1087 is empty.)
1088 """
1089 manager = _pylab_helpers.Gcf.get_active()
1090 if manager is not None:
1091 return manager.canvas.figure
1092 else:
1093 return figure()
1094
1095
1096def fignum_exists(num: int | str) -> bool:
1097 """
1098 Return whether the figure with the given id exists.
1099
1100 Parameters
1101 ----------
1102 num : int or str
1103 A figure identifier.
1104
1105 Returns
1106 -------
1107 bool
1108 Whether or not a figure with id *num* exists.
1109 """
1110 return (
1111 _pylab_helpers.Gcf.has_fignum(num)
1112 if isinstance(num, int)
1113 else num in get_figlabels()
1114 )
1115
1116
1117def get_fignums() -> list[int]:
1118 """Return a list of existing figure numbers."""
1119 return sorted(_pylab_helpers.Gcf.figs)
1120
1121
1122def get_figlabels() -> list[Any]:
1123 """Return a list of existing figure labels."""
1124 managers = _pylab_helpers.Gcf.get_all_fig_managers()
1125 managers.sort(key=lambda m: m.num)
1126 return [m.canvas.figure.get_label() for m in managers]
1127
1128
1129def get_current_fig_manager() -> FigureManagerBase | None:
1130 """
1131 Return the figure manager of the current figure.
1132
1133 The figure manager is a container for the actual backend-depended window
1134 that displays the figure on screen.
1135
1136 If no current figure exists, a new one is created, and its figure
1137 manager is returned.
1138
1139 Returns
1140 -------
1141 `.FigureManagerBase` or backend-dependent subclass thereof
1142 """
1143 return gcf().canvas.manager
1144
1145
1146@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_connect)
1147def connect(s: str, func: Callable[[Event], Any]) -> int:
1148 return gcf().canvas.mpl_connect(s, func)
1149
1150
1151@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_disconnect)
1152def disconnect(cid: int) -> None:
1153 gcf().canvas.mpl_disconnect(cid)
1154
1155
1156def close(fig: None | int | str | Figure | Literal["all"] = None) -> None:
1157 """
1158 Close a figure window.
1159
1160 Parameters
1161 ----------
1162 fig : None or int or str or `.Figure`
1163 The figure to close. There are a number of ways to specify this:
1164
1165 - *None*: the current figure
1166 - `.Figure`: the given `.Figure` instance
1167 - ``int``: a figure number
1168 - ``str``: a figure name
1169 - 'all': all figures
1170
1171 """
1172 if fig is None:
1173 manager = _pylab_helpers.Gcf.get_active()
1174 if manager is None:
1175 return
1176 else:
1177 _pylab_helpers.Gcf.destroy(manager)
1178 elif fig == 'all':
1179 _pylab_helpers.Gcf.destroy_all()
1180 elif isinstance(fig, int):
1181 _pylab_helpers.Gcf.destroy(fig)
1182 elif hasattr(fig, 'int'):
1183 # if we are dealing with a type UUID, we
1184 # can use its integer representation
1185 _pylab_helpers.Gcf.destroy(fig.int)
1186 elif isinstance(fig, str):
1187 all_labels = get_figlabels()
1188 if fig in all_labels:
1189 num = get_fignums()[all_labels.index(fig)]
1190 _pylab_helpers.Gcf.destroy(num)
1191 elif isinstance(fig, Figure):
1192 _pylab_helpers.Gcf.destroy_fig(fig)
1193 else:
1194 raise TypeError("close() argument must be a Figure, an int, a string, "
1195 "or None, not %s" % type(fig))
1196
1197
1198def clf() -> None:
1199 """Clear the current figure."""
1200 gcf().clear()
1201
1202
1203def draw() -> None:
1204 """
1205 Redraw the current figure.
1206
1207 This is used to update a figure that has been altered, but not
1208 automatically re-drawn. If interactive mode is on (via `.ion()`), this
1209 should be only rarely needed, but there may be ways to modify the state of
1210 a figure without marking it as "stale". Please report these cases as bugs.
1211
1212 This is equivalent to calling ``fig.canvas.draw_idle()``, where ``fig`` is
1213 the current figure.
1214
1215 See Also
1216 --------
1217 .FigureCanvasBase.draw_idle
1218 .FigureCanvasBase.draw
1219 """
1220 gcf().canvas.draw_idle()
1221
1222
1223@_copy_docstring_and_deprecators(Figure.savefig)
1224def savefig(*args, **kwargs) -> None:
1225 fig = gcf()
1226 # savefig default implementation has no return, so mypy is unhappy
1227 # presumably this is here because subclasses can return?
1228 res = fig.savefig(*args, **kwargs) # type: ignore[func-returns-value]
1229 fig.canvas.draw_idle() # Need this if 'transparent=True', to reset colors.
1230 return res
1231
1232
1233## Putting things in figures ##
1234
1235
1236def figlegend(*args, **kwargs) -> Legend:
1237 return gcf().legend(*args, **kwargs)
1238if Figure.legend.__doc__:
1239 figlegend.__doc__ = Figure.legend.__doc__ \
1240 .replace(" legend(", " figlegend(") \
1241 .replace("fig.legend(", "plt.figlegend(") \
1242 .replace("ax.plot(", "plt.plot(")
1243
1244
1245## Axes ##
1246
1247@_docstring.dedent_interpd
1248def axes(
1249 arg: None | tuple[float, float, float, float] = None,
1250 **kwargs
1251) -> matplotlib.axes.Axes:
1252 """
1253 Add an Axes to the current figure and make it the current Axes.
1254
1255 Call signatures::
1256
1257 plt.axes()
1258 plt.axes(rect, projection=None, polar=False, **kwargs)
1259 plt.axes(ax)
1260
1261 Parameters
1262 ----------
1263 arg : None or 4-tuple
1264 The exact behavior of this function depends on the type:
1265
1266 - *None*: A new full window Axes is added using
1267 ``subplot(**kwargs)``.
1268 - 4-tuple of floats *rect* = ``(left, bottom, width, height)``.
1269 A new Axes is added with dimensions *rect* in normalized
1270 (0, 1) units using `~.Figure.add_axes` on the current figure.
1271
1272 projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
1273'polar', 'rectilinear', str}, optional
1274 The projection type of the `~.axes.Axes`. *str* is the name of
1275 a custom projection, see `~matplotlib.projections`. The default
1276 None results in a 'rectilinear' projection.
1277
1278 polar : bool, default: False
1279 If True, equivalent to projection='polar'.
1280
1281 sharex, sharey : `~matplotlib.axes.Axes`, optional
1282 Share the x or y `~matplotlib.axis` with sharex and/or sharey.
1283 The axis will have the same limits, ticks, and scale as the axis
1284 of the shared Axes.
1285
1286 label : str
1287 A label for the returned Axes.
1288
1289 Returns
1290 -------
1291 `~.axes.Axes`, or a subclass of `~.axes.Axes`
1292 The returned Axes class depends on the projection used. It is
1293 `~.axes.Axes` if rectilinear projection is used and
1294 `.projections.polar.PolarAxes` if polar projection is used.
1295
1296 Other Parameters
1297 ----------------
1298 **kwargs
1299 This method also takes the keyword arguments for
1300 the returned Axes class. The keyword arguments for the
1301 rectilinear Axes class `~.axes.Axes` can be found in
1302 the following table but there might also be other keyword
1303 arguments if another projection is used, see the actual Axes
1304 class.
1305
1306 %(Axes:kwdoc)s
1307
1308 See Also
1309 --------
1310 .Figure.add_axes
1311 .pyplot.subplot
1312 .Figure.add_subplot
1313 .Figure.subplots
1314 .pyplot.subplots
1315
1316 Examples
1317 --------
1318 ::
1319
1320 # Creating a new full window Axes
1321 plt.axes()
1322
1323 # Creating a new Axes with specified dimensions and a grey background
1324 plt.axes((left, bottom, width, height), facecolor='grey')
1325 """
1326 fig = gcf()
1327 pos = kwargs.pop('position', None)
1328 if arg is None:
1329 if pos is None:
1330 return fig.add_subplot(**kwargs)
1331 else:
1332 return fig.add_axes(pos, **kwargs)
1333 else:
1334 return fig.add_axes(arg, **kwargs)
1335
1336
1337def delaxes(ax: matplotlib.axes.Axes | None = None) -> None:
1338 """
1339 Remove an `~.axes.Axes` (defaulting to the current Axes) from its figure.
1340 """
1341 if ax is None:
1342 ax = gca()
1343 ax.remove()
1344
1345
1346def sca(ax: Axes) -> None:
1347 """
1348 Set the current Axes to *ax* and the current Figure to the parent of *ax*.
1349 """
1350 # Mypy sees ax.figure as potentially None,
1351 # but if you are calling this, it won't be None
1352 # Additionally the slight difference between `Figure` and `FigureBase` mypy catches
1353 figure(ax.figure) # type: ignore[arg-type]
1354 ax.figure.sca(ax) # type: ignore[union-attr]
1355
1356
1357def cla() -> None:
1358 """Clear the current Axes."""
1359 # Not generated via boilerplate.py to allow a different docstring.
1360 return gca().cla()
1361
1362
1363## More ways of creating Axes ##
1364
1365@_docstring.dedent_interpd
1366def subplot(*args, **kwargs) -> Axes:
1367 """
1368 Add an Axes to the current figure or retrieve an existing Axes.
1369
1370 This is a wrapper of `.Figure.add_subplot` which provides additional
1371 behavior when working with the implicit API (see the notes section).
1372
1373 Call signatures::
1374
1375 subplot(nrows, ncols, index, **kwargs)
1376 subplot(pos, **kwargs)
1377 subplot(**kwargs)
1378 subplot(ax)
1379
1380 Parameters
1381 ----------
1382 *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
1383 The position of the subplot described by one of
1384
1385 - Three integers (*nrows*, *ncols*, *index*). The subplot will take the
1386 *index* position on a grid with *nrows* rows and *ncols* columns.
1387 *index* starts at 1 in the upper left corner and increases to the
1388 right. *index* can also be a two-tuple specifying the (*first*,
1389 *last*) indices (1-based, and including *last*) of the subplot, e.g.,
1390 ``fig.add_subplot(3, 1, (1, 2))`` makes a subplot that spans the
1391 upper 2/3 of the figure.
1392 - A 3-digit integer. The digits are interpreted as if given separately
1393 as three single-digit integers, i.e. ``fig.add_subplot(235)`` is the
1394 same as ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
1395 if there are no more than 9 subplots.
1396 - A `.SubplotSpec`.
1397
1398 projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
1399'polar', 'rectilinear', str}, optional
1400 The projection type of the subplot (`~.axes.Axes`). *str* is the name
1401 of a custom projection, see `~matplotlib.projections`. The default
1402 None results in a 'rectilinear' projection.
1403
1404 polar : bool, default: False
1405 If True, equivalent to projection='polar'.
1406
1407 sharex, sharey : `~matplotlib.axes.Axes`, optional
1408 Share the x or y `~matplotlib.axis` with sharex and/or sharey. The
1409 axis will have the same limits, ticks, and scale as the axis of the
1410 shared Axes.
1411
1412 label : str
1413 A label for the returned Axes.
1414
1415 Returns
1416 -------
1417 `~.axes.Axes`
1418
1419 The Axes of the subplot. The returned Axes can actually be an instance
1420 of a subclass, such as `.projections.polar.PolarAxes` for polar
1421 projections.
1422
1423 Other Parameters
1424 ----------------
1425 **kwargs
1426 This method also takes the keyword arguments for the returned Axes
1427 base class; except for the *figure* argument. The keyword arguments
1428 for the rectilinear base class `~.axes.Axes` can be found in
1429 the following table but there might also be other keyword
1430 arguments if another projection is used.
1431
1432 %(Axes:kwdoc)s
1433
1434 Notes
1435 -----
1436 Creating a new Axes will delete any preexisting Axes that
1437 overlaps with it beyond sharing a boundary::
1438
1439 import matplotlib.pyplot as plt
1440 # plot a line, implicitly creating a subplot(111)
1441 plt.plot([1, 2, 3])
1442 # now create a subplot which represents the top plot of a grid
1443 # with 2 rows and 1 column. Since this subplot will overlap the
1444 # first, the plot (and its Axes) previously created, will be removed
1445 plt.subplot(211)
1446
1447 If you do not want this behavior, use the `.Figure.add_subplot` method
1448 or the `.pyplot.axes` function instead.
1449
1450 If no *kwargs* are passed and there exists an Axes in the location
1451 specified by *args* then that Axes will be returned rather than a new
1452 Axes being created.
1453
1454 If *kwargs* are passed and there exists an Axes in the location
1455 specified by *args*, the projection type is the same, and the
1456 *kwargs* match with the existing Axes, then the existing Axes is
1457 returned. Otherwise a new Axes is created with the specified
1458 parameters. We save a reference to the *kwargs* which we use
1459 for this comparison. If any of the values in *kwargs* are
1460 mutable we will not detect the case where they are mutated.
1461 In these cases we suggest using `.Figure.add_subplot` and the
1462 explicit Axes API rather than the implicit pyplot API.
1463
1464 See Also
1465 --------
1466 .Figure.add_subplot
1467 .pyplot.subplots
1468 .pyplot.axes
1469 .Figure.subplots
1470
1471 Examples
1472 --------
1473 ::
1474
1475 plt.subplot(221)
1476
1477 # equivalent but more general
1478 ax1 = plt.subplot(2, 2, 1)
1479
1480 # add a subplot with no frame
1481 ax2 = plt.subplot(222, frameon=False)
1482
1483 # add a polar subplot
1484 plt.subplot(223, projection='polar')
1485
1486 # add a red subplot that shares the x-axis with ax1
1487 plt.subplot(224, sharex=ax1, facecolor='red')
1488
1489 # delete ax2 from the figure
1490 plt.delaxes(ax2)
1491
1492 # add ax2 to the figure again
1493 plt.subplot(ax2)
1494
1495 # make the first Axes "current" again
1496 plt.subplot(221)
1497
1498 """
1499 # Here we will only normalize `polar=True` vs `projection='polar'` and let
1500 # downstream code deal with the rest.
1501 unset = object()
1502 projection = kwargs.get('projection', unset)
1503 polar = kwargs.pop('polar', unset)
1504 if polar is not unset and polar:
1505 # if we got mixed messages from the user, raise
1506 if projection is not unset and projection != 'polar':
1507 raise ValueError(
1508 f"polar={polar}, yet projection={projection!r}. "
1509 "Only one of these arguments should be supplied."
1510 )
1511 kwargs['projection'] = projection = 'polar'
1512
1513 # if subplot called without arguments, create subplot(1, 1, 1)
1514 if len(args) == 0:
1515 args = (1, 1, 1)
1516
1517 # This check was added because it is very easy to type subplot(1, 2, False)
1518 # when subplots(1, 2, False) was intended (sharex=False, that is). In most
1519 # cases, no error will ever occur, but mysterious behavior can result
1520 # because what was intended to be the sharex argument is instead treated as
1521 # a subplot index for subplot()
1522 if len(args) >= 3 and isinstance(args[2], bool):
1523 _api.warn_external("The subplot index argument to subplot() appears "
1524 "to be a boolean. Did you intend to use "
1525 "subplots()?")
1526 # Check for nrows and ncols, which are not valid subplot args:
1527 if 'nrows' in kwargs or 'ncols' in kwargs:
1528 raise TypeError("subplot() got an unexpected keyword argument 'ncols' "
1529 "and/or 'nrows'. Did you intend to call subplots()?")
1530
1531 fig = gcf()
1532
1533 # First, search for an existing subplot with a matching spec.
1534 key = SubplotSpec._from_subplot_args(fig, args)
1535
1536 for ax in fig.axes:
1537 # If we found an Axes at the position, we can reuse it if the user passed no
1538 # kwargs or if the Axes class and kwargs are identical.
1539 if (ax.get_subplotspec() == key
1540 and (kwargs == {}
1541 or (ax._projection_init
1542 == fig._process_projection_requirements(**kwargs)))):
1543 break
1544 else:
1545 # we have exhausted the known Axes and none match, make a new one!
1546 ax = fig.add_subplot(*args, **kwargs)
1547
1548 fig.sca(ax)
1549
1550 return ax
1551
1552
1553@overload
1554def subplots(
1555 nrows: Literal[1] = ...,
1556 ncols: Literal[1] = ...,
1557 *,
1558 sharex: bool | Literal["none", "all", "row", "col"] = ...,
1559 sharey: bool | Literal["none", "all", "row", "col"] = ...,
1560 squeeze: Literal[True] = ...,
1561 width_ratios: Sequence[float] | None = ...,
1562 height_ratios: Sequence[float] | None = ...,
1563 subplot_kw: dict[str, Any] | None = ...,
1564 gridspec_kw: dict[str, Any] | None = ...,
1565 **fig_kw
1566) -> tuple[Figure, Axes]:
1567 ...
1568
1569
1570@overload
1571def subplots(
1572 nrows: int = ...,
1573 ncols: int = ...,
1574 *,
1575 sharex: bool | Literal["none", "all", "row", "col"] = ...,
1576 sharey: bool | Literal["none", "all", "row", "col"] = ...,
1577 squeeze: Literal[False],
1578 width_ratios: Sequence[float] | None = ...,
1579 height_ratios: Sequence[float] | None = ...,
1580 subplot_kw: dict[str, Any] | None = ...,
1581 gridspec_kw: dict[str, Any] | None = ...,
1582 **fig_kw
1583) -> tuple[Figure, np.ndarray]: # TODO numpy/numpy#24738
1584 ...
1585
1586
1587@overload
1588def subplots(
1589 nrows: int = ...,
1590 ncols: int = ...,
1591 *,
1592 sharex: bool | Literal["none", "all", "row", "col"] = ...,
1593 sharey: bool | Literal["none", "all", "row", "col"] = ...,
1594 squeeze: bool = ...,
1595 width_ratios: Sequence[float] | None = ...,
1596 height_ratios: Sequence[float] | None = ...,
1597 subplot_kw: dict[str, Any] | None = ...,
1598 gridspec_kw: dict[str, Any] | None = ...,
1599 **fig_kw
1600) -> tuple[Figure, Any]:
1601 ...
1602
1603
1604def subplots(
1605 nrows: int = 1, ncols: int = 1, *,
1606 sharex: bool | Literal["none", "all", "row", "col"] = False,
1607 sharey: bool | Literal["none", "all", "row", "col"] = False,
1608 squeeze: bool = True,
1609 width_ratios: Sequence[float] | None = None,
1610 height_ratios: Sequence[float] | None = None,
1611 subplot_kw: dict[str, Any] | None = None,
1612 gridspec_kw: dict[str, Any] | None = None,
1613 **fig_kw
1614) -> tuple[Figure, Any]:
1615 """
1616 Create a figure and a set of subplots.
1617
1618 This utility wrapper makes it convenient to create common layouts of
1619 subplots, including the enclosing figure object, in a single call.
1620
1621 Parameters
1622 ----------
1623 nrows, ncols : int, default: 1
1624 Number of rows/columns of the subplot grid.
1625
1626 sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
1627 Controls sharing of properties among x (*sharex*) or y (*sharey*)
1628 axes:
1629
1630 - True or 'all': x- or y-axis will be shared among all subplots.
1631 - False or 'none': each subplot x- or y-axis will be independent.
1632 - 'row': each subplot row will share an x- or y-axis.
1633 - 'col': each subplot column will share an x- or y-axis.
1634
1635 When subplots have a shared x-axis along a column, only the x tick
1636 labels of the bottom subplot are created. Similarly, when subplots
1637 have a shared y-axis along a row, only the y tick labels of the first
1638 column subplot are created. To later turn other subplots' ticklabels
1639 on, use `~matplotlib.axes.Axes.tick_params`.
1640
1641 When subplots have a shared axis that has units, calling
1642 `.Axis.set_units` will update each axis with the new units.
1643
1644 Note that it is not possible to unshare axes.
1645
1646 squeeze : bool, default: True
1647 - If True, extra dimensions are squeezed out from the returned
1648 array of `~matplotlib.axes.Axes`:
1649
1650 - if only one subplot is constructed (nrows=ncols=1), the
1651 resulting single Axes object is returned as a scalar.
1652 - for Nx1 or 1xM subplots, the returned object is a 1D numpy
1653 object array of Axes objects.
1654 - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
1655
1656 - If False, no squeezing at all is done: the returned Axes object is
1657 always a 2D array containing Axes instances, even if it ends up
1658 being 1x1.
1659
1660 width_ratios : array-like of length *ncols*, optional
1661 Defines the relative widths of the columns. Each column gets a
1662 relative width of ``width_ratios[i] / sum(width_ratios)``.
1663 If not given, all columns will have the same width. Equivalent
1664 to ``gridspec_kw={'width_ratios': [...]}``.
1665
1666 height_ratios : array-like of length *nrows*, optional
1667 Defines the relative heights of the rows. Each row gets a
1668 relative height of ``height_ratios[i] / sum(height_ratios)``.
1669 If not given, all rows will have the same height. Convenience
1670 for ``gridspec_kw={'height_ratios': [...]}``.
1671
1672 subplot_kw : dict, optional
1673 Dict with keywords passed to the
1674 `~matplotlib.figure.Figure.add_subplot` call used to create each
1675 subplot.
1676
1677 gridspec_kw : dict, optional
1678 Dict with keywords passed to the `~matplotlib.gridspec.GridSpec`
1679 constructor used to create the grid the subplots are placed on.
1680
1681 **fig_kw
1682 All additional keyword arguments are passed to the
1683 `.pyplot.figure` call.
1684
1685 Returns
1686 -------
1687 fig : `.Figure`
1688
1689 ax : `~matplotlib.axes.Axes` or array of Axes
1690 *ax* can be either a single `~.axes.Axes` object, or an array of Axes
1691 objects if more than one subplot was created. The dimensions of the
1692 resulting array can be controlled with the squeeze keyword, see above.
1693
1694 Typical idioms for handling the return value are::
1695
1696 # using the variable ax for single a Axes
1697 fig, ax = plt.subplots()
1698
1699 # using the variable axs for multiple Axes
1700 fig, axs = plt.subplots(2, 2)
1701
1702 # using tuple unpacking for multiple Axes
1703 fig, (ax1, ax2) = plt.subplots(1, 2)
1704 fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
1705
1706 The names ``ax`` and pluralized ``axs`` are preferred over ``axes``
1707 because for the latter it's not clear if it refers to a single
1708 `~.axes.Axes` instance or a collection of these.
1709
1710 See Also
1711 --------
1712 .pyplot.figure
1713 .pyplot.subplot
1714 .pyplot.axes
1715 .Figure.subplots
1716 .Figure.add_subplot
1717
1718 Examples
1719 --------
1720 ::
1721
1722 # First create some toy data:
1723 x = np.linspace(0, 2*np.pi, 400)
1724 y = np.sin(x**2)
1725
1726 # Create just a figure and only one subplot
1727 fig, ax = plt.subplots()
1728 ax.plot(x, y)
1729 ax.set_title('Simple plot')
1730
1731 # Create two subplots and unpack the output array immediately
1732 f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
1733 ax1.plot(x, y)
1734 ax1.set_title('Sharing Y axis')
1735 ax2.scatter(x, y)
1736
1737 # Create four polar Axes and access them through the returned array
1738 fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
1739 axs[0, 0].plot(x, y)
1740 axs[1, 1].scatter(x, y)
1741
1742 # Share a X axis with each column of subplots
1743 plt.subplots(2, 2, sharex='col')
1744
1745 # Share a Y axis with each row of subplots
1746 plt.subplots(2, 2, sharey='row')
1747
1748 # Share both X and Y axes with all subplots
1749 plt.subplots(2, 2, sharex='all', sharey='all')
1750
1751 # Note that this is the same as
1752 plt.subplots(2, 2, sharex=True, sharey=True)
1753
1754 # Create figure number 10 with a single subplot
1755 # and clears it if it already exists.
1756 fig, ax = plt.subplots(num=10, clear=True)
1757
1758 """
1759 fig = figure(**fig_kw)
1760 axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
1761 squeeze=squeeze, subplot_kw=subplot_kw,
1762 gridspec_kw=gridspec_kw, height_ratios=height_ratios,
1763 width_ratios=width_ratios)
1764 return fig, axs
1765
1766
1767@overload
1768def subplot_mosaic(
1769 mosaic: str,
1770 *,
1771 sharex: bool = ...,
1772 sharey: bool = ...,
1773 width_ratios: ArrayLike | None = ...,
1774 height_ratios: ArrayLike | None = ...,
1775 empty_sentinel: str = ...,
1776 subplot_kw: dict[str, Any] | None = ...,
1777 gridspec_kw: dict[str, Any] | None = ...,
1778 per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | None = ...,
1779 **fig_kw: Any
1780) -> tuple[Figure, dict[str, matplotlib.axes.Axes]]: ...
1781
1782
1783@overload
1784def subplot_mosaic(
1785 mosaic: list[HashableList[_T]],
1786 *,
1787 sharex: bool = ...,
1788 sharey: bool = ...,
1789 width_ratios: ArrayLike | None = ...,
1790 height_ratios: ArrayLike | None = ...,
1791 empty_sentinel: _T = ...,
1792 subplot_kw: dict[str, Any] | None = ...,
1793 gridspec_kw: dict[str, Any] | None = ...,
1794 per_subplot_kw: dict[_T | tuple[_T, ...], dict[str, Any]] | None = ...,
1795 **fig_kw: Any
1796) -> tuple[Figure, dict[_T, matplotlib.axes.Axes]]: ...
1797
1798
1799@overload
1800def subplot_mosaic(
1801 mosaic: list[HashableList[Hashable]],
1802 *,
1803 sharex: bool = ...,
1804 sharey: bool = ...,
1805 width_ratios: ArrayLike | None = ...,
1806 height_ratios: ArrayLike | None = ...,
1807 empty_sentinel: Any = ...,
1808 subplot_kw: dict[str, Any] | None = ...,
1809 gridspec_kw: dict[str, Any] | None = ...,
1810 per_subplot_kw: dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = ...,
1811 **fig_kw: Any
1812) -> tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]: ...
1813
1814
1815def subplot_mosaic(
1816 mosaic: str | list[HashableList[_T]] | list[HashableList[Hashable]],
1817 *,
1818 sharex: bool = False,
1819 sharey: bool = False,
1820 width_ratios: ArrayLike | None = None,
1821 height_ratios: ArrayLike | None = None,
1822 empty_sentinel: Any = '.',
1823 subplot_kw: dict[str, Any] | None = None,
1824 gridspec_kw: dict[str, Any] | None = None,
1825 per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] |
1826 dict[_T | tuple[_T, ...], dict[str, Any]] |
1827 dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = None,
1828 **fig_kw: Any
1829) -> tuple[Figure, dict[str, matplotlib.axes.Axes]] | \
1830 tuple[Figure, dict[_T, matplotlib.axes.Axes]] | \
1831 tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]:
1832 """
1833 Build a layout of Axes based on ASCII art or nested lists.
1834
1835 This is a helper function to build complex GridSpec layouts visually.
1836
1837 See :ref:`mosaic`
1838 for an example and full API documentation
1839
1840 Parameters
1841 ----------
1842 mosaic : list of list of {hashable or nested} or str
1843
1844 A visual layout of how you want your Axes to be arranged
1845 labeled as strings. For example ::
1846
1847 x = [['A panel', 'A panel', 'edge'],
1848 ['C panel', '.', 'edge']]
1849
1850 produces 4 Axes:
1851
1852 - 'A panel' which is 1 row high and spans the first two columns
1853 - 'edge' which is 2 rows high and is on the right edge
1854 - 'C panel' which in 1 row and 1 column wide in the bottom left
1855 - a blank space 1 row and 1 column wide in the bottom center
1856
1857 Any of the entries in the layout can be a list of lists
1858 of the same form to create nested layouts.
1859
1860 If input is a str, then it must be of the form ::
1861
1862 '''
1863 AAE
1864 C.E
1865 '''
1866
1867 where each character is a column and each line is a row.
1868 This only allows only single character Axes labels and does
1869 not allow nesting but is very terse.
1870
1871 sharex, sharey : bool, default: False
1872 If True, the x-axis (*sharex*) or y-axis (*sharey*) will be shared
1873 among all subplots. In that case, tick label visibility and axis units
1874 behave as for `subplots`. If False, each subplot's x- or y-axis will
1875 be independent.
1876
1877 width_ratios : array-like of length *ncols*, optional
1878 Defines the relative widths of the columns. Each column gets a
1879 relative width of ``width_ratios[i] / sum(width_ratios)``.
1880 If not given, all columns will have the same width. Convenience
1881 for ``gridspec_kw={'width_ratios': [...]}``.
1882
1883 height_ratios : array-like of length *nrows*, optional
1884 Defines the relative heights of the rows. Each row gets a
1885 relative height of ``height_ratios[i] / sum(height_ratios)``.
1886 If not given, all rows will have the same height. Convenience
1887 for ``gridspec_kw={'height_ratios': [...]}``.
1888
1889 empty_sentinel : object, optional
1890 Entry in the layout to mean "leave this space empty". Defaults
1891 to ``'.'``. Note, if *layout* is a string, it is processed via
1892 `inspect.cleandoc` to remove leading white space, which may
1893 interfere with using white-space as the empty sentinel.
1894
1895 subplot_kw : dict, optional
1896 Dictionary with keywords passed to the `.Figure.add_subplot` call
1897 used to create each subplot. These values may be overridden by
1898 values in *per_subplot_kw*.
1899
1900 per_subplot_kw : dict, optional
1901 A dictionary mapping the Axes identifiers or tuples of identifiers
1902 to a dictionary of keyword arguments to be passed to the
1903 `.Figure.add_subplot` call used to create each subplot. The values
1904 in these dictionaries have precedence over the values in
1905 *subplot_kw*.
1906
1907 If *mosaic* is a string, and thus all keys are single characters,
1908 it is possible to use a single string instead of a tuple as keys;
1909 i.e. ``"AB"`` is equivalent to ``("A", "B")``.
1910
1911 .. versionadded:: 3.7
1912
1913 gridspec_kw : dict, optional
1914 Dictionary with keywords passed to the `.GridSpec` constructor used
1915 to create the grid the subplots are placed on.
1916
1917 **fig_kw
1918 All additional keyword arguments are passed to the
1919 `.pyplot.figure` call.
1920
1921 Returns
1922 -------
1923 fig : `.Figure`
1924 The new figure
1925
1926 dict[label, Axes]
1927 A dictionary mapping the labels to the Axes objects. The order of
1928 the Axes is left-to-right and top-to-bottom of their position in the
1929 total layout.
1930
1931 """
1932 fig = figure(**fig_kw)
1933 ax_dict = fig.subplot_mosaic( # type: ignore[misc]
1934 mosaic, # type: ignore[arg-type]
1935 sharex=sharex, sharey=sharey,
1936 height_ratios=height_ratios, width_ratios=width_ratios,
1937 subplot_kw=subplot_kw, gridspec_kw=gridspec_kw,
1938 empty_sentinel=empty_sentinel,
1939 per_subplot_kw=per_subplot_kw, # type: ignore[arg-type]
1940 )
1941 return fig, ax_dict
1942
1943
1944def subplot2grid(
1945 shape: tuple[int, int], loc: tuple[int, int],
1946 rowspan: int = 1, colspan: int = 1,
1947 fig: Figure | None = None,
1948 **kwargs
1949) -> matplotlib.axes.Axes:
1950 """
1951 Create a subplot at a specific location inside a regular grid.
1952
1953 Parameters
1954 ----------
1955 shape : (int, int)
1956 Number of rows and of columns of the grid in which to place axis.
1957 loc : (int, int)
1958 Row number and column number of the axis location within the grid.
1959 rowspan : int, default: 1
1960 Number of rows for the axis to span downwards.
1961 colspan : int, default: 1
1962 Number of columns for the axis to span to the right.
1963 fig : `.Figure`, optional
1964 Figure to place the subplot in. Defaults to the current figure.
1965 **kwargs
1966 Additional keyword arguments are handed to `~.Figure.add_subplot`.
1967
1968 Returns
1969 -------
1970 `~.axes.Axes`
1971
1972 The Axes of the subplot. The returned Axes can actually be an instance
1973 of a subclass, such as `.projections.polar.PolarAxes` for polar
1974 projections.
1975
1976 Notes
1977 -----
1978 The following call ::
1979
1980 ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan)
1981
1982 is identical to ::
1983
1984 fig = gcf()
1985 gs = fig.add_gridspec(nrows, ncols)
1986 ax = fig.add_subplot(gs[row:row+rowspan, col:col+colspan])
1987 """
1988 if fig is None:
1989 fig = gcf()
1990 rows, cols = shape
1991 gs = GridSpec._check_gridspec_exists(fig, rows, cols)
1992 subplotspec = gs.new_subplotspec(loc, rowspan=rowspan, colspan=colspan)
1993 return fig.add_subplot(subplotspec, **kwargs)
1994
1995
1996def twinx(ax: matplotlib.axes.Axes | None = None) -> _AxesBase:
1997 """
1998 Make and return a second Axes that shares the *x*-axis. The new Axes will
1999 overlay *ax* (or the current Axes if *ax* is *None*), and its ticks will be
2000 on the right.
2001
2002 Examples
2003 --------
2004 :doc:`/gallery/subplots_axes_and_figures/two_scales`
2005 """
2006 if ax is None:
2007 ax = gca()
2008 ax1 = ax.twinx()
2009 return ax1
2010
2011
2012def twiny(ax: matplotlib.axes.Axes | None = None) -> _AxesBase:
2013 """
2014 Make and return a second Axes that shares the *y*-axis. The new Axes will
2015 overlay *ax* (or the current Axes if *ax* is *None*), and its ticks will be
2016 on the top.
2017
2018 Examples
2019 --------
2020 :doc:`/gallery/subplots_axes_and_figures/two_scales`
2021 """
2022 if ax is None:
2023 ax = gca()
2024 ax1 = ax.twiny()
2025 return ax1
2026
2027
2028def subplot_tool(targetfig: Figure | None = None) -> SubplotTool | None:
2029 """
2030 Launch a subplot tool window for a figure.
2031
2032 Returns
2033 -------
2034 `matplotlib.widgets.SubplotTool`
2035 """
2036 if targetfig is None:
2037 targetfig = gcf()
2038 tb = targetfig.canvas.manager.toolbar # type: ignore[union-attr]
2039 if hasattr(tb, "configure_subplots"): # toolbar2
2040 from matplotlib.backend_bases import NavigationToolbar2
2041 return cast(NavigationToolbar2, tb).configure_subplots()
2042 elif hasattr(tb, "trigger_tool"): # toolmanager
2043 from matplotlib.backend_bases import ToolContainerBase
2044 cast(ToolContainerBase, tb).trigger_tool("subplots")
2045 return None
2046 else:
2047 raise ValueError("subplot_tool can only be launched for figures with "
2048 "an associated toolbar")
2049
2050
2051def box(on: bool | None = None) -> None:
2052 """
2053 Turn the Axes box on or off on the current Axes.
2054
2055 Parameters
2056 ----------
2057 on : bool or None
2058 The new `~matplotlib.axes.Axes` box state. If ``None``, toggle
2059 the state.
2060
2061 See Also
2062 --------
2063 :meth:`matplotlib.axes.Axes.set_frame_on`
2064 :meth:`matplotlib.axes.Axes.get_frame_on`
2065 """
2066 ax = gca()
2067 if on is None:
2068 on = not ax.get_frame_on()
2069 ax.set_frame_on(on)
2070
2071## Axis ##
2072
2073
2074def xlim(*args, **kwargs) -> tuple[float, float]:
2075 """
2076 Get or set the x limits of the current Axes.
2077
2078 Call signatures::
2079
2080 left, right = xlim() # return the current xlim
2081 xlim((left, right)) # set the xlim to left, right
2082 xlim(left, right) # set the xlim to left, right
2083
2084 If you do not specify args, you can pass *left* or *right* as kwargs,
2085 i.e.::
2086
2087 xlim(right=3) # adjust the right leaving left unchanged
2088 xlim(left=1) # adjust the left leaving right unchanged
2089
2090 Setting limits turns autoscaling off for the x-axis.
2091
2092 Returns
2093 -------
2094 left, right
2095 A tuple of the new x-axis limits.
2096
2097 Notes
2098 -----
2099 Calling this function with no arguments (e.g. ``xlim()``) is the pyplot
2100 equivalent of calling `~.Axes.get_xlim` on the current Axes.
2101 Calling this function with arguments is the pyplot equivalent of calling
2102 `~.Axes.set_xlim` on the current Axes. All arguments are passed though.
2103 """
2104 ax = gca()
2105 if not args and not kwargs:
2106 return ax.get_xlim()
2107 ret = ax.set_xlim(*args, **kwargs)
2108 return ret
2109
2110
2111def ylim(*args, **kwargs) -> tuple[float, float]:
2112 """
2113 Get or set the y-limits of the current Axes.
2114
2115 Call signatures::
2116
2117 bottom, top = ylim() # return the current ylim
2118 ylim((bottom, top)) # set the ylim to bottom, top
2119 ylim(bottom, top) # set the ylim to bottom, top
2120
2121 If you do not specify args, you can alternatively pass *bottom* or
2122 *top* as kwargs, i.e.::
2123
2124 ylim(top=3) # adjust the top leaving bottom unchanged
2125 ylim(bottom=1) # adjust the bottom leaving top unchanged
2126
2127 Setting limits turns autoscaling off for the y-axis.
2128
2129 Returns
2130 -------
2131 bottom, top
2132 A tuple of the new y-axis limits.
2133
2134 Notes
2135 -----
2136 Calling this function with no arguments (e.g. ``ylim()``) is the pyplot
2137 equivalent of calling `~.Axes.get_ylim` on the current Axes.
2138 Calling this function with arguments is the pyplot equivalent of calling
2139 `~.Axes.set_ylim` on the current Axes. All arguments are passed though.
2140 """
2141 ax = gca()
2142 if not args and not kwargs:
2143 return ax.get_ylim()
2144 ret = ax.set_ylim(*args, **kwargs)
2145 return ret
2146
2147
2148def xticks(
2149 ticks: ArrayLike | None = None,
2150 labels: Sequence[str] | None = None,
2151 *,
2152 minor: bool = False,
2153 **kwargs
2154) -> tuple[list[Tick] | np.ndarray, list[Text]]:
2155 """
2156 Get or set the current tick locations and labels of the x-axis.
2157
2158 Pass no arguments to return the current values without modifying them.
2159
2160 Parameters
2161 ----------
2162 ticks : array-like, optional
2163 The list of xtick locations. Passing an empty list removes all xticks.
2164 labels : array-like, optional
2165 The labels to place at the given *ticks* locations. This argument can
2166 only be passed if *ticks* is passed as well.
2167 minor : bool, default: False
2168 If ``False``, get/set the major ticks/labels; if ``True``, the minor
2169 ticks/labels.
2170 **kwargs
2171 `.Text` properties can be used to control the appearance of the labels.
2172
2173 .. warning::
2174
2175 This only sets the properties of the current ticks, which is
2176 only sufficient if you either pass *ticks*, resulting in a
2177 fixed list of ticks, or if the plot is static.
2178
2179 Ticks are not guaranteed to be persistent. Various operations
2180 can create, delete and modify the Tick instances. There is an
2181 imminent risk that these settings can get lost if you work on
2182 the figure further (including also panning/zooming on a
2183 displayed figure).
2184
2185 Use `~.pyplot.tick_params` instead if possible.
2186
2187
2188 Returns
2189 -------
2190 locs
2191 The list of xtick locations.
2192 labels
2193 The list of xlabel `.Text` objects.
2194
2195 Notes
2196 -----
2197 Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
2198 equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
2199 the current Axes.
2200 Calling this function with arguments is the pyplot equivalent of calling
2201 `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current Axes.
2202
2203 Examples
2204 --------
2205 >>> locs, labels = xticks() # Get the current locations and labels.
2206 >>> xticks(np.arange(0, 1, step=0.2)) # Set label locations.
2207 >>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
2208 >>> xticks([0, 1, 2], ['January', 'February', 'March'],
2209 ... rotation=20) # Set text labels and properties.
2210 >>> xticks([]) # Disable xticks.
2211 """
2212 ax = gca()
2213
2214 locs: list[Tick] | np.ndarray
2215 if ticks is None:
2216 locs = ax.get_xticks(minor=minor)
2217 if labels is not None:
2218 raise TypeError("xticks(): Parameter 'labels' can't be set "
2219 "without setting 'ticks'")
2220 else:
2221 locs = ax.set_xticks(ticks, minor=minor)
2222
2223 labels_out: list[Text] = []
2224 if labels is None:
2225 labels_out = ax.get_xticklabels(minor=minor)
2226 for l in labels_out:
2227 l._internal_update(kwargs)
2228 else:
2229 labels_out = ax.set_xticklabels(labels, minor=minor, **kwargs)
2230
2231 return locs, labels_out
2232
2233
2234def yticks(
2235 ticks: ArrayLike | None = None,
2236 labels: Sequence[str] | None = None,
2237 *,
2238 minor: bool = False,
2239 **kwargs
2240) -> tuple[list[Tick] | np.ndarray, list[Text]]:
2241 """
2242 Get or set the current tick locations and labels of the y-axis.
2243
2244 Pass no arguments to return the current values without modifying them.
2245
2246 Parameters
2247 ----------
2248 ticks : array-like, optional
2249 The list of ytick locations. Passing an empty list removes all yticks.
2250 labels : array-like, optional
2251 The labels to place at the given *ticks* locations. This argument can
2252 only be passed if *ticks* is passed as well.
2253 minor : bool, default: False
2254 If ``False``, get/set the major ticks/labels; if ``True``, the minor
2255 ticks/labels.
2256 **kwargs
2257 `.Text` properties can be used to control the appearance of the labels.
2258
2259 .. warning::
2260
2261 This only sets the properties of the current ticks, which is
2262 only sufficient if you either pass *ticks*, resulting in a
2263 fixed list of ticks, or if the plot is static.
2264
2265 Ticks are not guaranteed to be persistent. Various operations
2266 can create, delete and modify the Tick instances. There is an
2267 imminent risk that these settings can get lost if you work on
2268 the figure further (including also panning/zooming on a
2269 displayed figure).
2270
2271 Use `~.pyplot.tick_params` instead if possible.
2272
2273 Returns
2274 -------
2275 locs
2276 The list of ytick locations.
2277 labels
2278 The list of ylabel `.Text` objects.
2279
2280 Notes
2281 -----
2282 Calling this function with no arguments (e.g. ``yticks()``) is the pyplot
2283 equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on
2284 the current Axes.
2285 Calling this function with arguments is the pyplot equivalent of calling
2286 `~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current Axes.
2287
2288 Examples
2289 --------
2290 >>> locs, labels = yticks() # Get the current locations and labels.
2291 >>> yticks(np.arange(0, 1, step=0.2)) # Set label locations.
2292 >>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
2293 >>> yticks([0, 1, 2], ['January', 'February', 'March'],
2294 ... rotation=45) # Set text labels and properties.
2295 >>> yticks([]) # Disable yticks.
2296 """
2297 ax = gca()
2298
2299 locs: list[Tick] | np.ndarray
2300 if ticks is None:
2301 locs = ax.get_yticks(minor=minor)
2302 if labels is not None:
2303 raise TypeError("yticks(): Parameter 'labels' can't be set "
2304 "without setting 'ticks'")
2305 else:
2306 locs = ax.set_yticks(ticks, minor=minor)
2307
2308 labels_out: list[Text] = []
2309 if labels is None:
2310 labels_out = ax.get_yticklabels(minor=minor)
2311 for l in labels_out:
2312 l._internal_update(kwargs)
2313 else:
2314 labels_out = ax.set_yticklabels(labels, minor=minor, **kwargs)
2315
2316 return locs, labels_out
2317
2318
2319def rgrids(
2320 radii: ArrayLike | None = None,
2321 labels: Sequence[str | Text] | None = None,
2322 angle: float | None = None,
2323 fmt: str | None = None,
2324 **kwargs
2325) -> tuple[list[Line2D], list[Text]]:
2326 """
2327 Get or set the radial gridlines on the current polar plot.
2328
2329 Call signatures::
2330
2331 lines, labels = rgrids()
2332 lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs)
2333
2334 When called with no arguments, `.rgrids` simply returns the tuple
2335 (*lines*, *labels*). When called with arguments, the labels will
2336 appear at the specified radial distances and angle.
2337
2338 Parameters
2339 ----------
2340 radii : tuple with floats
2341 The radii for the radial gridlines
2342
2343 labels : tuple with strings or None
2344 The labels to use at each radial gridline. The
2345 `matplotlib.ticker.ScalarFormatter` will be used if None.
2346
2347 angle : float
2348 The angular position of the radius labels in degrees.
2349
2350 fmt : str or None
2351 Format string used in `matplotlib.ticker.FormatStrFormatter`.
2352 For example '%f'.
2353
2354 Returns
2355 -------
2356 lines : list of `.lines.Line2D`
2357 The radial gridlines.
2358
2359 labels : list of `.text.Text`
2360 The tick labels.
2361
2362 Other Parameters
2363 ----------------
2364 **kwargs
2365 *kwargs* are optional `.Text` properties for the labels.
2366
2367 See Also
2368 --------
2369 .pyplot.thetagrids
2370 .projections.polar.PolarAxes.set_rgrids
2371 .Axis.get_gridlines
2372 .Axis.get_ticklabels
2373
2374 Examples
2375 --------
2376 ::
2377
2378 # set the locations of the radial gridlines
2379 lines, labels = rgrids( (0.25, 0.5, 1.0) )
2380
2381 # set the locations and labels of the radial gridlines
2382 lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ))
2383 """
2384 ax = gca()
2385 if not isinstance(ax, PolarAxes):
2386 raise RuntimeError('rgrids only defined for polar Axes')
2387 if all(p is None for p in [radii, labels, angle, fmt]) and not kwargs:
2388 lines_out: list[Line2D] = ax.yaxis.get_gridlines()
2389 labels_out: list[Text] = ax.yaxis.get_ticklabels()
2390 elif radii is None:
2391 raise TypeError("'radii' cannot be None when other parameters are passed")
2392 else:
2393 lines_out, labels_out = ax.set_rgrids(
2394 radii, labels=labels, angle=angle, fmt=fmt, **kwargs)
2395 return lines_out, labels_out
2396
2397
2398def thetagrids(
2399 angles: ArrayLike | None = None,
2400 labels: Sequence[str | Text] | None = None,
2401 fmt: str | None = None,
2402 **kwargs
2403) -> tuple[list[Line2D], list[Text]]:
2404 """
2405 Get or set the theta gridlines on the current polar plot.
2406
2407 Call signatures::
2408
2409 lines, labels = thetagrids()
2410 lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs)
2411
2412 When called with no arguments, `.thetagrids` simply returns the tuple
2413 (*lines*, *labels*). When called with arguments, the labels will
2414 appear at the specified angles.
2415
2416 Parameters
2417 ----------
2418 angles : tuple with floats, degrees
2419 The angles of the theta gridlines.
2420
2421 labels : tuple with strings or None
2422 The labels to use at each radial gridline. The
2423 `.projections.polar.ThetaFormatter` will be used if None.
2424
2425 fmt : str or None
2426 Format string used in `matplotlib.ticker.FormatStrFormatter`.
2427 For example '%f'. Note that the angle in radians will be used.
2428
2429 Returns
2430 -------
2431 lines : list of `.lines.Line2D`
2432 The theta gridlines.
2433
2434 labels : list of `.text.Text`
2435 The tick labels.
2436
2437 Other Parameters
2438 ----------------
2439 **kwargs
2440 *kwargs* are optional `.Text` properties for the labels.
2441
2442 See Also
2443 --------
2444 .pyplot.rgrids
2445 .projections.polar.PolarAxes.set_thetagrids
2446 .Axis.get_gridlines
2447 .Axis.get_ticklabels
2448
2449 Examples
2450 --------
2451 ::
2452
2453 # set the locations of the angular gridlines
2454 lines, labels = thetagrids(range(45, 360, 90))
2455
2456 # set the locations and labels of the angular gridlines
2457 lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE'))
2458 """
2459 ax = gca()
2460 if not isinstance(ax, PolarAxes):
2461 raise RuntimeError('thetagrids only defined for polar Axes')
2462 if all(param is None for param in [angles, labels, fmt]) and not kwargs:
2463 lines_out: list[Line2D] = ax.xaxis.get_ticklines()
2464 labels_out: list[Text] = ax.xaxis.get_ticklabels()
2465 elif angles is None:
2466 raise TypeError("'angles' cannot be None when other parameters are passed")
2467 else:
2468 lines_out, labels_out = ax.set_thetagrids(angles,
2469 labels=labels, fmt=fmt,
2470 **kwargs)
2471 return lines_out, labels_out
2472
2473
2474@_api.deprecated("3.7", pending=True)
2475def get_plot_commands() -> list[str]:
2476 """
2477 Get a sorted list of all of the plotting commands.
2478 """
2479 NON_PLOT_COMMANDS = {
2480 'connect', 'disconnect', 'get_current_fig_manager', 'ginput',
2481 'new_figure_manager', 'waitforbuttonpress'}
2482 return [name for name in _get_pyplot_commands()
2483 if name not in NON_PLOT_COMMANDS]
2484
2485
2486def _get_pyplot_commands() -> list[str]:
2487 # This works by searching for all functions in this module and removing
2488 # a few hard-coded exclusions, as well as all of the colormap-setting
2489 # functions, and anything marked as private with a preceding underscore.
2490 exclude = {'colormaps', 'colors', 'get_plot_commands', *colormaps}
2491 this_module = inspect.getmodule(get_plot_commands)
2492 return sorted(
2493 name for name, obj in globals().items()
2494 if not name.startswith('_') and name not in exclude
2495 and inspect.isfunction(obj)
2496 and inspect.getmodule(obj) is this_module)
2497
2498
2499## Plotting part 1: manually generated functions and wrappers ##
2500
2501
2502@_copy_docstring_and_deprecators(Figure.colorbar)
2503def colorbar(
2504 mappable: ScalarMappable | None = None,
2505 cax: matplotlib.axes.Axes | None = None,
2506 ax: matplotlib.axes.Axes | Iterable[matplotlib.axes.Axes] | None = None,
2507 **kwargs
2508) -> Colorbar:
2509 if mappable is None:
2510 mappable = gci()
2511 if mappable is None:
2512 raise RuntimeError('No mappable was found to use for colorbar '
2513 'creation. First define a mappable such as '
2514 'an image (with imshow) or a contour set ('
2515 'with contourf).')
2516 ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kwargs)
2517 return ret
2518
2519
2520def clim(vmin: float | None = None, vmax: float | None = None) -> None:
2521 """
2522 Set the color limits of the current image.
2523
2524 If either *vmin* or *vmax* is None, the image min/max respectively
2525 will be used for color scaling.
2526
2527 If you want to set the clim of multiple images, use
2528 `~.ScalarMappable.set_clim` on every image, for example::
2529
2530 for im in gca().get_images():
2531 im.set_clim(0, 0.5)
2532
2533 """
2534 im = gci()
2535 if im is None:
2536 raise RuntimeError('You must first define an image, e.g., with imshow')
2537
2538 im.set_clim(vmin, vmax)
2539
2540
2541def get_cmap(name: Colormap | str | None = None, lut: int | None = None) -> Colormap:
2542 """
2543 Get a colormap instance, defaulting to rc values if *name* is None.
2544
2545 Parameters
2546 ----------
2547 name : `~matplotlib.colors.Colormap` or str or None, default: None
2548 If a `.Colormap` instance, it will be returned. Otherwise, the name of
2549 a colormap known to Matplotlib, which will be resampled by *lut*. The
2550 default, None, means :rc:`image.cmap`.
2551 lut : int or None, default: None
2552 If *name* is not already a Colormap instance and *lut* is not None, the
2553 colormap will be resampled to have *lut* entries in the lookup table.
2554
2555 Returns
2556 -------
2557 Colormap
2558 """
2559 if name is None:
2560 name = rcParams['image.cmap']
2561 if isinstance(name, Colormap):
2562 return name
2563 _api.check_in_list(sorted(_colormaps), name=name)
2564 if lut is None:
2565 return _colormaps[name]
2566 else:
2567 return _colormaps[name].resampled(lut)
2568
2569
2570def set_cmap(cmap: Colormap | str) -> None:
2571 """
2572 Set the default colormap, and applies it to the current image if any.
2573
2574 Parameters
2575 ----------
2576 cmap : `~matplotlib.colors.Colormap` or str
2577 A colormap instance or the name of a registered colormap.
2578
2579 See Also
2580 --------
2581 colormaps
2582 get_cmap
2583 """
2584 cmap = get_cmap(cmap)
2585
2586 rc('image', cmap=cmap.name)
2587 im = gci()
2588
2589 if im is not None:
2590 im.set_cmap(cmap)
2591
2592
2593@_copy_docstring_and_deprecators(matplotlib.image.imread)
2594def imread(
2595 fname: str | pathlib.Path | BinaryIO, format: str | None = None
2596) -> np.ndarray:
2597 return matplotlib.image.imread(fname, format)
2598
2599
2600@_copy_docstring_and_deprecators(matplotlib.image.imsave)
2601def imsave(
2602 fname: str | os.PathLike | BinaryIO, arr: ArrayLike, **kwargs
2603) -> None:
2604 matplotlib.image.imsave(fname, arr, **kwargs)
2605
2606
2607def matshow(A: ArrayLike, fignum: None | int = None, **kwargs) -> AxesImage:
2608 """
2609 Display a 2D array as a matrix in a new figure window.
2610
2611 The origin is set at the upper left hand corner.
2612 The indexing is ``(row, column)`` so that the first index runs vertically
2613 and the second index runs horizontally in the figure:
2614
2615 .. code-block:: none
2616
2617 A[0, 0] ⋯ A[0, M-1]
2618 ⋮ ⋮
2619 A[N-1, 0] ⋯ A[N-1, M-1]
2620
2621 The aspect ratio of the figure window is that of the array,
2622 unless this would make an excessively short or narrow figure.
2623
2624 Tick labels for the xaxis are placed on top.
2625
2626 Parameters
2627 ----------
2628 A : 2D array-like
2629 The matrix to be displayed.
2630
2631 fignum : None or int
2632 If *None*, create a new, appropriately sized figure window.
2633
2634 If 0, use the current Axes (creating one if there is none, without ever
2635 adjusting the figure size).
2636
2637 Otherwise, create a new Axes on the figure with the given number
2638 (creating it at the appropriate size if it does not exist, but not
2639 adjusting the figure size otherwise). Note that this will be drawn on
2640 top of any preexisting Axes on the figure.
2641
2642 Returns
2643 -------
2644 `~matplotlib.image.AxesImage`
2645
2646 Other Parameters
2647 ----------------
2648 **kwargs : `~matplotlib.axes.Axes.imshow` arguments
2649
2650 """
2651 A = np.asanyarray(A)
2652 if fignum == 0:
2653 ax = gca()
2654 else:
2655 # Extract actual aspect ratio of array and make appropriately sized
2656 # figure.
2657 fig = figure(fignum, figsize=figaspect(A))
2658 ax = fig.add_axes((0.15, 0.09, 0.775, 0.775))
2659 im = ax.matshow(A, **kwargs)
2660 sci(im)
2661 return im
2662
2663
2664def polar(*args, **kwargs) -> list[Line2D]:
2665 """
2666 Make a polar plot.
2667
2668 call signature::
2669
2670 polar(theta, r, **kwargs)
2671
2672 Multiple *theta*, *r* arguments are supported, with format strings, as in
2673 `plot`.
2674 """
2675 # If an axis already exists, check if it has a polar projection
2676 if gcf().get_axes():
2677 ax = gca()
2678 if not isinstance(ax, PolarAxes):
2679 _api.warn_external('Trying to create polar plot on an Axes '
2680 'that does not have a polar projection.')
2681 else:
2682 ax = axes(projection="polar")
2683 return ax.plot(*args, **kwargs)
2684
2685
2686# If rcParams['backend_fallback'] is true, and an interactive backend is
2687# requested, ignore rcParams['backend'] and force selection of a backend that
2688# is compatible with the current running interactive framework.
2689if (rcParams["backend_fallback"]
2690 and rcParams._get_backend_or_none() in ( # type: ignore[attr-defined]
2691 set(backend_registry.list_builtin(BackendFilter.INTERACTIVE)) -
2692 {'webagg', 'nbagg'})
2693 and cbook._get_running_interactive_framework()):
2694 rcParams._set("backend", rcsetup._auto_backend_sentinel)
2695
2696# fmt: on
2697
2698################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
2699
2700
2701# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2702@_copy_docstring_and_deprecators(Figure.figimage)
2703def figimage(
2704 X: ArrayLike,
2705 xo: int = 0,
2706 yo: int = 0,
2707 alpha: float | None = None,
2708 norm: str | Normalize | None = None,
2709 cmap: str | Colormap | None = None,
2710 vmin: float | None = None,
2711 vmax: float | None = None,
2712 origin: Literal["upper", "lower"] | None = None,
2713 resize: bool = False,
2714 **kwargs,
2715) -> FigureImage:
2716 return gcf().figimage(
2717 X,
2718 xo=xo,
2719 yo=yo,
2720 alpha=alpha,
2721 norm=norm,
2722 cmap=cmap,
2723 vmin=vmin,
2724 vmax=vmax,
2725 origin=origin,
2726 resize=resize,
2727 **kwargs,
2728 )
2729
2730
2731# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2732@_copy_docstring_and_deprecators(Figure.text)
2733def figtext(
2734 x: float, y: float, s: str, fontdict: dict[str, Any] | None = None, **kwargs
2735) -> Text:
2736 return gcf().text(x, y, s, fontdict=fontdict, **kwargs)
2737
2738
2739# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2740@_copy_docstring_and_deprecators(Figure.gca)
2741def gca() -> Axes:
2742 return gcf().gca()
2743
2744
2745# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2746@_copy_docstring_and_deprecators(Figure._gci)
2747def gci() -> ScalarMappable | None:
2748 return gcf()._gci()
2749
2750
2751# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2752@_copy_docstring_and_deprecators(Figure.ginput)
2753def ginput(
2754 n: int = 1,
2755 timeout: float = 30,
2756 show_clicks: bool = True,
2757 mouse_add: MouseButton = MouseButton.LEFT,
2758 mouse_pop: MouseButton = MouseButton.RIGHT,
2759 mouse_stop: MouseButton = MouseButton.MIDDLE,
2760) -> list[tuple[int, int]]:
2761 return gcf().ginput(
2762 n=n,
2763 timeout=timeout,
2764 show_clicks=show_clicks,
2765 mouse_add=mouse_add,
2766 mouse_pop=mouse_pop,
2767 mouse_stop=mouse_stop,
2768 )
2769
2770
2771# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2772@_copy_docstring_and_deprecators(Figure.subplots_adjust)
2773def subplots_adjust(
2774 left: float | None = None,
2775 bottom: float | None = None,
2776 right: float | None = None,
2777 top: float | None = None,
2778 wspace: float | None = None,
2779 hspace: float | None = None,
2780) -> None:
2781 gcf().subplots_adjust(
2782 left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace
2783 )
2784
2785
2786# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2787@_copy_docstring_and_deprecators(Figure.suptitle)
2788def suptitle(t: str, **kwargs) -> Text:
2789 return gcf().suptitle(t, **kwargs)
2790
2791
2792# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2793@_copy_docstring_and_deprecators(Figure.tight_layout)
2794def tight_layout(
2795 *,
2796 pad: float = 1.08,
2797 h_pad: float | None = None,
2798 w_pad: float | None = None,
2799 rect: tuple[float, float, float, float] | None = None,
2800) -> None:
2801 gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
2802
2803
2804# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2805@_copy_docstring_and_deprecators(Figure.waitforbuttonpress)
2806def waitforbuttonpress(timeout: float = -1) -> None | bool:
2807 return gcf().waitforbuttonpress(timeout=timeout)
2808
2809
2810# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2811@_copy_docstring_and_deprecators(Axes.acorr)
2812def acorr(
2813 x: ArrayLike, *, data=None, **kwargs
2814) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]:
2815 return gca().acorr(x, **({"data": data} if data is not None else {}), **kwargs)
2816
2817
2818# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2819@_copy_docstring_and_deprecators(Axes.angle_spectrum)
2820def angle_spectrum(
2821 x: ArrayLike,
2822 Fs: float | None = None,
2823 Fc: int | None = None,
2824 window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
2825 pad_to: int | None = None,
2826 sides: Literal["default", "onesided", "twosided"] | None = None,
2827 *,
2828 data=None,
2829 **kwargs,
2830) -> tuple[np.ndarray, np.ndarray, Line2D]:
2831 return gca().angle_spectrum(
2832 x,
2833 Fs=Fs,
2834 Fc=Fc,
2835 window=window,
2836 pad_to=pad_to,
2837 sides=sides,
2838 **({"data": data} if data is not None else {}),
2839 **kwargs,
2840 )
2841
2842
2843# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2844@_copy_docstring_and_deprecators(Axes.annotate)
2845def annotate(
2846 text: str,
2847 xy: tuple[float, float],
2848 xytext: tuple[float, float] | None = None,
2849 xycoords: str
2850 | Artist
2851 | Transform
2852 | Callable[[RendererBase], Bbox | Transform]
2853 | tuple[float, float] = "data",
2854 textcoords: str
2855 | Artist
2856 | Transform
2857 | Callable[[RendererBase], Bbox | Transform]
2858 | tuple[float, float]
2859 | None = None,
2860 arrowprops: dict[str, Any] | None = None,
2861 annotation_clip: bool | None = None,
2862 **kwargs,
2863) -> Annotation:
2864 return gca().annotate(
2865 text,
2866 xy,
2867 xytext=xytext,
2868 xycoords=xycoords,
2869 textcoords=textcoords,
2870 arrowprops=arrowprops,
2871 annotation_clip=annotation_clip,
2872 **kwargs,
2873 )
2874
2875
2876# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2877@_copy_docstring_and_deprecators(Axes.arrow)
2878def arrow(x: float, y: float, dx: float, dy: float, **kwargs) -> FancyArrow:
2879 return gca().arrow(x, y, dx, dy, **kwargs)
2880
2881
2882# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2883@_copy_docstring_and_deprecators(Axes.autoscale)
2884def autoscale(
2885 enable: bool = True,
2886 axis: Literal["both", "x", "y"] = "both",
2887 tight: bool | None = None,
2888) -> None:
2889 gca().autoscale(enable=enable, axis=axis, tight=tight)
2890
2891
2892# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2893@_copy_docstring_and_deprecators(Axes.axhline)
2894def axhline(y: float = 0, xmin: float = 0, xmax: float = 1, **kwargs) -> Line2D:
2895 return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs)
2896
2897
2898# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2899@_copy_docstring_and_deprecators(Axes.axhspan)
2900def axhspan(
2901 ymin: float, ymax: float, xmin: float = 0, xmax: float = 1, **kwargs
2902) -> Rectangle:
2903 return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs)
2904
2905
2906# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2907@_copy_docstring_and_deprecators(Axes.axis)
2908def axis(
2909 arg: tuple[float, float, float, float] | bool | str | None = None,
2910 /,
2911 *,
2912 emit: bool = True,
2913 **kwargs,
2914) -> tuple[float, float, float, float]:
2915 return gca().axis(arg, emit=emit, **kwargs)
2916
2917
2918# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2919@_copy_docstring_and_deprecators(Axes.axline)
2920def axline(
2921 xy1: tuple[float, float],
2922 xy2: tuple[float, float] | None = None,
2923 *,
2924 slope: float | None = None,
2925 **kwargs,
2926) -> AxLine:
2927 return gca().axline(xy1, xy2=xy2, slope=slope, **kwargs)
2928
2929
2930# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2931@_copy_docstring_and_deprecators(Axes.axvline)
2932def axvline(x: float = 0, ymin: float = 0, ymax: float = 1, **kwargs) -> Line2D:
2933 return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs)
2934
2935
2936# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2937@_copy_docstring_and_deprecators(Axes.axvspan)
2938def axvspan(
2939 xmin: float, xmax: float, ymin: float = 0, ymax: float = 1, **kwargs
2940) -> Rectangle:
2941 return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)
2942
2943
2944# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2945@_copy_docstring_and_deprecators(Axes.bar)
2946def bar(
2947 x: float | ArrayLike,
2948 height: float | ArrayLike,
2949 width: float | ArrayLike = 0.8,
2950 bottom: float | ArrayLike | None = None,
2951 *,
2952 align: Literal["center", "edge"] = "center",
2953 data=None,
2954 **kwargs,
2955) -> BarContainer:
2956 return gca().bar(
2957 x,
2958 height,
2959 width=width,
2960 bottom=bottom,
2961 align=align,
2962 **({"data": data} if data is not None else {}),
2963 **kwargs,
2964 )
2965
2966
2967# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2968@_copy_docstring_and_deprecators(Axes.barbs)
2969def barbs(*args, data=None, **kwargs) -> Barbs:
2970 return gca().barbs(*args, **({"data": data} if data is not None else {}), **kwargs)
2971
2972
2973# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2974@_copy_docstring_and_deprecators(Axes.barh)
2975def barh(
2976 y: float | ArrayLike,
2977 width: float | ArrayLike,
2978 height: float | ArrayLike = 0.8,
2979 left: float | ArrayLike | None = None,
2980 *,
2981 align: Literal["center", "edge"] = "center",
2982 data=None,
2983 **kwargs,
2984) -> BarContainer:
2985 return gca().barh(
2986 y,
2987 width,
2988 height=height,
2989 left=left,
2990 align=align,
2991 **({"data": data} if data is not None else {}),
2992 **kwargs,
2993 )
2994
2995
2996# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
2997@_copy_docstring_and_deprecators(Axes.bar_label)
2998def bar_label(
2999 container: BarContainer,
3000 labels: ArrayLike | None = None,
3001 *,
3002 fmt: str | Callable[[float], str] = "%g",
3003 label_type: Literal["center", "edge"] = "edge",
3004 padding: float = 0,
3005 **kwargs,
3006) -> list[Annotation]:
3007 return gca().bar_label(
3008 container,
3009 labels=labels,
3010 fmt=fmt,
3011 label_type=label_type,
3012 padding=padding,
3013 **kwargs,
3014 )
3015
3016
3017# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3018@_copy_docstring_and_deprecators(Axes.boxplot)
3019def boxplot(
3020 x: ArrayLike | Sequence[ArrayLike],
3021 notch: bool | None = None,
3022 sym: str | None = None,
3023 vert: bool | None = None,
3024 whis: float | tuple[float, float] | None = None,
3025 positions: ArrayLike | None = None,
3026 widths: float | ArrayLike | None = None,
3027 patch_artist: bool | None = None,
3028 bootstrap: int | None = None,
3029 usermedians: ArrayLike | None = None,
3030 conf_intervals: ArrayLike | None = None,
3031 meanline: bool | None = None,
3032 showmeans: bool | None = None,
3033 showcaps: bool | None = None,
3034 showbox: bool | None = None,
3035 showfliers: bool | None = None,
3036 boxprops: dict[str, Any] | None = None,
3037 tick_labels: Sequence[str] | None = None,
3038 flierprops: dict[str, Any] | None = None,
3039 medianprops: dict[str, Any] | None = None,
3040 meanprops: dict[str, Any] | None = None,
3041 capprops: dict[str, Any] | None = None,
3042 whiskerprops: dict[str, Any] | None = None,
3043 manage_ticks: bool = True,
3044 autorange: bool = False,
3045 zorder: float | None = None,
3046 capwidths: float | ArrayLike | None = None,
3047 label: Sequence[str] | None = None,
3048 *,
3049 data=None,
3050) -> dict[str, Any]:
3051 return gca().boxplot(
3052 x,
3053 notch=notch,
3054 sym=sym,
3055 vert=vert,
3056 whis=whis,
3057 positions=positions,
3058 widths=widths,
3059 patch_artist=patch_artist,
3060 bootstrap=bootstrap,
3061 usermedians=usermedians,
3062 conf_intervals=conf_intervals,
3063 meanline=meanline,
3064 showmeans=showmeans,
3065 showcaps=showcaps,
3066 showbox=showbox,
3067 showfliers=showfliers,
3068 boxprops=boxprops,
3069 tick_labels=tick_labels,
3070 flierprops=flierprops,
3071 medianprops=medianprops,
3072 meanprops=meanprops,
3073 capprops=capprops,
3074 whiskerprops=whiskerprops,
3075 manage_ticks=manage_ticks,
3076 autorange=autorange,
3077 zorder=zorder,
3078 capwidths=capwidths,
3079 label=label,
3080 **({"data": data} if data is not None else {}),
3081 )
3082
3083
3084# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3085@_copy_docstring_and_deprecators(Axes.broken_barh)
3086def broken_barh(
3087 xranges: Sequence[tuple[float, float]],
3088 yrange: tuple[float, float],
3089 *,
3090 data=None,
3091 **kwargs,
3092) -> PolyCollection:
3093 return gca().broken_barh(
3094 xranges, yrange, **({"data": data} if data is not None else {}), **kwargs
3095 )
3096
3097
3098# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3099@_copy_docstring_and_deprecators(Axes.clabel)
3100def clabel(CS: ContourSet, levels: ArrayLike | None = None, **kwargs) -> list[Text]:
3101 return gca().clabel(CS, levels=levels, **kwargs)
3102
3103
3104# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3105@_copy_docstring_and_deprecators(Axes.cohere)
3106def cohere(
3107 x: ArrayLike,
3108 y: ArrayLike,
3109 NFFT: int = 256,
3110 Fs: float = 2,
3111 Fc: int = 0,
3112 detrend: Literal["none", "mean", "linear"]
3113 | Callable[[ArrayLike], ArrayLike] = mlab.detrend_none,
3114 window: Callable[[ArrayLike], ArrayLike] | ArrayLike = mlab.window_hanning,
3115 noverlap: int = 0,
3116 pad_to: int | None = None,
3117 sides: Literal["default", "onesided", "twosided"] = "default",
3118 scale_by_freq: bool | None = None,
3119 *,
3120 data=None,
3121 **kwargs,
3122) -> tuple[np.ndarray, np.ndarray]:
3123 return gca().cohere(
3124 x,
3125 y,
3126 NFFT=NFFT,
3127 Fs=Fs,
3128 Fc=Fc,
3129 detrend=detrend,
3130 window=window,
3131 noverlap=noverlap,
3132 pad_to=pad_to,
3133 sides=sides,
3134 scale_by_freq=scale_by_freq,
3135 **({"data": data} if data is not None else {}),
3136 **kwargs,
3137 )
3138
3139
3140# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3141@_copy_docstring_and_deprecators(Axes.contour)
3142def contour(*args, data=None, **kwargs) -> QuadContourSet:
3143 __ret = gca().contour(
3144 *args, **({"data": data} if data is not None else {}), **kwargs
3145 )
3146 if __ret._A is not None: # type: ignore[attr-defined]
3147 sci(__ret)
3148 return __ret
3149
3150
3151# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3152@_copy_docstring_and_deprecators(Axes.contourf)
3153def contourf(*args, data=None, **kwargs) -> QuadContourSet:
3154 __ret = gca().contourf(
3155 *args, **({"data": data} if data is not None else {}), **kwargs
3156 )
3157 if __ret._A is not None: # type: ignore[attr-defined]
3158 sci(__ret)
3159 return __ret
3160
3161
3162# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3163@_copy_docstring_and_deprecators(Axes.csd)
3164def csd(
3165 x: ArrayLike,
3166 y: ArrayLike,
3167 NFFT: int | None = None,
3168 Fs: float | None = None,
3169 Fc: int | None = None,
3170 detrend: Literal["none", "mean", "linear"]
3171 | Callable[[ArrayLike], ArrayLike]
3172 | None = None,
3173 window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
3174 noverlap: int | None = None,
3175 pad_to: int | None = None,
3176 sides: Literal["default", "onesided", "twosided"] | None = None,
3177 scale_by_freq: bool | None = None,
3178 return_line: bool | None = None,
3179 *,
3180 data=None,
3181 **kwargs,
3182) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]:
3183 return gca().csd(
3184 x,
3185 y,
3186 NFFT=NFFT,
3187 Fs=Fs,
3188 Fc=Fc,
3189 detrend=detrend,
3190 window=window,
3191 noverlap=noverlap,
3192 pad_to=pad_to,
3193 sides=sides,
3194 scale_by_freq=scale_by_freq,
3195 return_line=return_line,
3196 **({"data": data} if data is not None else {}),
3197 **kwargs,
3198 )
3199
3200
3201# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3202@_copy_docstring_and_deprecators(Axes.ecdf)
3203def ecdf(
3204 x: ArrayLike,
3205 weights: ArrayLike | None = None,
3206 *,
3207 complementary: bool = False,
3208 orientation: Literal["vertical", "horizonatal"] = "vertical",
3209 compress: bool = False,
3210 data=None,
3211 **kwargs,
3212) -> Line2D:
3213 return gca().ecdf(
3214 x,
3215 weights=weights,
3216 complementary=complementary,
3217 orientation=orientation,
3218 compress=compress,
3219 **({"data": data} if data is not None else {}),
3220 **kwargs,
3221 )
3222
3223
3224# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3225@_copy_docstring_and_deprecators(Axes.errorbar)
3226def errorbar(
3227 x: float | ArrayLike,
3228 y: float | ArrayLike,
3229 yerr: float | ArrayLike | None = None,
3230 xerr: float | ArrayLike | None = None,
3231 fmt: str = "",
3232 ecolor: ColorType | None = None,
3233 elinewidth: float | None = None,
3234 capsize: float | None = None,
3235 barsabove: bool = False,
3236 lolims: bool | ArrayLike = False,
3237 uplims: bool | ArrayLike = False,
3238 xlolims: bool | ArrayLike = False,
3239 xuplims: bool | ArrayLike = False,
3240 errorevery: int | tuple[int, int] = 1,
3241 capthick: float | None = None,
3242 *,
3243 data=None,
3244 **kwargs,
3245) -> ErrorbarContainer:
3246 return gca().errorbar(
3247 x,
3248 y,
3249 yerr=yerr,
3250 xerr=xerr,
3251 fmt=fmt,
3252 ecolor=ecolor,
3253 elinewidth=elinewidth,
3254 capsize=capsize,
3255 barsabove=barsabove,
3256 lolims=lolims,
3257 uplims=uplims,
3258 xlolims=xlolims,
3259 xuplims=xuplims,
3260 errorevery=errorevery,
3261 capthick=capthick,
3262 **({"data": data} if data is not None else {}),
3263 **kwargs,
3264 )
3265
3266
3267# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3268@_copy_docstring_and_deprecators(Axes.eventplot)
3269def eventplot(
3270 positions: ArrayLike | Sequence[ArrayLike],
3271 orientation: Literal["horizontal", "vertical"] = "horizontal",
3272 lineoffsets: float | Sequence[float] = 1,
3273 linelengths: float | Sequence[float] = 1,
3274 linewidths: float | Sequence[float] | None = None,
3275 colors: ColorType | Sequence[ColorType] | None = None,
3276 alpha: float | Sequence[float] | None = None,
3277 linestyles: LineStyleType | Sequence[LineStyleType] = "solid",
3278 *,
3279 data=None,
3280 **kwargs,
3281) -> EventCollection:
3282 return gca().eventplot(
3283 positions,
3284 orientation=orientation,
3285 lineoffsets=lineoffsets,
3286 linelengths=linelengths,
3287 linewidths=linewidths,
3288 colors=colors,
3289 alpha=alpha,
3290 linestyles=linestyles,
3291 **({"data": data} if data is not None else {}),
3292 **kwargs,
3293 )
3294
3295
3296# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3297@_copy_docstring_and_deprecators(Axes.fill)
3298def fill(*args, data=None, **kwargs) -> list[Polygon]:
3299 return gca().fill(*args, **({"data": data} if data is not None else {}), **kwargs)
3300
3301
3302# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3303@_copy_docstring_and_deprecators(Axes.fill_between)
3304def fill_between(
3305 x: ArrayLike,
3306 y1: ArrayLike | float,
3307 y2: ArrayLike | float = 0,
3308 where: Sequence[bool] | None = None,
3309 interpolate: bool = False,
3310 step: Literal["pre", "post", "mid"] | None = None,
3311 *,
3312 data=None,
3313 **kwargs,
3314) -> PolyCollection:
3315 return gca().fill_between(
3316 x,
3317 y1,
3318 y2=y2,
3319 where=where,
3320 interpolate=interpolate,
3321 step=step,
3322 **({"data": data} if data is not None else {}),
3323 **kwargs,
3324 )
3325
3326
3327# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3328@_copy_docstring_and_deprecators(Axes.fill_betweenx)
3329def fill_betweenx(
3330 y: ArrayLike,
3331 x1: ArrayLike | float,
3332 x2: ArrayLike | float = 0,
3333 where: Sequence[bool] | None = None,
3334 step: Literal["pre", "post", "mid"] | None = None,
3335 interpolate: bool = False,
3336 *,
3337 data=None,
3338 **kwargs,
3339) -> PolyCollection:
3340 return gca().fill_betweenx(
3341 y,
3342 x1,
3343 x2=x2,
3344 where=where,
3345 step=step,
3346 interpolate=interpolate,
3347 **({"data": data} if data is not None else {}),
3348 **kwargs,
3349 )
3350
3351
3352# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3353@_copy_docstring_and_deprecators(Axes.grid)
3354def grid(
3355 visible: bool | None = None,
3356 which: Literal["major", "minor", "both"] = "major",
3357 axis: Literal["both", "x", "y"] = "both",
3358 **kwargs,
3359) -> None:
3360 gca().grid(visible=visible, which=which, axis=axis, **kwargs)
3361
3362
3363# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3364@_copy_docstring_and_deprecators(Axes.hexbin)
3365def hexbin(
3366 x: ArrayLike,
3367 y: ArrayLike,
3368 C: ArrayLike | None = None,
3369 gridsize: int | tuple[int, int] = 100,
3370 bins: Literal["log"] | int | Sequence[float] | None = None,
3371 xscale: Literal["linear", "log"] = "linear",
3372 yscale: Literal["linear", "log"] = "linear",
3373 extent: tuple[float, float, float, float] | None = None,
3374 cmap: str | Colormap | None = None,
3375 norm: str | Normalize | None = None,
3376 vmin: float | None = None,
3377 vmax: float | None = None,
3378 alpha: float | None = None,
3379 linewidths: float | None = None,
3380 edgecolors: Literal["face", "none"] | ColorType = "face",
3381 reduce_C_function: Callable[[np.ndarray | list[float]], float] = np.mean,
3382 mincnt: int | None = None,
3383 marginals: bool = False,
3384 *,
3385 data=None,
3386 **kwargs,
3387) -> PolyCollection:
3388 __ret = gca().hexbin(
3389 x,
3390 y,
3391 C=C,
3392 gridsize=gridsize,
3393 bins=bins,
3394 xscale=xscale,
3395 yscale=yscale,
3396 extent=extent,
3397 cmap=cmap,
3398 norm=norm,
3399 vmin=vmin,
3400 vmax=vmax,
3401 alpha=alpha,
3402 linewidths=linewidths,
3403 edgecolors=edgecolors,
3404 reduce_C_function=reduce_C_function,
3405 mincnt=mincnt,
3406 marginals=marginals,
3407 **({"data": data} if data is not None else {}),
3408 **kwargs,
3409 )
3410 sci(__ret)
3411 return __ret
3412
3413
3414# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3415@_copy_docstring_and_deprecators(Axes.hist)
3416def hist(
3417 x: ArrayLike | Sequence[ArrayLike],
3418 bins: int | Sequence[float] | str | None = None,
3419 range: tuple[float, float] | None = None,
3420 density: bool = False,
3421 weights: ArrayLike | None = None,
3422 cumulative: bool | float = False,
3423 bottom: ArrayLike | float | None = None,
3424 histtype: Literal["bar", "barstacked", "step", "stepfilled"] = "bar",
3425 align: Literal["left", "mid", "right"] = "mid",
3426 orientation: Literal["vertical", "horizontal"] = "vertical",
3427 rwidth: float | None = None,
3428 log: bool = False,
3429 color: ColorType | Sequence[ColorType] | None = None,
3430 label: str | Sequence[str] | None = None,
3431 stacked: bool = False,
3432 *,
3433 data=None,
3434 **kwargs,
3435) -> tuple[
3436 np.ndarray | list[np.ndarray],
3437 np.ndarray,
3438 BarContainer | Polygon | list[BarContainer | Polygon],
3439]:
3440 return gca().hist(
3441 x,
3442 bins=bins,
3443 range=range,
3444 density=density,
3445 weights=weights,
3446 cumulative=cumulative,
3447 bottom=bottom,
3448 histtype=histtype,
3449 align=align,
3450 orientation=orientation,
3451 rwidth=rwidth,
3452 log=log,
3453 color=color,
3454 label=label,
3455 stacked=stacked,
3456 **({"data": data} if data is not None else {}),
3457 **kwargs,
3458 )
3459
3460
3461# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3462@_copy_docstring_and_deprecators(Axes.stairs)
3463def stairs(
3464 values: ArrayLike,
3465 edges: ArrayLike | None = None,
3466 *,
3467 orientation: Literal["vertical", "horizontal"] = "vertical",
3468 baseline: float | ArrayLike | None = 0,
3469 fill: bool = False,
3470 data=None,
3471 **kwargs,
3472) -> StepPatch:
3473 return gca().stairs(
3474 values,
3475 edges=edges,
3476 orientation=orientation,
3477 baseline=baseline,
3478 fill=fill,
3479 **({"data": data} if data is not None else {}),
3480 **kwargs,
3481 )
3482
3483
3484# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3485@_copy_docstring_and_deprecators(Axes.hist2d)
3486def hist2d(
3487 x: ArrayLike,
3488 y: ArrayLike,
3489 bins: None | int | tuple[int, int] | ArrayLike | tuple[ArrayLike, ArrayLike] = 10,
3490 range: ArrayLike | None = None,
3491 density: bool = False,
3492 weights: ArrayLike | None = None,
3493 cmin: float | None = None,
3494 cmax: float | None = None,
3495 *,
3496 data=None,
3497 **kwargs,
3498) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]:
3499 __ret = gca().hist2d(
3500 x,
3501 y,
3502 bins=bins,
3503 range=range,
3504 density=density,
3505 weights=weights,
3506 cmin=cmin,
3507 cmax=cmax,
3508 **({"data": data} if data is not None else {}),
3509 **kwargs,
3510 )
3511 sci(__ret[-1])
3512 return __ret
3513
3514
3515# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3516@_copy_docstring_and_deprecators(Axes.hlines)
3517def hlines(
3518 y: float | ArrayLike,
3519 xmin: float | ArrayLike,
3520 xmax: float | ArrayLike,
3521 colors: ColorType | Sequence[ColorType] | None = None,
3522 linestyles: LineStyleType = "solid",
3523 label: str = "",
3524 *,
3525 data=None,
3526 **kwargs,
3527) -> LineCollection:
3528 return gca().hlines(
3529 y,
3530 xmin,
3531 xmax,
3532 colors=colors,
3533 linestyles=linestyles,
3534 label=label,
3535 **({"data": data} if data is not None else {}),
3536 **kwargs,
3537 )
3538
3539
3540# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3541@_copy_docstring_and_deprecators(Axes.imshow)
3542def imshow(
3543 X: ArrayLike | PIL.Image.Image,
3544 cmap: str | Colormap | None = None,
3545 norm: str | Normalize | None = None,
3546 *,
3547 aspect: Literal["equal", "auto"] | float | None = None,
3548 interpolation: str | None = None,
3549 alpha: float | ArrayLike | None = None,
3550 vmin: float | None = None,
3551 vmax: float | None = None,
3552 origin: Literal["upper", "lower"] | None = None,
3553 extent: tuple[float, float, float, float] | None = None,
3554 interpolation_stage: Literal["data", "rgba"] | None = None,
3555 filternorm: bool = True,
3556 filterrad: float = 4.0,
3557 resample: bool | None = None,
3558 url: str | None = None,
3559 data=None,
3560 **kwargs,
3561) -> AxesImage:
3562 __ret = gca().imshow(
3563 X,
3564 cmap=cmap,
3565 norm=norm,
3566 aspect=aspect,
3567 interpolation=interpolation,
3568 alpha=alpha,
3569 vmin=vmin,
3570 vmax=vmax,
3571 origin=origin,
3572 extent=extent,
3573 interpolation_stage=interpolation_stage,
3574 filternorm=filternorm,
3575 filterrad=filterrad,
3576 resample=resample,
3577 url=url,
3578 **({"data": data} if data is not None else {}),
3579 **kwargs,
3580 )
3581 sci(__ret)
3582 return __ret
3583
3584
3585# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3586@_copy_docstring_and_deprecators(Axes.legend)
3587def legend(*args, **kwargs) -> Legend:
3588 return gca().legend(*args, **kwargs)
3589
3590
3591# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3592@_copy_docstring_and_deprecators(Axes.locator_params)
3593def locator_params(
3594 axis: Literal["both", "x", "y"] = "both", tight: bool | None = None, **kwargs
3595) -> None:
3596 gca().locator_params(axis=axis, tight=tight, **kwargs)
3597
3598
3599# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3600@_copy_docstring_and_deprecators(Axes.loglog)
3601def loglog(*args, **kwargs) -> list[Line2D]:
3602 return gca().loglog(*args, **kwargs)
3603
3604
3605# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3606@_copy_docstring_and_deprecators(Axes.magnitude_spectrum)
3607def magnitude_spectrum(
3608 x: ArrayLike,
3609 Fs: float | None = None,
3610 Fc: int | None = None,
3611 window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
3612 pad_to: int | None = None,
3613 sides: Literal["default", "onesided", "twosided"] | None = None,
3614 scale: Literal["default", "linear", "dB"] | None = None,
3615 *,
3616 data=None,
3617 **kwargs,
3618) -> tuple[np.ndarray, np.ndarray, Line2D]:
3619 return gca().magnitude_spectrum(
3620 x,
3621 Fs=Fs,
3622 Fc=Fc,
3623 window=window,
3624 pad_to=pad_to,
3625 sides=sides,
3626 scale=scale,
3627 **({"data": data} if data is not None else {}),
3628 **kwargs,
3629 )
3630
3631
3632# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3633@_copy_docstring_and_deprecators(Axes.margins)
3634def margins(
3635 *margins: float,
3636 x: float | None = None,
3637 y: float | None = None,
3638 tight: bool | None = True,
3639) -> tuple[float, float] | None:
3640 return gca().margins(*margins, x=x, y=y, tight=tight)
3641
3642
3643# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3644@_copy_docstring_and_deprecators(Axes.minorticks_off)
3645def minorticks_off() -> None:
3646 gca().minorticks_off()
3647
3648
3649# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3650@_copy_docstring_and_deprecators(Axes.minorticks_on)
3651def minorticks_on() -> None:
3652 gca().minorticks_on()
3653
3654
3655# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3656@_copy_docstring_and_deprecators(Axes.pcolor)
3657def pcolor(
3658 *args: ArrayLike,
3659 shading: Literal["flat", "nearest", "auto"] | None = None,
3660 alpha: float | None = None,
3661 norm: str | Normalize | None = None,
3662 cmap: str | Colormap | None = None,
3663 vmin: float | None = None,
3664 vmax: float | None = None,
3665 data=None,
3666 **kwargs,
3667) -> Collection:
3668 __ret = gca().pcolor(
3669 *args,
3670 shading=shading,
3671 alpha=alpha,
3672 norm=norm,
3673 cmap=cmap,
3674 vmin=vmin,
3675 vmax=vmax,
3676 **({"data": data} if data is not None else {}),
3677 **kwargs,
3678 )
3679 sci(__ret)
3680 return __ret
3681
3682
3683# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3684@_copy_docstring_and_deprecators(Axes.pcolormesh)
3685def pcolormesh(
3686 *args: ArrayLike,
3687 alpha: float | None = None,
3688 norm: str | Normalize | None = None,
3689 cmap: str | Colormap | None = None,
3690 vmin: float | None = None,
3691 vmax: float | None = None,
3692 shading: Literal["flat", "nearest", "gouraud", "auto"] | None = None,
3693 antialiased: bool = False,
3694 data=None,
3695 **kwargs,
3696) -> QuadMesh:
3697 __ret = gca().pcolormesh(
3698 *args,
3699 alpha=alpha,
3700 norm=norm,
3701 cmap=cmap,
3702 vmin=vmin,
3703 vmax=vmax,
3704 shading=shading,
3705 antialiased=antialiased,
3706 **({"data": data} if data is not None else {}),
3707 **kwargs,
3708 )
3709 sci(__ret)
3710 return __ret
3711
3712
3713# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3714@_copy_docstring_and_deprecators(Axes.phase_spectrum)
3715def phase_spectrum(
3716 x: ArrayLike,
3717 Fs: float | None = None,
3718 Fc: int | None = None,
3719 window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
3720 pad_to: int | None = None,
3721 sides: Literal["default", "onesided", "twosided"] | None = None,
3722 *,
3723 data=None,
3724 **kwargs,
3725) -> tuple[np.ndarray, np.ndarray, Line2D]:
3726 return gca().phase_spectrum(
3727 x,
3728 Fs=Fs,
3729 Fc=Fc,
3730 window=window,
3731 pad_to=pad_to,
3732 sides=sides,
3733 **({"data": data} if data is not None else {}),
3734 **kwargs,
3735 )
3736
3737
3738# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3739@_copy_docstring_and_deprecators(Axes.pie)
3740def pie(
3741 x: ArrayLike,
3742 explode: ArrayLike | None = None,
3743 labels: Sequence[str] | None = None,
3744 colors: ColorType | Sequence[ColorType] | None = None,
3745 autopct: str | Callable[[float], str] | None = None,
3746 pctdistance: float = 0.6,
3747 shadow: bool = False,
3748 labeldistance: float | None = 1.1,
3749 startangle: float = 0,
3750 radius: float = 1,
3751 counterclock: bool = True,
3752 wedgeprops: dict[str, Any] | None = None,
3753 textprops: dict[str, Any] | None = None,
3754 center: tuple[float, float] = (0, 0),
3755 frame: bool = False,
3756 rotatelabels: bool = False,
3757 *,
3758 normalize: bool = True,
3759 hatch: str | Sequence[str] | None = None,
3760 data=None,
3761) -> tuple[list[Wedge], list[Text]] | tuple[list[Wedge], list[Text], list[Text]]:
3762 return gca().pie(
3763 x,
3764 explode=explode,
3765 labels=labels,
3766 colors=colors,
3767 autopct=autopct,
3768 pctdistance=pctdistance,
3769 shadow=shadow,
3770 labeldistance=labeldistance,
3771 startangle=startangle,
3772 radius=radius,
3773 counterclock=counterclock,
3774 wedgeprops=wedgeprops,
3775 textprops=textprops,
3776 center=center,
3777 frame=frame,
3778 rotatelabels=rotatelabels,
3779 normalize=normalize,
3780 hatch=hatch,
3781 **({"data": data} if data is not None else {}),
3782 )
3783
3784
3785# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3786@_copy_docstring_and_deprecators(Axes.plot)
3787def plot(
3788 *args: float | ArrayLike | str,
3789 scalex: bool = True,
3790 scaley: bool = True,
3791 data=None,
3792 **kwargs,
3793) -> list[Line2D]:
3794 return gca().plot(
3795 *args,
3796 scalex=scalex,
3797 scaley=scaley,
3798 **({"data": data} if data is not None else {}),
3799 **kwargs,
3800 )
3801
3802
3803# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3804@_copy_docstring_and_deprecators(Axes.plot_date)
3805def plot_date(
3806 x: ArrayLike,
3807 y: ArrayLike,
3808 fmt: str = "o",
3809 tz: str | datetime.tzinfo | None = None,
3810 xdate: bool = True,
3811 ydate: bool = False,
3812 *,
3813 data=None,
3814 **kwargs,
3815) -> list[Line2D]:
3816 return gca().plot_date(
3817 x,
3818 y,
3819 fmt=fmt,
3820 tz=tz,
3821 xdate=xdate,
3822 ydate=ydate,
3823 **({"data": data} if data is not None else {}),
3824 **kwargs,
3825 )
3826
3827
3828# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3829@_copy_docstring_and_deprecators(Axes.psd)
3830def psd(
3831 x: ArrayLike,
3832 NFFT: int | None = None,
3833 Fs: float | None = None,
3834 Fc: int | None = None,
3835 detrend: Literal["none", "mean", "linear"]
3836 | Callable[[ArrayLike], ArrayLike]
3837 | None = None,
3838 window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
3839 noverlap: int | None = None,
3840 pad_to: int | None = None,
3841 sides: Literal["default", "onesided", "twosided"] | None = None,
3842 scale_by_freq: bool | None = None,
3843 return_line: bool | None = None,
3844 *,
3845 data=None,
3846 **kwargs,
3847) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]:
3848 return gca().psd(
3849 x,
3850 NFFT=NFFT,
3851 Fs=Fs,
3852 Fc=Fc,
3853 detrend=detrend,
3854 window=window,
3855 noverlap=noverlap,
3856 pad_to=pad_to,
3857 sides=sides,
3858 scale_by_freq=scale_by_freq,
3859 return_line=return_line,
3860 **({"data": data} if data is not None else {}),
3861 **kwargs,
3862 )
3863
3864
3865# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3866@_copy_docstring_and_deprecators(Axes.quiver)
3867def quiver(*args, data=None, **kwargs) -> Quiver:
3868 __ret = gca().quiver(
3869 *args, **({"data": data} if data is not None else {}), **kwargs
3870 )
3871 sci(__ret)
3872 return __ret
3873
3874
3875# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3876@_copy_docstring_and_deprecators(Axes.quiverkey)
3877def quiverkey(
3878 Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs
3879) -> QuiverKey:
3880 return gca().quiverkey(Q, X, Y, U, label, **kwargs)
3881
3882
3883# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3884@_copy_docstring_and_deprecators(Axes.scatter)
3885def scatter(
3886 x: float | ArrayLike,
3887 y: float | ArrayLike,
3888 s: float | ArrayLike | None = None,
3889 c: ArrayLike | Sequence[ColorType] | ColorType | None = None,
3890 marker: MarkerType | None = None,
3891 cmap: str | Colormap | None = None,
3892 norm: str | Normalize | None = None,
3893 vmin: float | None = None,
3894 vmax: float | None = None,
3895 alpha: float | None = None,
3896 linewidths: float | Sequence[float] | None = None,
3897 *,
3898 edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = None,
3899 plotnonfinite: bool = False,
3900 data=None,
3901 **kwargs,
3902) -> PathCollection:
3903 __ret = gca().scatter(
3904 x,
3905 y,
3906 s=s,
3907 c=c,
3908 marker=marker,
3909 cmap=cmap,
3910 norm=norm,
3911 vmin=vmin,
3912 vmax=vmax,
3913 alpha=alpha,
3914 linewidths=linewidths,
3915 edgecolors=edgecolors,
3916 plotnonfinite=plotnonfinite,
3917 **({"data": data} if data is not None else {}),
3918 **kwargs,
3919 )
3920 sci(__ret)
3921 return __ret
3922
3923
3924# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3925@_copy_docstring_and_deprecators(Axes.semilogx)
3926def semilogx(*args, **kwargs) -> list[Line2D]:
3927 return gca().semilogx(*args, **kwargs)
3928
3929
3930# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3931@_copy_docstring_and_deprecators(Axes.semilogy)
3932def semilogy(*args, **kwargs) -> list[Line2D]:
3933 return gca().semilogy(*args, **kwargs)
3934
3935
3936# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3937@_copy_docstring_and_deprecators(Axes.specgram)
3938def specgram(
3939 x: ArrayLike,
3940 NFFT: int | None = None,
3941 Fs: float | None = None,
3942 Fc: int | None = None,
3943 detrend: Literal["none", "mean", "linear"]
3944 | Callable[[ArrayLike], ArrayLike]
3945 | None = None,
3946 window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
3947 noverlap: int | None = None,
3948 cmap: str | Colormap | None = None,
3949 xextent: tuple[float, float] | None = None,
3950 pad_to: int | None = None,
3951 sides: Literal["default", "onesided", "twosided"] | None = None,
3952 scale_by_freq: bool | None = None,
3953 mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = None,
3954 scale: Literal["default", "linear", "dB"] | None = None,
3955 vmin: float | None = None,
3956 vmax: float | None = None,
3957 *,
3958 data=None,
3959 **kwargs,
3960) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]:
3961 __ret = gca().specgram(
3962 x,
3963 NFFT=NFFT,
3964 Fs=Fs,
3965 Fc=Fc,
3966 detrend=detrend,
3967 window=window,
3968 noverlap=noverlap,
3969 cmap=cmap,
3970 xextent=xextent,
3971 pad_to=pad_to,
3972 sides=sides,
3973 scale_by_freq=scale_by_freq,
3974 mode=mode,
3975 scale=scale,
3976 vmin=vmin,
3977 vmax=vmax,
3978 **({"data": data} if data is not None else {}),
3979 **kwargs,
3980 )
3981 sci(__ret[-1])
3982 return __ret
3983
3984
3985# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
3986@_copy_docstring_and_deprecators(Axes.spy)
3987def spy(
3988 Z: ArrayLike,
3989 precision: float | Literal["present"] = 0,
3990 marker: str | None = None,
3991 markersize: float | None = None,
3992 aspect: Literal["equal", "auto"] | float | None = "equal",
3993 origin: Literal["upper", "lower"] = "upper",
3994 **kwargs,
3995) -> AxesImage:
3996 __ret = gca().spy(
3997 Z,
3998 precision=precision,
3999 marker=marker,
4000 markersize=markersize,
4001 aspect=aspect,
4002 origin=origin,
4003 **kwargs,
4004 )
4005 if isinstance(__ret, cm.ScalarMappable):
4006 sci(__ret) # noqa
4007 return __ret
4008
4009
4010# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4011@_copy_docstring_and_deprecators(Axes.stackplot)
4012def stackplot(
4013 x, *args, labels=(), colors=None, hatch=None, baseline="zero", data=None, **kwargs
4014):
4015 return gca().stackplot(
4016 x,
4017 *args,
4018 labels=labels,
4019 colors=colors,
4020 hatch=hatch,
4021 baseline=baseline,
4022 **({"data": data} if data is not None else {}),
4023 **kwargs,
4024 )
4025
4026
4027# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4028@_copy_docstring_and_deprecators(Axes.stem)
4029def stem(
4030 *args: ArrayLike | str,
4031 linefmt: str | None = None,
4032 markerfmt: str | None = None,
4033 basefmt: str | None = None,
4034 bottom: float = 0,
4035 label: str | None = None,
4036 orientation: Literal["vertical", "horizontal"] = "vertical",
4037 data=None,
4038) -> StemContainer:
4039 return gca().stem(
4040 *args,
4041 linefmt=linefmt,
4042 markerfmt=markerfmt,
4043 basefmt=basefmt,
4044 bottom=bottom,
4045 label=label,
4046 orientation=orientation,
4047 **({"data": data} if data is not None else {}),
4048 )
4049
4050
4051# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4052@_copy_docstring_and_deprecators(Axes.step)
4053def step(
4054 x: ArrayLike,
4055 y: ArrayLike,
4056 *args,
4057 where: Literal["pre", "post", "mid"] = "pre",
4058 data=None,
4059 **kwargs,
4060) -> list[Line2D]:
4061 return gca().step(
4062 x,
4063 y,
4064 *args,
4065 where=where,
4066 **({"data": data} if data is not None else {}),
4067 **kwargs,
4068 )
4069
4070
4071# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4072@_copy_docstring_and_deprecators(Axes.streamplot)
4073def streamplot(
4074 x,
4075 y,
4076 u,
4077 v,
4078 density=1,
4079 linewidth=None,
4080 color=None,
4081 cmap=None,
4082 norm=None,
4083 arrowsize=1,
4084 arrowstyle="-|>",
4085 minlength=0.1,
4086 transform=None,
4087 zorder=None,
4088 start_points=None,
4089 maxlength=4.0,
4090 integration_direction="both",
4091 broken_streamlines=True,
4092 *,
4093 data=None,
4094):
4095 __ret = gca().streamplot(
4096 x,
4097 y,
4098 u,
4099 v,
4100 density=density,
4101 linewidth=linewidth,
4102 color=color,
4103 cmap=cmap,
4104 norm=norm,
4105 arrowsize=arrowsize,
4106 arrowstyle=arrowstyle,
4107 minlength=minlength,
4108 transform=transform,
4109 zorder=zorder,
4110 start_points=start_points,
4111 maxlength=maxlength,
4112 integration_direction=integration_direction,
4113 broken_streamlines=broken_streamlines,
4114 **({"data": data} if data is not None else {}),
4115 )
4116 sci(__ret.lines)
4117 return __ret
4118
4119
4120# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4121@_copy_docstring_and_deprecators(Axes.table)
4122def table(
4123 cellText=None,
4124 cellColours=None,
4125 cellLoc="right",
4126 colWidths=None,
4127 rowLabels=None,
4128 rowColours=None,
4129 rowLoc="left",
4130 colLabels=None,
4131 colColours=None,
4132 colLoc="center",
4133 loc="bottom",
4134 bbox=None,
4135 edges="closed",
4136 **kwargs,
4137):
4138 return gca().table(
4139 cellText=cellText,
4140 cellColours=cellColours,
4141 cellLoc=cellLoc,
4142 colWidths=colWidths,
4143 rowLabels=rowLabels,
4144 rowColours=rowColours,
4145 rowLoc=rowLoc,
4146 colLabels=colLabels,
4147 colColours=colColours,
4148 colLoc=colLoc,
4149 loc=loc,
4150 bbox=bbox,
4151 edges=edges,
4152 **kwargs,
4153 )
4154
4155
4156# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4157@_copy_docstring_and_deprecators(Axes.text)
4158def text(
4159 x: float, y: float, s: str, fontdict: dict[str, Any] | None = None, **kwargs
4160) -> Text:
4161 return gca().text(x, y, s, fontdict=fontdict, **kwargs)
4162
4163
4164# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4165@_copy_docstring_and_deprecators(Axes.tick_params)
4166def tick_params(axis: Literal["both", "x", "y"] = "both", **kwargs) -> None:
4167 gca().tick_params(axis=axis, **kwargs)
4168
4169
4170# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4171@_copy_docstring_and_deprecators(Axes.ticklabel_format)
4172def ticklabel_format(
4173 *,
4174 axis: Literal["both", "x", "y"] = "both",
4175 style: Literal["", "sci", "scientific", "plain"] | None = None,
4176 scilimits: tuple[int, int] | None = None,
4177 useOffset: bool | float | None = None,
4178 useLocale: bool | None = None,
4179 useMathText: bool | None = None,
4180) -> None:
4181 gca().ticklabel_format(
4182 axis=axis,
4183 style=style,
4184 scilimits=scilimits,
4185 useOffset=useOffset,
4186 useLocale=useLocale,
4187 useMathText=useMathText,
4188 )
4189
4190
4191# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4192@_copy_docstring_and_deprecators(Axes.tricontour)
4193def tricontour(*args, **kwargs):
4194 __ret = gca().tricontour(*args, **kwargs)
4195 if __ret._A is not None: # type: ignore[attr-defined]
4196 sci(__ret)
4197 return __ret
4198
4199
4200# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4201@_copy_docstring_and_deprecators(Axes.tricontourf)
4202def tricontourf(*args, **kwargs):
4203 __ret = gca().tricontourf(*args, **kwargs)
4204 if __ret._A is not None: # type: ignore[attr-defined]
4205 sci(__ret)
4206 return __ret
4207
4208
4209# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4210@_copy_docstring_and_deprecators(Axes.tripcolor)
4211def tripcolor(
4212 *args,
4213 alpha=1.0,
4214 norm=None,
4215 cmap=None,
4216 vmin=None,
4217 vmax=None,
4218 shading="flat",
4219 facecolors=None,
4220 **kwargs,
4221):
4222 __ret = gca().tripcolor(
4223 *args,
4224 alpha=alpha,
4225 norm=norm,
4226 cmap=cmap,
4227 vmin=vmin,
4228 vmax=vmax,
4229 shading=shading,
4230 facecolors=facecolors,
4231 **kwargs,
4232 )
4233 sci(__ret)
4234 return __ret
4235
4236
4237# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4238@_copy_docstring_and_deprecators(Axes.triplot)
4239def triplot(*args, **kwargs):
4240 return gca().triplot(*args, **kwargs)
4241
4242
4243# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4244@_copy_docstring_and_deprecators(Axes.violinplot)
4245def violinplot(
4246 dataset: ArrayLike | Sequence[ArrayLike],
4247 positions: ArrayLike | None = None,
4248 vert: bool = True,
4249 widths: float | ArrayLike = 0.5,
4250 showmeans: bool = False,
4251 showextrema: bool = True,
4252 showmedians: bool = False,
4253 quantiles: Sequence[float | Sequence[float]] | None = None,
4254 points: int = 100,
4255 bw_method: Literal["scott", "silverman"]
4256 | float
4257 | Callable[[GaussianKDE], float]
4258 | None = None,
4259 side: Literal["both", "low", "high"] = "both",
4260 *,
4261 data=None,
4262) -> dict[str, Collection]:
4263 return gca().violinplot(
4264 dataset,
4265 positions=positions,
4266 vert=vert,
4267 widths=widths,
4268 showmeans=showmeans,
4269 showextrema=showextrema,
4270 showmedians=showmedians,
4271 quantiles=quantiles,
4272 points=points,
4273 bw_method=bw_method,
4274 side=side,
4275 **({"data": data} if data is not None else {}),
4276 )
4277
4278
4279# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4280@_copy_docstring_and_deprecators(Axes.vlines)
4281def vlines(
4282 x: float | ArrayLike,
4283 ymin: float | ArrayLike,
4284 ymax: float | ArrayLike,
4285 colors: ColorType | Sequence[ColorType] | None = None,
4286 linestyles: LineStyleType = "solid",
4287 label: str = "",
4288 *,
4289 data=None,
4290 **kwargs,
4291) -> LineCollection:
4292 return gca().vlines(
4293 x,
4294 ymin,
4295 ymax,
4296 colors=colors,
4297 linestyles=linestyles,
4298 label=label,
4299 **({"data": data} if data is not None else {}),
4300 **kwargs,
4301 )
4302
4303
4304# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4305@_copy_docstring_and_deprecators(Axes.xcorr)
4306def xcorr(
4307 x: ArrayLike,
4308 y: ArrayLike,
4309 normed: bool = True,
4310 detrend: Callable[[ArrayLike], ArrayLike] = mlab.detrend_none,
4311 usevlines: bool = True,
4312 maxlags: int = 10,
4313 *,
4314 data=None,
4315 **kwargs,
4316) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]:
4317 return gca().xcorr(
4318 x,
4319 y,
4320 normed=normed,
4321 detrend=detrend,
4322 usevlines=usevlines,
4323 maxlags=maxlags,
4324 **({"data": data} if data is not None else {}),
4325 **kwargs,
4326 )
4327
4328
4329# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4330@_copy_docstring_and_deprecators(Axes._sci)
4331def sci(im: ScalarMappable) -> None:
4332 gca()._sci(im)
4333
4334
4335# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4336@_copy_docstring_and_deprecators(Axes.set_title)
4337def title(
4338 label: str,
4339 fontdict: dict[str, Any] | None = None,
4340 loc: Literal["left", "center", "right"] | None = None,
4341 pad: float | None = None,
4342 *,
4343 y: float | None = None,
4344 **kwargs,
4345) -> Text:
4346 return gca().set_title(label, fontdict=fontdict, loc=loc, pad=pad, y=y, **kwargs)
4347
4348
4349# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4350@_copy_docstring_and_deprecators(Axes.set_xlabel)
4351def xlabel(
4352 xlabel: str,
4353 fontdict: dict[str, Any] | None = None,
4354 labelpad: float | None = None,
4355 *,
4356 loc: Literal["left", "center", "right"] | None = None,
4357 **kwargs,
4358) -> Text:
4359 return gca().set_xlabel(
4360 xlabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs
4361 )
4362
4363
4364# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4365@_copy_docstring_and_deprecators(Axes.set_ylabel)
4366def ylabel(
4367 ylabel: str,
4368 fontdict: dict[str, Any] | None = None,
4369 labelpad: float | None = None,
4370 *,
4371 loc: Literal["bottom", "center", "top"] | None = None,
4372 **kwargs,
4373) -> Text:
4374 return gca().set_ylabel(
4375 ylabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs
4376 )
4377
4378
4379# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4380@_copy_docstring_and_deprecators(Axes.set_xscale)
4381def xscale(value: str | ScaleBase, **kwargs) -> None:
4382 gca().set_xscale(value, **kwargs)
4383
4384
4385# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4386@_copy_docstring_and_deprecators(Axes.set_yscale)
4387def yscale(value: str | ScaleBase, **kwargs) -> None:
4388 gca().set_yscale(value, **kwargs)
4389
4390
4391# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4392def autumn() -> None:
4393 """
4394 Set the colormap to 'autumn'.
4395
4396 This changes the default colormap as well as the colormap of the current
4397 image if there is one. See ``help(colormaps)`` for more information.
4398 """
4399 set_cmap("autumn")
4400
4401
4402# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4403def bone() -> None:
4404 """
4405 Set the colormap to 'bone'.
4406
4407 This changes the default colormap as well as the colormap of the current
4408 image if there is one. See ``help(colormaps)`` for more information.
4409 """
4410 set_cmap("bone")
4411
4412
4413# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4414def cool() -> None:
4415 """
4416 Set the colormap to 'cool'.
4417
4418 This changes the default colormap as well as the colormap of the current
4419 image if there is one. See ``help(colormaps)`` for more information.
4420 """
4421 set_cmap("cool")
4422
4423
4424# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4425def copper() -> None:
4426 """
4427 Set the colormap to 'copper'.
4428
4429 This changes the default colormap as well as the colormap of the current
4430 image if there is one. See ``help(colormaps)`` for more information.
4431 """
4432 set_cmap("copper")
4433
4434
4435# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4436def flag() -> None:
4437 """
4438 Set the colormap to 'flag'.
4439
4440 This changes the default colormap as well as the colormap of the current
4441 image if there is one. See ``help(colormaps)`` for more information.
4442 """
4443 set_cmap("flag")
4444
4445
4446# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4447def gray() -> None:
4448 """
4449 Set the colormap to 'gray'.
4450
4451 This changes the default colormap as well as the colormap of the current
4452 image if there is one. See ``help(colormaps)`` for more information.
4453 """
4454 set_cmap("gray")
4455
4456
4457# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4458def hot() -> None:
4459 """
4460 Set the colormap to 'hot'.
4461
4462 This changes the default colormap as well as the colormap of the current
4463 image if there is one. See ``help(colormaps)`` for more information.
4464 """
4465 set_cmap("hot")
4466
4467
4468# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4469def hsv() -> None:
4470 """
4471 Set the colormap to 'hsv'.
4472
4473 This changes the default colormap as well as the colormap of the current
4474 image if there is one. See ``help(colormaps)`` for more information.
4475 """
4476 set_cmap("hsv")
4477
4478
4479# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4480def jet() -> None:
4481 """
4482 Set the colormap to 'jet'.
4483
4484 This changes the default colormap as well as the colormap of the current
4485 image if there is one. See ``help(colormaps)`` for more information.
4486 """
4487 set_cmap("jet")
4488
4489
4490# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4491def pink() -> None:
4492 """
4493 Set the colormap to 'pink'.
4494
4495 This changes the default colormap as well as the colormap of the current
4496 image if there is one. See ``help(colormaps)`` for more information.
4497 """
4498 set_cmap("pink")
4499
4500
4501# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4502def prism() -> None:
4503 """
4504 Set the colormap to 'prism'.
4505
4506 This changes the default colormap as well as the colormap of the current
4507 image if there is one. See ``help(colormaps)`` for more information.
4508 """
4509 set_cmap("prism")
4510
4511
4512# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4513def spring() -> None:
4514 """
4515 Set the colormap to 'spring'.
4516
4517 This changes the default colormap as well as the colormap of the current
4518 image if there is one. See ``help(colormaps)`` for more information.
4519 """
4520 set_cmap("spring")
4521
4522
4523# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4524def summer() -> None:
4525 """
4526 Set the colormap to 'summer'.
4527
4528 This changes the default colormap as well as the colormap of the current
4529 image if there is one. See ``help(colormaps)`` for more information.
4530 """
4531 set_cmap("summer")
4532
4533
4534# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4535def winter() -> None:
4536 """
4537 Set the colormap to 'winter'.
4538
4539 This changes the default colormap as well as the colormap of the current
4540 image if there is one. See ``help(colormaps)`` for more information.
4541 """
4542 set_cmap("winter")
4543
4544
4545# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4546def magma() -> None:
4547 """
4548 Set the colormap to 'magma'.
4549
4550 This changes the default colormap as well as the colormap of the current
4551 image if there is one. See ``help(colormaps)`` for more information.
4552 """
4553 set_cmap("magma")
4554
4555
4556# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4557def inferno() -> None:
4558 """
4559 Set the colormap to 'inferno'.
4560
4561 This changes the default colormap as well as the colormap of the current
4562 image if there is one. See ``help(colormaps)`` for more information.
4563 """
4564 set_cmap("inferno")
4565
4566
4567# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4568def plasma() -> None:
4569 """
4570 Set the colormap to 'plasma'.
4571
4572 This changes the default colormap as well as the colormap of the current
4573 image if there is one. See ``help(colormaps)`` for more information.
4574 """
4575 set_cmap("plasma")
4576
4577
4578# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4579def viridis() -> None:
4580 """
4581 Set the colormap to 'viridis'.
4582
4583 This changes the default colormap as well as the colormap of the current
4584 image if there is one. See ``help(colormaps)`` for more information.
4585 """
4586 set_cmap("viridis")
4587
4588
4589# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
4590def nipy_spectral() -> None:
4591 """
4592 Set the colormap to 'nipy_spectral'.
4593
4594 This changes the default colormap as well as the colormap of the current
4595 image if there is one. See ``help(colormaps)`` for more information.
4596 """
4597 set_cmap("nipy_spectral")