is_assignments/a2/code/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py

3251 lines
110 KiB
Python
Raw Normal View History

2022-12-19 10:09:00 +01:00
# Note: The first part of this file can be modified in place, but the latter
# part is autogenerated by the boilerplate.py script.
"""
`matplotlib.pyplot` is a state-based interface to matplotlib. It provides
an implicit, MATLAB-like, way of plotting. It also opens figures on your
screen, and acts as the figure GUI manager.
pyplot is mainly intended for interactive plots and simple cases of
programmatic plot generation::
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
The explicit object-oriented API is recommended for complex plots, though
pyplot is still usually used to create the figure and often the axes in the
figure. See `.pyplot.figure`, `.pyplot.subplots`, and
`.pyplot.subplot_mosaic` to create figures, and
:doc:`Axes API </api/axes_api>` for the plotting methods on an Axes::
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
See :ref:`api_interfaces` for an explanation of the tradeoffs between the
implicit and explicit interfaces.
"""
from contextlib import ExitStack
from enum import Enum
import functools
import importlib
import inspect
import logging
from numbers import Number
import re
import sys
import threading
import time
from cycler import cycler
import matplotlib
import matplotlib.colorbar
import matplotlib.image
from matplotlib import _api
from matplotlib import rcsetup, style
from matplotlib import _pylab_helpers, interactive
from matplotlib import cbook
from matplotlib import _docstring
from matplotlib.backend_bases import FigureCanvasBase, MouseButton
from matplotlib.figure import Figure, FigureBase, figaspect
from matplotlib.gridspec import GridSpec, SubplotSpec
from matplotlib import rcParams, rcParamsDefault, get_backend, rcParamsOrig
from matplotlib.rcsetup import interactive_bk as _interactive_bk
from matplotlib.artist import Artist
from matplotlib.axes import Axes, Subplot
from matplotlib.projections import PolarAxes
from matplotlib import mlab # for detrend_none, window_hanning
from matplotlib.scale import get_scale_names
from matplotlib import cm
from matplotlib.cm import _colormaps as colormaps, register_cmap
from matplotlib.colors import _color_sequences as color_sequences
import numpy as np
# We may not need the following imports here:
from matplotlib.colors import Normalize
from matplotlib.lines import Line2D
from matplotlib.text import Text, Annotation
from matplotlib.patches import Polygon, Rectangle, Circle, Arrow
from matplotlib.widgets import Button, Slider, Widget
from .ticker import (
TickHelper, Formatter, FixedFormatter, NullFormatter, FuncFormatter,
FormatStrFormatter, ScalarFormatter, LogFormatter, LogFormatterExponent,
LogFormatterMathtext, Locator, IndexLocator, FixedLocator, NullLocator,
LinearLocator, LogLocator, AutoLocator, MultipleLocator, MaxNLocator)
_log = logging.getLogger(__name__)
def _copy_docstring_and_deprecators(method, func=None):
if func is None:
return functools.partial(_copy_docstring_and_deprecators, method)
decorators = [_docstring.copy(method)]
# Check whether the definition of *method* includes @_api.rename_parameter
# or @_api.make_keyword_only decorators; if so, propagate them to the
# pyplot wrapper as well.
while getattr(method, "__wrapped__", None) is not None:
decorator = _api.deprecation.DECORATORS.get(method)
if decorator:
decorators.append(decorator)
method = method.__wrapped__
for decorator in decorators[::-1]:
func = decorator(func)
return func
## Global ##
# The state controlled by {,un}install_repl_displayhook().
_ReplDisplayHook = Enum("_ReplDisplayHook", ["NONE", "PLAIN", "IPYTHON"])
_REPL_DISPLAYHOOK = _ReplDisplayHook.NONE
def _draw_all_if_interactive():
if matplotlib.is_interactive():
draw_all()
def install_repl_displayhook():
"""
Connect to the display hook of the current shell.
The display hook gets called when the read-evaluate-print-loop (REPL) of
the shell has finished the execution of a command. We use this callback
to be able to automatically update a figure in interactive mode.
This works both with IPython and with vanilla python shells.
"""
global _REPL_DISPLAYHOOK
if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON:
return
# See if we have IPython hooks around, if so use them.
# Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
# entries can also have been explicitly set to None.
mod_ipython = sys.modules.get("IPython")
if not mod_ipython:
_REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN
return
ip = mod_ipython.get_ipython()
if not ip:
_REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN
return
ip.events.register("post_execute", _draw_all_if_interactive)
_REPL_DISPLAYHOOK = _ReplDisplayHook.IPYTHON
from IPython.core.pylabtools import backend2gui
# trigger IPython's eventloop integration, if available
ipython_gui_name = backend2gui.get(get_backend())
if ipython_gui_name:
ip.enable_gui(ipython_gui_name)
def uninstall_repl_displayhook():
"""Disconnect from the display hook of the current shell."""
global _REPL_DISPLAYHOOK
if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON:
from IPython import get_ipython
ip = get_ipython()
ip.events.unregister("post_execute", _draw_all_if_interactive)
_REPL_DISPLAYHOOK = _ReplDisplayHook.NONE
draw_all = _pylab_helpers.Gcf.draw_all
@_copy_docstring_and_deprecators(matplotlib.set_loglevel)
def set_loglevel(*args, **kwargs): # Ensure this appears in the pyplot docs.
return matplotlib.set_loglevel(*args, **kwargs)
@_copy_docstring_and_deprecators(Artist.findobj)
def findobj(o=None, match=None, include_self=True):
if o is None:
o = gcf()
return o.findobj(match, include_self=include_self)
def _get_required_interactive_framework(backend_mod):
if not hasattr(getattr(backend_mod, "FigureCanvas", None),
"required_interactive_framework"):
_api.warn_deprecated(
"3.6", name="Support for FigureCanvases without a "
"required_interactive_framework attribute")
return None
# Inline this once the deprecation elapses.
return backend_mod.FigureCanvas.required_interactive_framework
_backend_mod = None
def _get_backend_mod():
"""
Ensure that a backend is selected and return it.
This is currently private, but may be made public in the future.
"""
if _backend_mod is None:
# Use __getitem__ here to avoid going through the fallback logic (which
# will (re)import pyplot and then call switch_backend if we need to
# resolve the auto sentinel)
switch_backend(dict.__getitem__(rcParams, "backend"))
return _backend_mod
def switch_backend(newbackend):
"""
Close all open figures and set the Matplotlib backend.
The argument is case-insensitive. Switching to an interactive backend is
possible only if no event loop for another interactive backend has started.
Switching to and from non-interactive backends is always possible.
Parameters
----------
newbackend : str
The name of the backend to use.
"""
global _backend_mod
# make sure the init is pulled up so we can assign to it later
import matplotlib.backends
close("all")
if newbackend is rcsetup._auto_backend_sentinel:
current_framework = cbook._get_running_interactive_framework()
mapping = {'qt': 'qtagg',
'gtk3': 'gtk3agg',
'gtk4': 'gtk4agg',
'wx': 'wxagg',
'tk': 'tkagg',
'macosx': 'macosx',
'headless': 'agg'}
best_guess = mapping.get(current_framework, None)
if best_guess is not None:
candidates = [best_guess]
else:
candidates = []
candidates += [
"macosx", "qtagg", "gtk4agg", "gtk3agg", "tkagg", "wxagg"]
# Don't try to fallback on the cairo-based backends as they each have
# an additional dependency (pycairo) over the agg-based backend, and
# are of worse quality.
for candidate in candidates:
try:
switch_backend(candidate)
except ImportError:
continue
else:
rcParamsOrig['backend'] = candidate
return
else:
# Switching to Agg should always succeed; if it doesn't, let the
# exception propagate out.
switch_backend("agg")
rcParamsOrig["backend"] = "agg"
return
backend_mod = importlib.import_module(
cbook._backend_module_name(newbackend))
required_framework = _get_required_interactive_framework(backend_mod)
if required_framework is not None:
current_framework = cbook._get_running_interactive_framework()
if (current_framework and required_framework
and current_framework != required_framework):
raise ImportError(
"Cannot load backend {!r} which requires the {!r} interactive "
"framework, as {!r} is currently running".format(
newbackend, required_framework, current_framework))
# Load the new_figure_manager() and show() functions from the backend.
# Classically, backends can directly export these functions. This should
# keep working for backcompat.
new_figure_manager = getattr(backend_mod, "new_figure_manager", None)
# show = getattr(backend_mod, "show", None)
# In that classical approach, backends are implemented as modules, but
# "inherit" default method implementations from backend_bases._Backend.
# This is achieved by creating a "class" that inherits from
# backend_bases._Backend and whose body is filled with the module globals.
class backend_mod(matplotlib.backend_bases._Backend):
locals().update(vars(backend_mod))
# However, the newer approach for defining new_figure_manager (and, in
# the future, show) is to derive them from canvas methods. In that case,
# also update backend_mod accordingly; also, per-backend customization of
# draw_if_interactive is disabled.
if new_figure_manager is None:
# only try to get the canvas class if have opted into the new scheme
canvas_class = backend_mod.FigureCanvas
def new_figure_manager_given_figure(num, figure):
return canvas_class.new_manager(figure, num)
def new_figure_manager(num, *args, FigureClass=Figure, **kwargs):
fig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, fig)
def draw_if_interactive():
if matplotlib.is_interactive():
manager = _pylab_helpers.Gcf.get_active()
if manager:
manager.canvas.draw_idle()
backend_mod.new_figure_manager_given_figure = \
new_figure_manager_given_figure
backend_mod.new_figure_manager = new_figure_manager
backend_mod.draw_if_interactive = draw_if_interactive
_log.debug("Loaded backend %s version %s.",
newbackend, backend_mod.backend_version)
rcParams['backend'] = rcParamsDefault['backend'] = newbackend
_backend_mod = backend_mod
for func_name in ["new_figure_manager", "draw_if_interactive", "show"]:
globals()[func_name].__signature__ = inspect.signature(
getattr(backend_mod, func_name))
# Need to keep a global reference to the backend for compatibility reasons.
# See https://github.com/matplotlib/matplotlib/issues/6092
matplotlib.backends.backend = newbackend
# make sure the repl display hook is installed in case we become
# interactive
install_repl_displayhook()
def _warn_if_gui_out_of_main_thread():
warn = False
if _get_required_interactive_framework(_get_backend_mod()):
if hasattr(threading, 'get_native_id'):
# This compares native thread ids because even if Python-level
# Thread objects match, the underlying OS thread (which is what
# really matters) may be different on Python implementations with
# green threads.
if threading.get_native_id() != threading.main_thread().native_id:
warn = True
else:
# Fall back to Python-level Thread if native IDs are unavailable,
# mainly for PyPy.
if threading.current_thread() is not threading.main_thread():
warn = True
if warn:
_api.warn_external(
"Starting a Matplotlib GUI outside of the main thread will likely "
"fail.")
# This function's signature is rewritten upon backend-load by switch_backend.
def new_figure_manager(*args, **kwargs):
"""Create a new figure manager instance."""
_warn_if_gui_out_of_main_thread()
return _get_backend_mod().new_figure_manager(*args, **kwargs)
# This function's signature is rewritten upon backend-load by switch_backend.
def draw_if_interactive(*args, **kwargs):
"""
Redraw the current figure if in interactive mode.
.. warning::
End users will typically not have to call this function because the
the interactive mode takes care of this.
"""
return _get_backend_mod().draw_if_interactive(*args, **kwargs)
# This function's signature is rewritten upon backend-load by switch_backend.
def show(*args, **kwargs):
"""
Display all open figures.
Parameters
----------
block : bool, optional
Whether to wait for all figures to be closed before returning.
If `True` block and run the GUI main loop until all figure windows
are closed.
If `False` ensure that all figure windows are displayed and return
immediately. In this case, you are responsible for ensuring
that the event loop is running to have responsive figures.
Defaults to True in non-interactive mode and to False in interactive
mode (see `.pyplot.isinteractive`).
See Also
--------
ion : Enable interactive mode, which shows / updates the figure after
every plotting command, so that calling ``show()`` is not necessary.
ioff : Disable interactive mode.
savefig : Save the figure to an image file instead of showing it on screen.
Notes
-----
**Saving figures to file and showing a window at the same time**
If you want an image file as well as a user interface window, use
`.pyplot.savefig` before `.pyplot.show`. At the end of (a blocking)
``show()`` the figure is closed and thus unregistered from pyplot. Calling
`.pyplot.savefig` afterwards would save a new and thus empty figure. This
limitation of command order does not apply if the show is non-blocking or
if you keep a reference to the figure and use `.Figure.savefig`.
**Auto-show in jupyter notebooks**
The jupyter backends (activated via ``%matplotlib inline``,
``%matplotlib notebook``, or ``%matplotlib widget``), call ``show()`` at
the end of every cell by default. Thus, you usually don't have to call it
explicitly there.
"""
_warn_if_gui_out_of_main_thread()
return _get_backend_mod().show(*args, **kwargs)
def isinteractive():
"""
Return whether plots are updated after every plotting command.
The interactive mode is mainly useful if you build plots from the command
line and want to see the effect of each command while you are building the
figure.
In interactive mode:
- newly created figures will be shown immediately;
- figures will automatically redraw on change;
- `.pyplot.show` will not block by default.
In non-interactive mode:
- newly created figures and changes to figures will not be reflected until
explicitly asked to be;
- `.pyplot.show` will block by default.
See Also
--------
ion : Enable interactive mode.
ioff : Disable interactive mode.
show : Show all figures (and maybe block).
pause : Show all figures, and block for a time.
"""
return matplotlib.is_interactive()
def ioff():
"""
Disable interactive mode.
See `.pyplot.isinteractive` for more details.
See Also
--------
ion : Enable interactive mode.
isinteractive : Whether interactive mode is enabled.
show : Show all figures (and maybe block).
pause : Show all figures, and block for a time.
Notes
-----
For a temporary change, this can be used as a context manager::
# if interactive mode is on
# then figures will be shown on creation
plt.ion()
# This figure will be shown immediately
fig = plt.figure()
with plt.ioff():
# interactive mode will be off
# figures will not automatically be shown
fig2 = plt.figure()
# ...
To enable optional usage as a context manager, this function returns a
`~contextlib.ExitStack` object, which is not intended to be stored or
accessed by the user.
"""
stack = ExitStack()
stack.callback(ion if isinteractive() else ioff)
matplotlib.interactive(False)
uninstall_repl_displayhook()
return stack
def ion():
"""
Enable interactive mode.
See `.pyplot.isinteractive` for more details.
See Also
--------
ioff : Disable interactive mode.
isinteractive : Whether interactive mode is enabled.
show : Show all figures (and maybe block).
pause : Show all figures, and block for a time.
Notes
-----
For a temporary change, this can be used as a context manager::
# if interactive mode is off
# then figures will not be shown on creation
plt.ioff()
# This figure will not be shown immediately
fig = plt.figure()
with plt.ion():
# interactive mode will be on
# figures will automatically be shown
fig2 = plt.figure()
# ...
To enable optional usage as a context manager, this function returns a
`~contextlib.ExitStack` object, which is not intended to be stored or
accessed by the user.
"""
stack = ExitStack()
stack.callback(ion if isinteractive() else ioff)
matplotlib.interactive(True)
install_repl_displayhook()
return stack
def pause(interval):
"""
Run the GUI event loop for *interval* seconds.
If there is an active figure, it will be updated and displayed before the
pause, and the GUI event loop (if any) will run during the pause.
This can be used for crude animation. For more complex animation use
:mod:`matplotlib.animation`.
If there is no active figure, sleep for *interval* seconds instead.
See Also
--------
matplotlib.animation : Proper animations
show : Show all figures and optional block until all figures are closed.
"""
manager = _pylab_helpers.Gcf.get_active()
if manager is not None:
canvas = manager.canvas
if canvas.figure.stale:
canvas.draw_idle()
show(block=False)
canvas.start_event_loop(interval)
else:
time.sleep(interval)
@_copy_docstring_and_deprecators(matplotlib.rc)
def rc(group, **kwargs):
matplotlib.rc(group, **kwargs)
@_copy_docstring_and_deprecators(matplotlib.rc_context)
def rc_context(rc=None, fname=None):
return matplotlib.rc_context(rc, fname)
@_copy_docstring_and_deprecators(matplotlib.rcdefaults)
def rcdefaults():
matplotlib.rcdefaults()
if matplotlib.is_interactive():
draw_all()
# getp/get/setp are explicitly reexported so that they show up in pyplot docs.
@_copy_docstring_and_deprecators(matplotlib.artist.getp)
def getp(obj, *args, **kwargs):
return matplotlib.artist.getp(obj, *args, **kwargs)
@_copy_docstring_and_deprecators(matplotlib.artist.get)
def get(obj, *args, **kwargs):
return matplotlib.artist.get(obj, *args, **kwargs)
@_copy_docstring_and_deprecators(matplotlib.artist.setp)
def setp(obj, *args, **kwargs):
return matplotlib.artist.setp(obj, *args, **kwargs)
def xkcd(scale=1, length=100, randomness=2):
"""
Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode. This will
only have effect on things drawn after this function is called.
For best results, the "Humor Sans" font should be installed: it is
not included with Matplotlib.
Parameters
----------
scale : float, optional
The amplitude of the wiggle perpendicular to the source line.
length : float, optional
The length of the wiggle along the line.
randomness : float, optional
The scale factor by which the length is shrunken or expanded.
Notes
-----
This function works by a number of rcParams, so it will probably
override others you have set before.
If you want the effects of this function to be temporary, it can
be used as a context manager, for example::
with plt.xkcd():
# This figure will be in XKCD-style
fig1 = plt.figure()
# ...
# This figure will be in regular style
fig2 = plt.figure()
"""
# This cannot be implemented in terms of contextmanager() or rc_context()
# because this needs to work as a non-contextmanager too.
if rcParams['text.usetex']:
raise RuntimeError(
"xkcd mode is not compatible with text.usetex = True")
stack = ExitStack()
stack.callback(dict.update, rcParams, rcParams.copy())
from matplotlib import patheffects
rcParams.update({
'font.family': ['xkcd', 'xkcd Script', 'Humor Sans', 'Comic Neue',
'Comic Sans MS'],
'font.size': 14.0,
'path.sketch': (scale, length, randomness),
'path.effects': [
patheffects.withStroke(linewidth=4, foreground="w")],
'axes.linewidth': 1.5,
'lines.linewidth': 2.0,
'figure.facecolor': 'white',
'grid.linewidth': 0.0,
'axes.grid': False,
'axes.unicode_minus': False,
'axes.edgecolor': 'black',
'xtick.major.size': 8,
'xtick.major.width': 3,
'ytick.major.size': 8,
'ytick.major.width': 3,
})
return stack
## Figures ##
@_api.make_keyword_only("3.6", "facecolor")
def figure(num=None, # autoincrement if None, else integer from 1-N
figsize=None, # defaults to rc figure.figsize
dpi=None, # defaults to rc figure.dpi
facecolor=None, # defaults to rc figure.facecolor
edgecolor=None, # defaults to rc figure.edgecolor
frameon=True,
FigureClass=Figure,
clear=False,
**kwargs
):
"""
Create a new figure, or activate an existing figure.
Parameters
----------
num : int or str or `.Figure` or `.SubFigure`, optional
A unique identifier for the figure.
If a figure with that identifier already exists, this figure is made
active and returned. An integer refers to the ``Figure.number``
attribute, a string refers to the figure label.
If there is no figure with the identifier or *num* is not given, a new
figure is created, made active and returned. If *num* is an int, it
will be used for the ``Figure.number`` attribute, otherwise, an
auto-generated integer value is used (starting at 1 and incremented
for each new figure). If *num* is a string, the figure label and the
window title is set to this value. If num is a ``SubFigure``, its
parent ``Figure`` is activated.
figsize : (float, float), default: :rc:`figure.figsize`
Width, height in inches.
dpi : float, default: :rc:`figure.dpi`
The resolution of the figure in dots-per-inch.
facecolor : color, default: :rc:`figure.facecolor`
The background color.
edgecolor : color, default: :rc:`figure.edgecolor`
The border color.
frameon : bool, default: True
If False, suppress drawing the figure frame.
FigureClass : subclass of `~matplotlib.figure.Figure`
If set, an instance of this subclass will be created, rather than a
plain `.Figure`.
clear : bool, default: False
If True and the figure already exists, then it is cleared.
layout : {'constrained', 'tight', `.LayoutEngine`, None}, default: None
The layout mechanism for positioning of plot elements to avoid
overlapping Axes decorations (labels, ticks, etc). Note that layout
managers can measurably slow down figure display. Defaults to *None*
(but see the documentation of the `.Figure` constructor regarding the
interaction with rcParams).
**kwargs
Additional keyword arguments are passed to the `.Figure` constructor.
Returns
-------
`~matplotlib.figure.Figure`
Notes
-----
Newly created figures are passed to the `~.FigureCanvasBase.new_manager`
method or the `new_figure_manager` function provided by the current
backend, which install a canvas and a manager on the figure.
If you are creating many figures, make sure you explicitly call
`.pyplot.close` on the figures you are not using, because this will
enable pyplot to properly clean up the memory.
`~matplotlib.rcParams` defines the default values, which can be modified
in the matplotlibrc file.
"""
if isinstance(num, FigureBase):
if num.canvas.manager is None:
raise ValueError("The passed figure is not managed by pyplot")
_pylab_helpers.Gcf.set_active(num.canvas.manager)
return num.figure
allnums = get_fignums()
next_num = max(allnums) + 1 if allnums else 1
fig_label = ''
if num is None:
num = next_num
elif isinstance(num, str):
fig_label = num
all_labels = get_figlabels()
if fig_label not in all_labels:
if fig_label == 'all':
_api.warn_external("close('all') closes all existing figures.")
num = next_num
else:
inum = all_labels.index(fig_label)
num = allnums[inum]
else:
num = int(num) # crude validation of num argument
manager = _pylab_helpers.Gcf.get_fig_manager(num)
if manager is None:
max_open_warning = rcParams['figure.max_open_warning']
if len(allnums) == max_open_warning >= 1:
_api.warn_external(
f"More than {max_open_warning} figures have been opened. "
f"Figures created through the pyplot interface "
f"(`matplotlib.pyplot.figure`) are retained until explicitly "
f"closed and may consume too much memory. (To control this "
f"warning, see the rcParam `figure.max_open_warning`). "
f"Consider using `matplotlib.pyplot.close()`.",
RuntimeWarning)
manager = new_figure_manager(
num, figsize=figsize, dpi=dpi,
facecolor=facecolor, edgecolor=edgecolor, frameon=frameon,
FigureClass=FigureClass, **kwargs)
fig = manager.canvas.figure
if fig_label:
fig.set_label(fig_label)
_pylab_helpers.Gcf._set_new_active_manager(manager)
# make sure backends (inline) that we don't ship that expect this
# to be called in plotting commands to make the figure call show
# still work. There is probably a better way to do this in the
# FigureManager base class.
draw_if_interactive()
if _REPL_DISPLAYHOOK is _ReplDisplayHook.PLAIN:
fig.stale_callback = _auto_draw_if_interactive
if clear:
manager.canvas.figure.clear()
return manager.canvas.figure
def _auto_draw_if_interactive(fig, val):
"""
An internal helper function for making sure that auto-redrawing
works as intended in the plain python repl.
Parameters
----------
fig : Figure
A figure object which is assumed to be associated with a canvas
"""
if (val and matplotlib.is_interactive()
and not fig.canvas.is_saving()
and not fig.canvas._is_idle_drawing):
# Some artists can mark themselves as stale in the middle of drawing
# (e.g. axes position & tick labels being computed at draw time), but
# this shouldn't trigger a redraw because the current redraw will
# already take them into account.
with fig.canvas._idle_draw_cntx():
fig.canvas.draw_idle()
def gcf():
"""
Get the current figure.
If there is currently no figure on the pyplot figure stack, a new one is
created using `~.pyplot.figure()`. (To test whether there is currently a
figure on the pyplot figure stack, check whether `~.pyplot.get_fignums()`
is empty.)
"""
manager = _pylab_helpers.Gcf.get_active()
if manager is not None:
return manager.canvas.figure
else:
return figure()
def fignum_exists(num):
"""Return whether the figure with the given id exists."""
return _pylab_helpers.Gcf.has_fignum(num) or num in get_figlabels()
def get_fignums():
"""Return a list of existing figure numbers."""
return sorted(_pylab_helpers.Gcf.figs)
def get_figlabels():
"""Return a list of existing figure labels."""
managers = _pylab_helpers.Gcf.get_all_fig_managers()
managers.sort(key=lambda m: m.num)
return [m.canvas.figure.get_label() for m in managers]
def get_current_fig_manager():
"""
Return the figure manager of the current figure.
The figure manager is a container for the actual backend-depended window
that displays the figure on screen.
If no current figure exists, a new one is created, and its figure
manager is returned.
Returns
-------
`.FigureManagerBase` or backend-dependent subclass thereof
"""
return gcf().canvas.manager
@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_connect)
def connect(s, func):
return gcf().canvas.mpl_connect(s, func)
@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_disconnect)
def disconnect(cid):
return gcf().canvas.mpl_disconnect(cid)
def close(fig=None):
"""
Close a figure window.
Parameters
----------
fig : None or int or str or `.Figure`
The figure to close. There are a number of ways to specify this:
- *None*: the current figure
- `.Figure`: the given `.Figure` instance
- ``int``: a figure number
- ``str``: a figure name
- 'all': all figures
"""
if fig is None:
manager = _pylab_helpers.Gcf.get_active()
if manager is None:
return
else:
_pylab_helpers.Gcf.destroy(manager)
elif fig == 'all':
_pylab_helpers.Gcf.destroy_all()
elif isinstance(fig, int):
_pylab_helpers.Gcf.destroy(fig)
elif hasattr(fig, 'int'):
# if we are dealing with a type UUID, we
# can use its integer representation
_pylab_helpers.Gcf.destroy(fig.int)
elif isinstance(fig, str):
all_labels = get_figlabels()
if fig in all_labels:
num = get_fignums()[all_labels.index(fig)]
_pylab_helpers.Gcf.destroy(num)
elif isinstance(fig, Figure):
_pylab_helpers.Gcf.destroy_fig(fig)
else:
raise TypeError("close() argument must be a Figure, an int, a string, "
"or None, not %s" % type(fig))
def clf():
"""Clear the current figure."""
gcf().clear()
def draw():
"""
Redraw the current figure.
This is used to update a figure that has been altered, but not
automatically re-drawn. If interactive mode is on (via `.ion()`), this
should be only rarely needed, but there may be ways to modify the state of
a figure without marking it as "stale". Please report these cases as bugs.
This is equivalent to calling ``fig.canvas.draw_idle()``, where ``fig`` is
the current figure.
"""
gcf().canvas.draw_idle()
@_copy_docstring_and_deprecators(Figure.savefig)
def savefig(*args, **kwargs):
fig = gcf()
res = fig.savefig(*args, **kwargs)
fig.canvas.draw_idle() # Need this if 'transparent=True', to reset colors.
return res
## Putting things in figures ##
def figlegend(*args, **kwargs):
return gcf().legend(*args, **kwargs)
if Figure.legend.__doc__:
figlegend.__doc__ = Figure.legend.__doc__.replace("legend(", "figlegend(")
## Axes ##
@_docstring.dedent_interpd
def axes(arg=None, **kwargs):
"""
Add an Axes to the current figure and make it the current Axes.
Call signatures::
plt.axes()
plt.axes(rect, projection=None, polar=False, **kwargs)
plt.axes(ax)
Parameters
----------
arg : None or 4-tuple
The exact behavior of this function depends on the type:
- *None*: A new full window Axes is added using
``subplot(**kwargs)``.
- 4-tuple of floats *rect* = ``[left, bottom, width, height]``.
A new Axes is added with dimensions *rect* in normalized
(0, 1) units using `~.Figure.add_axes` on the current figure.
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
The projection type of the `~.axes.Axes`. *str* is the name of
a custom projection, see `~matplotlib.projections`. The default
None results in a 'rectilinear' projection.
polar : bool, default: False
If True, equivalent to projection='polar'.
sharex, sharey : `~.axes.Axes`, optional
Share the x or y `~matplotlib.axis` with sharex and/or sharey.
The axis will have the same limits, ticks, and scale as the axis
of the shared Axes.
label : str
A label for the returned Axes.
Returns
-------
`~.axes.Axes`, or a subclass of `~.axes.Axes`
The returned axes class depends on the projection used. It is
`~.axes.Axes` if rectilinear projection is used and
`.projections.polar.PolarAxes` if polar projection is used.
Other Parameters
----------------
**kwargs
This method also takes the keyword arguments for
the returned Axes class. The keyword arguments for the
rectilinear Axes class `~.axes.Axes` can be found in
the following table but there might also be other keyword
arguments if another projection is used, see the actual Axes
class.
%(Axes:kwdoc)s
Notes
-----
If the figure already has an Axes with key (*args*,
*kwargs*) then it will simply make that axes current and
return it. This behavior is deprecated. Meanwhile, if you do
not want this behavior (i.e., you want to force the creation of a
new axes), you must use a unique set of args and kwargs. The Axes
*label* attribute has been exposed for this purpose: if you want
two Axes that are otherwise identical to be added to the figure,
make sure you give them unique labels.
See Also
--------
.Figure.add_axes
.pyplot.subplot
.Figure.add_subplot
.Figure.subplots
.pyplot.subplots
Examples
--------
::
# Creating a new full window Axes
plt.axes()
# Creating a new Axes with specified dimensions and a grey background
plt.axes((left, bottom, width, height), facecolor='grey')
"""
fig = gcf()
pos = kwargs.pop('position', None)
if arg is None:
if pos is None:
return fig.add_subplot(**kwargs)
else:
return fig.add_axes(pos, **kwargs)
else:
return fig.add_axes(arg, **kwargs)
def delaxes(ax=None):
"""
Remove an `~.axes.Axes` (defaulting to the current axes) from its figure.
"""
if ax is None:
ax = gca()
ax.remove()
def sca(ax):
"""
Set the current Axes to *ax* and the current Figure to the parent of *ax*.
"""
figure(ax.figure)
ax.figure.sca(ax)
def cla():
"""Clear the current axes."""
# Not generated via boilerplate.py to allow a different docstring.
return gca().cla()
## More ways of creating axes ##
@_docstring.dedent_interpd
def subplot(*args, **kwargs):
"""
Add an Axes to the current figure or retrieve an existing Axes.
This is a wrapper of `.Figure.add_subplot` which provides additional
behavior when working with the implicit API (see the notes section).
Call signatures::
subplot(nrows, ncols, index, **kwargs)
subplot(pos, **kwargs)
subplot(**kwargs)
subplot(ax)
Parameters
----------
*args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
The position of the subplot described by one of
- Three integers (*nrows*, *ncols*, *index*). The subplot will take the
*index* position on a grid with *nrows* rows and *ncols* columns.
*index* starts at 1 in the upper left corner and increases to the
right. *index* can also be a two-tuple specifying the (*first*,
*last*) indices (1-based, and including *last*) of the subplot, e.g.,
``fig.add_subplot(3, 1, (1, 2))`` makes a subplot that spans the
upper 2/3 of the figure.
- A 3-digit integer. The digits are interpreted as if given separately
as three single-digit integers, i.e. ``fig.add_subplot(235)`` is the
same as ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
if there are no more than 9 subplots.
- A `.SubplotSpec`.
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
The projection type of the subplot (`~.axes.Axes`). *str* is the name
of a custom projection, see `~matplotlib.projections`. The default
None results in a 'rectilinear' projection.
polar : bool, default: False
If True, equivalent to projection='polar'.
sharex, sharey : `~.axes.Axes`, optional
Share the x or y `~matplotlib.axis` with sharex and/or sharey. The
axis will have the same limits, ticks, and scale as the axis of the
shared axes.
label : str
A label for the returned axes.
Returns
-------
`.axes.SubplotBase`, or another subclass of `~.axes.Axes`
The axes of the subplot. The returned axes base class depends on
the projection used. It is `~.axes.Axes` if rectilinear projection
is used and `.projections.polar.PolarAxes` if polar projection
is used. The returned axes is then a subplot subclass of the
base class.
Other Parameters
----------------
**kwargs
This method also takes the keyword arguments for the returned axes
base class; except for the *figure* argument. The keyword arguments
for the rectilinear base class `~.axes.Axes` can be found in
the following table but there might also be other keyword
arguments if another projection is used.
%(Axes:kwdoc)s
Notes
-----
Creating a new Axes will delete any preexisting Axes that
overlaps with it beyond sharing a boundary::
import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
plt.plot([1, 2, 3])
# now create a subplot which represents the top plot of a grid
# with 2 rows and 1 column. Since this subplot will overlap the
# first, the plot (and its axes) previously created, will be removed
plt.subplot(211)
If you do not want this behavior, use the `.Figure.add_subplot` method
or the `.pyplot.axes` function instead.
If no *kwargs* are passed and there exists an Axes in the location
specified by *args* then that Axes will be returned rather than a new
Axes being created.
If *kwargs* are passed and there exists an Axes in the location
specified by *args*, the projection type is the same, and the
*kwargs* match with the existing Axes, then the existing Axes is
returned. Otherwise a new Axes is created with the specified
parameters. We save a reference to the *kwargs* which we use
for this comparison. If any of the values in *kwargs* are
mutable we will not detect the case where they are mutated.
In these cases we suggest using `.Figure.add_subplot` and the
explicit Axes API rather than the implicit pyplot API.
See Also
--------
.Figure.add_subplot
.pyplot.subplots
.pyplot.axes
.Figure.subplots
Examples
--------
::
plt.subplot(221)
# equivalent but more general
ax1 = plt.subplot(2, 2, 1)
# add a subplot with no frame
ax2 = plt.subplot(222, frameon=False)
# add a polar subplot
plt.subplot(223, projection='polar')
# add a red subplot that shares the x-axis with ax1
plt.subplot(224, sharex=ax1, facecolor='red')
# delete ax2 from the figure
plt.delaxes(ax2)
# add ax2 to the figure again
plt.subplot(ax2)
# make the first axes "current" again
plt.subplot(221)
"""
# Here we will only normalize `polar=True` vs `projection='polar'` and let
# downstream code deal with the rest.
unset = object()
projection = kwargs.get('projection', unset)
polar = kwargs.pop('polar', unset)
if polar is not unset and polar:
# if we got mixed messages from the user, raise
if projection is not unset and projection != 'polar':
raise ValueError(
f"polar={polar}, yet projection={projection!r}. "
"Only one of these arguments should be supplied."
)
kwargs['projection'] = projection = 'polar'
# if subplot called without arguments, create subplot(1, 1, 1)
if len(args) == 0:
args = (1, 1, 1)
# This check was added because it is very easy to type subplot(1, 2, False)
# when subplots(1, 2, False) was intended (sharex=False, that is). In most
# cases, no error will ever occur, but mysterious behavior can result
# because what was intended to be the sharex argument is instead treated as
# a subplot index for subplot()
if len(args) >= 3 and isinstance(args[2], bool):
_api.warn_external("The subplot index argument to subplot() appears "
"to be a boolean. Did you intend to use "
"subplots()?")
# Check for nrows and ncols, which are not valid subplot args:
if 'nrows' in kwargs or 'ncols' in kwargs:
raise TypeError("subplot() got an unexpected keyword argument 'ncols' "
"and/or 'nrows'. Did you intend to call subplots()?")
fig = gcf()
# First, search for an existing subplot with a matching spec.
key = SubplotSpec._from_subplot_args(fig, args)
for ax in fig.axes:
# if we found an Axes at the position sort out if we can re-use it
if hasattr(ax, 'get_subplotspec') and ax.get_subplotspec() == key:
# if the user passed no kwargs, re-use
if kwargs == {}:
break
# if the axes class and kwargs are identical, reuse
elif ax._projection_init == fig._process_projection_requirements(
*args, **kwargs
):
break
else:
# we have exhausted the known Axes and none match, make a new one!
ax = fig.add_subplot(*args, **kwargs)
fig.sca(ax)
axes_to_delete = [other for other in fig.axes
if other != ax and ax.bbox.fully_overlaps(other.bbox)]
if axes_to_delete:
_api.warn_deprecated(
"3.6", message="Auto-removal of overlapping axes is deprecated "
"since %(since)s and will be removed %(removal)s; explicitly call "
"ax.remove() as needed.")
for ax_to_del in axes_to_delete:
delaxes(ax_to_del)
return ax
def subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True,
width_ratios=None, height_ratios=None,
subplot_kw=None, gridspec_kw=None, **fig_kw):
"""
Create a figure and a set of subplots.
This utility wrapper makes it convenient to create common layouts of
subplots, including the enclosing figure object, in a single call.
Parameters
----------
nrows, ncols : int, default: 1
Number of rows/columns of the subplot grid.
sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of properties among x (*sharex*) or y (*sharey*)
axes:
- True or 'all': x- or y-axis will be shared among all subplots.
- False or 'none': each subplot x- or y-axis will be independent.
- 'row': each subplot row will share an x- or y-axis.
- 'col': each subplot column will share an x- or y-axis.
When subplots have a shared x-axis along a column, only the x tick
labels of the bottom subplot are created. Similarly, when subplots
have a shared y-axis along a row, only the y tick labels of the first
column subplot are created. To later turn other subplots' ticklabels
on, use `~matplotlib.axes.Axes.tick_params`.
When subplots have a shared axis that has units, calling
`~matplotlib.axis.Axis.set_units` will update each axis with the
new units.
squeeze : bool, default: True
- If True, extra dimensions are squeezed out from the returned
array of `~matplotlib.axes.Axes`:
- if only one subplot is constructed (nrows=ncols=1), the
resulting single Axes object is returned as a scalar.
- for Nx1 or 1xM subplots, the returned object is a 1D numpy
object array of Axes objects.
- for NxM, subplots with N>1 and M>1 are returned as a 2D array.
- If False, no squeezing at all is done: the returned Axes object is
always a 2D array containing Axes instances, even if it ends up
being 1x1.
width_ratios : array-like of length *ncols*, optional
Defines the relative widths of the columns. Each column gets a
relative width of ``width_ratios[i] / sum(width_ratios)``.
If not given, all columns will have the same width. Equivalent
to ``gridspec_kw={'width_ratios': [...]}``.
height_ratios : array-like of length *nrows*, optional
Defines the relative heights of the rows. Each row gets a
relative height of ``height_ratios[i] / sum(height_ratios)``.
If not given, all rows will have the same height. Convenience
for ``gridspec_kw={'height_ratios': [...]}``.
subplot_kw : dict, optional
Dict with keywords passed to the
`~matplotlib.figure.Figure.add_subplot` call used to create each
subplot.
gridspec_kw : dict, optional
Dict with keywords passed to the `~matplotlib.gridspec.GridSpec`
constructor used to create the grid the subplots are placed on.
**fig_kw
All additional keyword arguments are passed to the
`.pyplot.figure` call.
Returns
-------
fig : `.Figure`
ax : `~.axes.Axes` or array of Axes
*ax* can be either a single `~.axes.Axes` object, or an array of Axes
objects if more than one subplot was created. The dimensions of the
resulting array can be controlled with the squeeze keyword, see above.
Typical idioms for handling the return value are::
# using the variable ax for single a Axes
fig, ax = plt.subplots()
# using the variable axs for multiple Axes
fig, axs = plt.subplots(2, 2)
# using tuple unpacking for multiple Axes
fig, (ax1, ax2) = plt.subplots(1, 2)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
The names ``ax`` and pluralized ``axs`` are preferred over ``axes``
because for the latter it's not clear if it refers to a single
`~.axes.Axes` instance or a collection of these.
See Also
--------
.pyplot.figure
.pyplot.subplot
.pyplot.axes
.Figure.subplots
.Figure.add_subplot
Examples
--------
::
# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Create two subplots and unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Create four polar axes and access them through the returned array
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)
# Share a X axis with each column of subplots
plt.subplots(2, 2, sharex='col')
# Share a Y axis with each row of subplots
plt.subplots(2, 2, sharey='row')
# Share both X and Y axes with all subplots
plt.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
plt.subplots(2, 2, sharex=True, sharey=True)
# Create figure number 10 with a single subplot
# and clears it if it already exists.
fig, ax = plt.subplots(num=10, clear=True)
"""
fig = figure(**fig_kw)
axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
squeeze=squeeze, subplot_kw=subplot_kw,
gridspec_kw=gridspec_kw, height_ratios=height_ratios,
width_ratios=width_ratios)
return fig, axs
def subplot_mosaic(mosaic, *, sharex=False, sharey=False,
width_ratios=None, height_ratios=None, empty_sentinel='.',
subplot_kw=None, gridspec_kw=None, **fig_kw):
"""
Build a layout of Axes based on ASCII art or nested lists.
This is a helper function to build complex GridSpec layouts visually.
.. note::
This API is provisional and may be revised in the future based on
early user feedback.
See :doc:`/tutorials/provisional/mosaic`
for an example and full API documentation
Parameters
----------
mosaic : list of list of {hashable or nested} or str
A visual layout of how you want your Axes to be arranged
labeled as strings. For example ::
x = [['A panel', 'A panel', 'edge'],
['C panel', '.', 'edge']]
produces 4 axes:
- 'A panel' which is 1 row high and spans the first two columns
- 'edge' which is 2 rows high and is on the right edge
- 'C panel' which in 1 row and 1 column wide in the bottom left
- a blank space 1 row and 1 column wide in the bottom center
Any of the entries in the layout can be a list of lists
of the same form to create nested layouts.
If input is a str, then it must be of the form ::
'''
AAE
C.E
'''
where each character is a column and each line is a row.
This only allows only single character Axes labels and does
not allow nesting but is very terse.
sharex, sharey : bool, default: False
If True, the x-axis (*sharex*) or y-axis (*sharey*) will be shared
among all subplots. In that case, tick label visibility and axis units
behave as for `subplots`. If False, each subplot's x- or y-axis will
be independent.
width_ratios : array-like of length *ncols*, optional
Defines the relative widths of the columns. Each column gets a
relative width of ``width_ratios[i] / sum(width_ratios)``.
If not given, all columns will have the same width. Convenience
for ``gridspec_kw={'width_ratios': [...]}``.
height_ratios : array-like of length *nrows*, optional
Defines the relative heights of the rows. Each row gets a
relative height of ``height_ratios[i] / sum(height_ratios)``.
If not given, all rows will have the same height. Convenience
for ``gridspec_kw={'height_ratios': [...]}``.
empty_sentinel : object, optional
Entry in the layout to mean "leave this space empty". Defaults
to ``'.'``. Note, if *layout* is a string, it is processed via
`inspect.cleandoc` to remove leading white space, which may
interfere with using white-space as the empty sentinel.
subplot_kw : dict, optional
Dictionary with keywords passed to the `.Figure.add_subplot` call
used to create each subplot.
gridspec_kw : dict, optional
Dictionary with keywords passed to the `.GridSpec` constructor used
to create the grid the subplots are placed on.
**fig_kw
All additional keyword arguments are passed to the
`.pyplot.figure` call.
Returns
-------
fig : `.Figure`
The new figure
dict[label, Axes]
A dictionary mapping the labels to the Axes objects. The order of
the axes is left-to-right and top-to-bottom of their position in the
total layout.
"""
fig = figure(**fig_kw)
ax_dict = fig.subplot_mosaic(
mosaic, sharex=sharex, sharey=sharey,
height_ratios=height_ratios, width_ratios=width_ratios,
subplot_kw=subplot_kw, gridspec_kw=gridspec_kw,
empty_sentinel=empty_sentinel
)
return fig, ax_dict
def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):
"""
Create a subplot at a specific location inside a regular grid.
Parameters
----------
shape : (int, int)
Number of rows and of columns of the grid in which to place axis.
loc : (int, int)
Row number and column number of the axis location within the grid.
rowspan : int, default: 1
Number of rows for the axis to span downwards.
colspan : int, default: 1
Number of columns for the axis to span to the right.
fig : `.Figure`, optional
Figure to place the subplot in. Defaults to the current figure.
**kwargs
Additional keyword arguments are handed to `~.Figure.add_subplot`.
Returns
-------
`.axes.SubplotBase`, or another subclass of `~.axes.Axes`
The axes of the subplot. The returned axes base class depends on the
projection used. It is `~.axes.Axes` if rectilinear projection is used
and `.projections.polar.PolarAxes` if polar projection is used. The
returned axes is then a subplot subclass of the base class.
Notes
-----
The following call ::
ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan)
is identical to ::
fig = gcf()
gs = fig.add_gridspec(nrows, ncols)
ax = fig.add_subplot(gs[row:row+rowspan, col:col+colspan])
"""
if fig is None:
fig = gcf()
rows, cols = shape
gs = GridSpec._check_gridspec_exists(fig, rows, cols)
subplotspec = gs.new_subplotspec(loc, rowspan=rowspan, colspan=colspan)
ax = fig.add_subplot(subplotspec, **kwargs)
axes_to_delete = [other for other in fig.axes
if other != ax and ax.bbox.fully_overlaps(other.bbox)]
if axes_to_delete:
_api.warn_deprecated(
"3.6", message="Auto-removal of overlapping axes is deprecated "
"since %(since)s and will be removed %(removal)s; explicitly call "
"ax.remove() as needed.")
for ax_to_del in axes_to_delete:
delaxes(ax_to_del)
return ax
def twinx(ax=None):
"""
Make and return a second axes that shares the *x*-axis. The new axes will
overlay *ax* (or the current axes if *ax* is *None*), and its ticks will be
on the right.
Examples
--------
:doc:`/gallery/subplots_axes_and_figures/two_scales`
"""
if ax is None:
ax = gca()
ax1 = ax.twinx()
return ax1
def twiny(ax=None):
"""
Make and return a second axes that shares the *y*-axis. The new axes will
overlay *ax* (or the current axes if *ax* is *None*), and its ticks will be
on the top.
Examples
--------
:doc:`/gallery/subplots_axes_and_figures/two_scales`
"""
if ax is None:
ax = gca()
ax1 = ax.twiny()
return ax1
def subplot_tool(targetfig=None):
"""
Launch a subplot tool window for a figure.
Returns
-------
`matplotlib.widgets.SubplotTool`
"""
if targetfig is None:
targetfig = gcf()
tb = targetfig.canvas.manager.toolbar
if hasattr(tb, "configure_subplots"): # toolbar2
return tb.configure_subplots()
elif hasattr(tb, "trigger_tool"): # toolmanager
return tb.trigger_tool("subplots")
else:
raise ValueError("subplot_tool can only be launched for figures with "
"an associated toolbar")
def box(on=None):
"""
Turn the axes box on or off on the current axes.
Parameters
----------
on : bool or None
The new `~matplotlib.axes.Axes` box state. If ``None``, toggle
the state.
See Also
--------
:meth:`matplotlib.axes.Axes.set_frame_on`
:meth:`matplotlib.axes.Axes.get_frame_on`
"""
ax = gca()
if on is None:
on = not ax.get_frame_on()
ax.set_frame_on(on)
## Axis ##
def xlim(*args, **kwargs):
"""
Get or set the x limits of the current axes.
Call signatures::
left, right = xlim() # return the current xlim
xlim((left, right)) # set the xlim to left, right
xlim(left, right) # set the xlim to left, right
If you do not specify args, you can pass *left* or *right* as kwargs,
i.e.::
xlim(right=3) # adjust the right leaving left unchanged
xlim(left=1) # adjust the left leaving right unchanged
Setting limits turns autoscaling off for the x-axis.
Returns
-------
left, right
A tuple of the new x-axis limits.
Notes
-----
Calling this function with no arguments (e.g. ``xlim()``) is the pyplot
equivalent of calling `~.Axes.get_xlim` on the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_xlim` on the current axes. All arguments are passed though.
"""
ax = gca()
if not args and not kwargs:
return ax.get_xlim()
ret = ax.set_xlim(*args, **kwargs)
return ret
def ylim(*args, **kwargs):
"""
Get or set the y-limits of the current axes.
Call signatures::
bottom, top = ylim() # return the current ylim
ylim((bottom, top)) # set the ylim to bottom, top
ylim(bottom, top) # set the ylim to bottom, top
If you do not specify args, you can alternatively pass *bottom* or
*top* as kwargs, i.e.::
ylim(top=3) # adjust the top leaving bottom unchanged
ylim(bottom=1) # adjust the bottom leaving top unchanged
Setting limits turns autoscaling off for the y-axis.
Returns
-------
bottom, top
A tuple of the new y-axis limits.
Notes
-----
Calling this function with no arguments (e.g. ``ylim()``) is the pyplot
equivalent of calling `~.Axes.get_ylim` on the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_ylim` on the current axes. All arguments are passed though.
"""
ax = gca()
if not args and not kwargs:
return ax.get_ylim()
ret = ax.set_ylim(*args, **kwargs)
return ret
def xticks(ticks=None, labels=None, *, minor=False, **kwargs):
"""
Get or set the current tick locations and labels of the x-axis.
Pass no arguments to return the current values without modifying them.
Parameters
----------
ticks : array-like, optional
The list of xtick locations. Passing an empty list removes all xticks.
labels : array-like, optional
The labels to place at the given *ticks* locations. This argument can
only be passed if *ticks* is passed as well.
minor : bool, default: False
If ``False``, get/set the major ticks/labels; if ``True``, the minor
ticks/labels.
**kwargs
`.Text` properties can be used to control the appearance of the labels.
Returns
-------
locs
The list of xtick locations.
labels
The list of xlabel `.Text` objects.
Notes
-----
Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
Examples
--------
>>> locs, labels = xticks() # Get the current locations and labels.
>>> xticks(np.arange(0, 1, step=0.2)) # Set label locations.
>>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
>>> xticks([0, 1, 2], ['January', 'February', 'March'],
... rotation=20) # Set text labels and properties.
>>> xticks([]) # Disable xticks.
"""
ax = gca()
if ticks is None:
locs = ax.get_xticks(minor=minor)
if labels is not None:
raise TypeError("xticks(): Parameter 'labels' can't be set "
"without setting 'ticks'")
else:
locs = ax.set_xticks(ticks, minor=minor)
if labels is None:
labels = ax.get_xticklabels(minor=minor)
for l in labels:
l._internal_update(kwargs)
else:
labels = ax.set_xticklabels(labels, minor=minor, **kwargs)
return locs, labels
def yticks(ticks=None, labels=None, *, minor=False, **kwargs):
"""
Get or set the current tick locations and labels of the y-axis.
Pass no arguments to return the current values without modifying them.
Parameters
----------
ticks : array-like, optional
The list of ytick locations. Passing an empty list removes all yticks.
labels : array-like, optional
The labels to place at the given *ticks* locations. This argument can
only be passed if *ticks* is passed as well.
minor : bool, default: False
If ``False``, get/set the major ticks/labels; if ``True``, the minor
ticks/labels.
**kwargs
`.Text` properties can be used to control the appearance of the labels.
Returns
-------
locs
The list of ytick locations.
labels
The list of ylabel `.Text` objects.
Notes
-----
Calling this function with no arguments (e.g. ``yticks()``) is the pyplot
equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on
the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current axes.
Examples
--------
>>> locs, labels = yticks() # Get the current locations and labels.
>>> yticks(np.arange(0, 1, step=0.2)) # Set label locations.
>>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
>>> yticks([0, 1, 2], ['January', 'February', 'March'],
... rotation=45) # Set text labels and properties.
>>> yticks([]) # Disable yticks.
"""
ax = gca()
if ticks is None:
locs = ax.get_yticks(minor=minor)
if labels is not None:
raise TypeError("yticks(): Parameter 'labels' can't be set "
"without setting 'ticks'")
else:
locs = ax.set_yticks(ticks, minor=minor)
if labels is None:
labels = ax.get_yticklabels(minor=minor)
for l in labels:
l._internal_update(kwargs)
else:
labels = ax.set_yticklabels(labels, minor=minor, **kwargs)
return locs, labels
def rgrids(radii=None, labels=None, angle=None, fmt=None, **kwargs):
"""
Get or set the radial gridlines on the current polar plot.
Call signatures::
lines, labels = rgrids()
lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs)
When called with no arguments, `.rgrids` simply returns the tuple
(*lines*, *labels*). When called with arguments, the labels will
appear at the specified radial distances and angle.
Parameters
----------
radii : tuple with floats
The radii for the radial gridlines
labels : tuple with strings or None
The labels to use at each radial gridline. The
`matplotlib.ticker.ScalarFormatter` will be used if None.
angle : float
The angular position of the radius labels in degrees.
fmt : str or None
Format string used in `matplotlib.ticker.FormatStrFormatter`.
For example '%f'.
Returns
-------
lines : list of `.lines.Line2D`
The radial gridlines.
labels : list of `.text.Text`
The tick labels.
Other Parameters
----------------
**kwargs
*kwargs* are optional `.Text` properties for the labels.
See Also
--------
.pyplot.thetagrids
.projections.polar.PolarAxes.set_rgrids
.Axis.get_gridlines
.Axis.get_ticklabels
Examples
--------
::
# set the locations of the radial gridlines
lines, labels = rgrids( (0.25, 0.5, 1.0) )
# set the locations and labels of the radial gridlines
lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ))
"""
ax = gca()
if not isinstance(ax, PolarAxes):
raise RuntimeError('rgrids only defined for polar axes')
if all(p is None for p in [radii, labels, angle, fmt]) and not kwargs:
lines = ax.yaxis.get_gridlines()
labels = ax.yaxis.get_ticklabels()
else:
lines, labels = ax.set_rgrids(
radii, labels=labels, angle=angle, fmt=fmt, **kwargs)
return lines, labels
def thetagrids(angles=None, labels=None, fmt=None, **kwargs):
"""
Get or set the theta gridlines on the current polar plot.
Call signatures::
lines, labels = thetagrids()
lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs)
When called with no arguments, `.thetagrids` simply returns the tuple
(*lines*, *labels*). When called with arguments, the labels will
appear at the specified angles.
Parameters
----------
angles : tuple with floats, degrees
The angles of the theta gridlines.
labels : tuple with strings or None
The labels to use at each radial gridline. The
`.projections.polar.ThetaFormatter` will be used if None.
fmt : str or None
Format string used in `matplotlib.ticker.FormatStrFormatter`.
For example '%f'. Note that the angle in radians will be used.
Returns
-------
lines : list of `.lines.Line2D`
The theta gridlines.
labels : list of `.text.Text`
The tick labels.
Other Parameters
----------------
**kwargs
*kwargs* are optional `.Text` properties for the labels.
See Also
--------
.pyplot.rgrids
.projections.polar.PolarAxes.set_thetagrids
.Axis.get_gridlines
.Axis.get_ticklabels
Examples
--------
::
# set the locations of the angular gridlines
lines, labels = thetagrids(range(45, 360, 90))
# set the locations and labels of the angular gridlines
lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE'))
"""
ax = gca()
if not isinstance(ax, PolarAxes):
raise RuntimeError('thetagrids only defined for polar axes')
if all(param is None for param in [angles, labels, fmt]) and not kwargs:
lines = ax.xaxis.get_ticklines()
labels = ax.xaxis.get_ticklabels()
else:
lines, labels = ax.set_thetagrids(angles,
labels=labels, fmt=fmt, **kwargs)
return lines, labels
_NON_PLOT_COMMANDS = {
'connect', 'disconnect', 'get_current_fig_manager', 'ginput',
'new_figure_manager', 'waitforbuttonpress'}
def get_plot_commands():
"""
Get a sorted list of all of the plotting commands.
"""
# This works by searching for all functions in this module and removing
# a few hard-coded exclusions, as well as all of the colormap-setting
# functions, and anything marked as private with a preceding underscore.
exclude = {'colormaps', 'colors', 'get_plot_commands',
*_NON_PLOT_COMMANDS, *colormaps}
this_module = inspect.getmodule(get_plot_commands)
return sorted(
name for name, obj in globals().items()
if not name.startswith('_') and name not in exclude
and inspect.isfunction(obj)
and inspect.getmodule(obj) is this_module)
## Plotting part 1: manually generated functions and wrappers ##
@_copy_docstring_and_deprecators(Figure.colorbar)
def colorbar(mappable=None, cax=None, ax=None, **kwargs):
if mappable is None:
mappable = gci()
if mappable is None:
raise RuntimeError('No mappable was found to use for colorbar '
'creation. First define a mappable such as '
'an image (with imshow) or a contour set ('
'with contourf).')
ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kwargs)
return ret
def clim(vmin=None, vmax=None):
"""
Set the color limits of the current image.
If either *vmin* or *vmax* is None, the image min/max respectively
will be used for color scaling.
If you want to set the clim of multiple images, use
`~.ScalarMappable.set_clim` on every image, for example::
for im in gca().get_images():
im.set_clim(0, 0.5)
"""
im = gci()
if im is None:
raise RuntimeError('You must first define an image, e.g., with imshow')
im.set_clim(vmin, vmax)
# eventually this implementation should move here, use indirection for now to
# avoid having two copies of the code floating around.
def get_cmap(name=None, lut=None):
return cm._get_cmap(name=name, lut=lut)
get_cmap.__doc__ = cm._get_cmap.__doc__
def set_cmap(cmap):
"""
Set the default colormap, and applies it to the current image if any.
Parameters
----------
cmap : `~matplotlib.colors.Colormap` or str
A colormap instance or the name of a registered colormap.
See Also
--------
colormaps
matplotlib.cm.register_cmap
matplotlib.cm.get_cmap
"""
cmap = get_cmap(cmap)
rc('image', cmap=cmap.name)
im = gci()
if im is not None:
im.set_cmap(cmap)
@_copy_docstring_and_deprecators(matplotlib.image.imread)
def imread(fname, format=None):
return matplotlib.image.imread(fname, format)
@_copy_docstring_and_deprecators(matplotlib.image.imsave)
def imsave(fname, arr, **kwargs):
return matplotlib.image.imsave(fname, arr, **kwargs)
def matshow(A, fignum=None, **kwargs):
"""
Display an array as a matrix in a new figure window.
The origin is set at the upper left hand corner and rows (first
dimension of the array) are displayed horizontally. The aspect
ratio of the figure window is that of the array, unless this would
make an excessively short or narrow figure.
Tick labels for the xaxis are placed on top.
Parameters
----------
A : 2D array-like
The matrix to be displayed.
fignum : None or int or False
If *None*, create a new figure window with automatic numbering.
If a nonzero integer, draw into the figure with the given number
(create it if it does not exist).
If 0, use the current axes (or create one if it does not exist).
.. note::
Because of how `.Axes.matshow` tries to set the figure aspect
ratio to be the one of the array, strange things may happen if you
reuse an existing figure.
Returns
-------
`~matplotlib.image.AxesImage`
Other Parameters
----------------
**kwargs : `~matplotlib.axes.Axes.imshow` arguments
"""
A = np.asanyarray(A)
if fignum == 0:
ax = gca()
else:
# Extract actual aspect ratio of array and make appropriately sized
# figure.
fig = figure(fignum, figsize=figaspect(A))
ax = fig.add_axes([0.15, 0.09, 0.775, 0.775])
im = ax.matshow(A, **kwargs)
sci(im)
return im
def polar(*args, **kwargs):
"""
Make a polar plot.
call signature::
polar(theta, r, **kwargs)
Multiple *theta*, *r* arguments are supported, with format strings, as in
`plot`.
"""
# If an axis already exists, check if it has a polar projection
if gcf().get_axes():
ax = gca()
if not isinstance(ax, PolarAxes):
_api.warn_external('Trying to create polar plot on an Axes '
'that does not have a polar projection.')
else:
ax = axes(projection="polar")
return ax.plot(*args, **kwargs)
# If rcParams['backend_fallback'] is true, and an interactive backend is
# requested, ignore rcParams['backend'] and force selection of a backend that
# is compatible with the current running interactive framework.
if (rcParams["backend_fallback"]
and rcParams._get_backend_or_none() in (
set(_interactive_bk) - {'WebAgg', 'nbAgg'})
and cbook._get_running_interactive_framework()):
dict.__setitem__(rcParams, "backend", rcsetup._auto_backend_sentinel)
################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure.figimage)
def figimage(
X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None,
vmax=None, origin=None, resize=False, **kwargs):
return gcf().figimage(
X, xo=xo, yo=yo, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
vmax=vmax, origin=origin, resize=resize, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure.text)
def figtext(x, y, s, fontdict=None, **kwargs):
return gcf().text(x, y, s, fontdict=fontdict, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure.gca)
def gca():
return gcf().gca()
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure._gci)
def gci():
return gcf()._gci()
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure.ginput)
def ginput(
n=1, timeout=30, show_clicks=True,
mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT,
mouse_stop=MouseButton.MIDDLE):
return gcf().ginput(
n=n, timeout=timeout, show_clicks=show_clicks,
mouse_add=mouse_add, mouse_pop=mouse_pop,
mouse_stop=mouse_stop)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure.subplots_adjust)
def subplots_adjust(
left=None, bottom=None, right=None, top=None, wspace=None,
hspace=None):
return gcf().subplots_adjust(
left=left, bottom=bottom, right=right, top=top, wspace=wspace,
hspace=hspace)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure.suptitle)
def suptitle(t, **kwargs):
return gcf().suptitle(t, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure.tight_layout)
def tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None):
return gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure.waitforbuttonpress)
def waitforbuttonpress(timeout=-1):
return gcf().waitforbuttonpress(timeout=timeout)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.acorr)
def acorr(x, *, data=None, **kwargs):
return gca().acorr(
x, **({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.angle_spectrum)
def angle_spectrum(
x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
data=None, **kwargs):
return gca().angle_spectrum(
x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.annotate)
def annotate(
text, xy, xytext=None, xycoords='data', textcoords=None,
arrowprops=None, annotation_clip=None, **kwargs):
return gca().annotate(
text, xy, xytext=xytext, xycoords=xycoords,
textcoords=textcoords, arrowprops=arrowprops,
annotation_clip=annotation_clip, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.arrow)
def arrow(x, y, dx, dy, **kwargs):
return gca().arrow(x, y, dx, dy, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.autoscale)
def autoscale(enable=True, axis='both', tight=None):
return gca().autoscale(enable=enable, axis=axis, tight=tight)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.axhline)
def axhline(y=0, xmin=0, xmax=1, **kwargs):
return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.axhspan)
def axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs):
return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.axis)
def axis(*args, emit=True, **kwargs):
return gca().axis(*args, emit=emit, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.axline)
def axline(xy1, xy2=None, *, slope=None, **kwargs):
return gca().axline(xy1, xy2=xy2, slope=slope, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.axvline)
def axvline(x=0, ymin=0, ymax=1, **kwargs):
return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.axvspan)
def axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs):
return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.bar)
def bar(
x, height, width=0.8, bottom=None, *, align='center',
data=None, **kwargs):
return gca().bar(
x, height, width=width, bottom=bottom, align=align,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.barbs)
def barbs(*args, data=None, **kwargs):
return gca().barbs(
*args, **({"data": data} if data is not None else {}),
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.barh)
def barh(
y, width, height=0.8, left=None, *, align='center',
data=None, **kwargs):
return gca().barh(
y, width, height=height, left=left, align=align,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.bar_label)
def bar_label(
container, labels=None, *, fmt='%g', label_type='edge',
padding=0, **kwargs):
return gca().bar_label(
container, labels=labels, fmt=fmt, label_type=label_type,
padding=padding, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.boxplot)
def boxplot(
x, notch=None, sym=None, vert=None, whis=None,
positions=None, widths=None, patch_artist=None,
bootstrap=None, usermedians=None, conf_intervals=None,
meanline=None, showmeans=None, showcaps=None, showbox=None,
showfliers=None, boxprops=None, labels=None, flierprops=None,
medianprops=None, meanprops=None, capprops=None,
whiskerprops=None, manage_ticks=True, autorange=False,
zorder=None, capwidths=None, *, data=None):
return gca().boxplot(
x, notch=notch, sym=sym, vert=vert, whis=whis,
positions=positions, widths=widths, patch_artist=patch_artist,
bootstrap=bootstrap, usermedians=usermedians,
conf_intervals=conf_intervals, meanline=meanline,
showmeans=showmeans, showcaps=showcaps, showbox=showbox,
showfliers=showfliers, boxprops=boxprops, labels=labels,
flierprops=flierprops, medianprops=medianprops,
meanprops=meanprops, capprops=capprops,
whiskerprops=whiskerprops, manage_ticks=manage_ticks,
autorange=autorange, zorder=zorder, capwidths=capwidths,
**({"data": data} if data is not None else {}))
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.broken_barh)
def broken_barh(xranges, yrange, *, data=None, **kwargs):
return gca().broken_barh(
xranges, yrange,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.clabel)
def clabel(CS, levels=None, **kwargs):
return gca().clabel(CS, levels=levels, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.cohere)
def cohere(
x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, *, data=None, **kwargs):
return gca().cohere(
x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
noverlap=noverlap, pad_to=pad_to, sides=sides,
scale_by_freq=scale_by_freq,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.contour)
def contour(*args, data=None, **kwargs):
__ret = gca().contour(
*args, **({"data": data} if data is not None else {}),
**kwargs)
if __ret._A is not None: sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.contourf)
def contourf(*args, data=None, **kwargs):
__ret = gca().contourf(
*args, **({"data": data} if data is not None else {}),
**kwargs)
if __ret._A is not None: sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.csd)
def csd(
x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
return_line=None, *, data=None, **kwargs):
return gca().csd(
x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
noverlap=noverlap, pad_to=pad_to, sides=sides,
scale_by_freq=scale_by_freq, return_line=return_line,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.errorbar)
def errorbar(
x, y, yerr=None, xerr=None, fmt='', ecolor=None,
elinewidth=None, capsize=None, barsabove=False, lolims=False,
uplims=False, xlolims=False, xuplims=False, errorevery=1,
capthick=None, *, data=None, **kwargs):
return gca().errorbar(
x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor,
elinewidth=elinewidth, capsize=capsize, barsabove=barsabove,
lolims=lolims, uplims=uplims, xlolims=xlolims,
xuplims=xuplims, errorevery=errorevery, capthick=capthick,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.eventplot)
def eventplot(
positions, orientation='horizontal', lineoffsets=1,
linelengths=1, linewidths=None, colors=None,
linestyles='solid', *, data=None, **kwargs):
return gca().eventplot(
positions, orientation=orientation, lineoffsets=lineoffsets,
linelengths=linelengths, linewidths=linewidths, colors=colors,
linestyles=linestyles,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.fill)
def fill(*args, data=None, **kwargs):
return gca().fill(
*args, **({"data": data} if data is not None else {}),
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.fill_between)
def fill_between(
x, y1, y2=0, where=None, interpolate=False, step=None, *,
data=None, **kwargs):
return gca().fill_between(
x, y1, y2=y2, where=where, interpolate=interpolate, step=step,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.fill_betweenx)
def fill_betweenx(
y, x1, x2=0, where=None, step=None, interpolate=False, *,
data=None, **kwargs):
return gca().fill_betweenx(
y, x1, x2=x2, where=where, step=step, interpolate=interpolate,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.grid)
def grid(visible=None, which='major', axis='both', **kwargs):
return gca().grid(visible=visible, which=which, axis=axis, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.hexbin)
def hexbin(
x, y, C=None, gridsize=100, bins=None, xscale='linear',
yscale='linear', extent=None, cmap=None, norm=None, vmin=None,
vmax=None, alpha=None, linewidths=None, edgecolors='face',
reduce_C_function=np.mean, mincnt=None, marginals=False, *,
data=None, **kwargs):
__ret = gca().hexbin(
x, y, C=C, gridsize=gridsize, bins=bins, xscale=xscale,
yscale=yscale, extent=extent, cmap=cmap, norm=norm, vmin=vmin,
vmax=vmax, alpha=alpha, linewidths=linewidths,
edgecolors=edgecolors, reduce_C_function=reduce_C_function,
mincnt=mincnt, marginals=marginals,
**({"data": data} if data is not None else {}), **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.hist)
def hist(
x, bins=None, range=None, density=False, weights=None,
cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, color=None,
label=None, stacked=False, *, data=None, **kwargs):
return gca().hist(
x, bins=bins, range=range, density=density, weights=weights,
cumulative=cumulative, bottom=bottom, histtype=histtype,
align=align, orientation=orientation, rwidth=rwidth, log=log,
color=color, label=label, stacked=stacked,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.stairs)
def stairs(
values, edges=None, *, orientation='vertical', baseline=0,
fill=False, data=None, **kwargs):
return gca().stairs(
values, edges=edges, orientation=orientation,
baseline=baseline, fill=fill,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.hist2d)
def hist2d(
x, y, bins=10, range=None, density=False, weights=None,
cmin=None, cmax=None, *, data=None, **kwargs):
__ret = gca().hist2d(
x, y, bins=bins, range=range, density=density,
weights=weights, cmin=cmin, cmax=cmax,
**({"data": data} if data is not None else {}), **kwargs)
sci(__ret[-1])
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.hlines)
def hlines(
y, xmin, xmax, colors=None, linestyles='solid', label='', *,
data=None, **kwargs):
return gca().hlines(
y, xmin, xmax, colors=colors, linestyles=linestyles,
label=label, **({"data": data} if data is not None else {}),
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.imshow)
def imshow(
X, cmap=None, norm=None, aspect=None, interpolation=None,
alpha=None, vmin=None, vmax=None, origin=None, extent=None, *,
interpolation_stage=None, filternorm=True, filterrad=4.0,
resample=None, url=None, data=None, **kwargs):
__ret = gca().imshow(
X, cmap=cmap, norm=norm, aspect=aspect,
interpolation=interpolation, alpha=alpha, vmin=vmin,
vmax=vmax, origin=origin, extent=extent,
interpolation_stage=interpolation_stage,
filternorm=filternorm, filterrad=filterrad, resample=resample,
url=url, **({"data": data} if data is not None else {}),
**kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.legend)
def legend(*args, **kwargs):
return gca().legend(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.locator_params)
def locator_params(axis='both', tight=None, **kwargs):
return gca().locator_params(axis=axis, tight=tight, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.loglog)
def loglog(*args, **kwargs):
return gca().loglog(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.magnitude_spectrum)
def magnitude_spectrum(
x, Fs=None, Fc=None, window=None, pad_to=None, sides=None,
scale=None, *, data=None, **kwargs):
return gca().magnitude_spectrum(
x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
scale=scale, **({"data": data} if data is not None else {}),
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.margins)
def margins(*margins, x=None, y=None, tight=True):
return gca().margins(*margins, x=x, y=y, tight=tight)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.minorticks_off)
def minorticks_off():
return gca().minorticks_off()
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.minorticks_on)
def minorticks_on():
return gca().minorticks_on()
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.pcolor)
def pcolor(
*args, shading=None, alpha=None, norm=None, cmap=None,
vmin=None, vmax=None, data=None, **kwargs):
__ret = gca().pcolor(
*args, shading=shading, alpha=alpha, norm=norm, cmap=cmap,
vmin=vmin, vmax=vmax,
**({"data": data} if data is not None else {}), **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.pcolormesh)
def pcolormesh(
*args, alpha=None, norm=None, cmap=None, vmin=None,
vmax=None, shading=None, antialiased=False, data=None,
**kwargs):
__ret = gca().pcolormesh(
*args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
vmax=vmax, shading=shading, antialiased=antialiased,
**({"data": data} if data is not None else {}), **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.phase_spectrum)
def phase_spectrum(
x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
data=None, **kwargs):
return gca().phase_spectrum(
x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.pie)
def pie(
x, explode=None, labels=None, colors=None, autopct=None,
pctdistance=0.6, shadow=False, labeldistance=1.1,
startangle=0, radius=1, counterclock=True, wedgeprops=None,
textprops=None, center=(0, 0), frame=False,
rotatelabels=False, *, normalize=True, data=None):
return gca().pie(
x, explode=explode, labels=labels, colors=colors,
autopct=autopct, pctdistance=pctdistance, shadow=shadow,
labeldistance=labeldistance, startangle=startangle,
radius=radius, counterclock=counterclock,
wedgeprops=wedgeprops, textprops=textprops, center=center,
frame=frame, rotatelabels=rotatelabels, normalize=normalize,
**({"data": data} if data is not None else {}))
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.plot)
def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
return gca().plot(
*args, scalex=scalex, scaley=scaley,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.plot_date)
def plot_date(
x, y, fmt='o', tz=None, xdate=True, ydate=False, *,
data=None, **kwargs):
return gca().plot_date(
x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.psd)
def psd(
x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
return_line=None, *, data=None, **kwargs):
return gca().psd(
x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
noverlap=noverlap, pad_to=pad_to, sides=sides,
scale_by_freq=scale_by_freq, return_line=return_line,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.quiver)
def quiver(*args, data=None, **kwargs):
__ret = gca().quiver(
*args, **({"data": data} if data is not None else {}),
**kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.quiverkey)
def quiverkey(Q, X, Y, U, label, **kwargs):
return gca().quiverkey(Q, X, Y, U, label, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.scatter)
def scatter(
x, y, s=None, c=None, marker=None, cmap=None, norm=None,
vmin=None, vmax=None, alpha=None, linewidths=None, *,
edgecolors=None, plotnonfinite=False, data=None, **kwargs):
__ret = gca().scatter(
x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
edgecolors=edgecolors, plotnonfinite=plotnonfinite,
**({"data": data} if data is not None else {}), **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.semilogx)
def semilogx(*args, **kwargs):
return gca().semilogx(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.semilogy)
def semilogy(*args, **kwargs):
return gca().semilogy(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.specgram)
def specgram(
x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
noverlap=None, cmap=None, xextent=None, pad_to=None,
sides=None, scale_by_freq=None, mode=None, scale=None,
vmin=None, vmax=None, *, data=None, **kwargs):
__ret = gca().specgram(
x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
noverlap=noverlap, cmap=cmap, xextent=xextent, pad_to=pad_to,
sides=sides, scale_by_freq=scale_by_freq, mode=mode,
scale=scale, vmin=vmin, vmax=vmax,
**({"data": data} if data is not None else {}), **kwargs)
sci(__ret[-1])
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.spy)
def spy(
Z, precision=0, marker=None, markersize=None, aspect='equal',
origin='upper', **kwargs):
__ret = gca().spy(
Z, precision=precision, marker=marker, markersize=markersize,
aspect=aspect, origin=origin, **kwargs)
if isinstance(__ret, cm.ScalarMappable): sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.stackplot)
def stackplot(
x, *args, labels=(), colors=None, baseline='zero', data=None,
**kwargs):
return gca().stackplot(
x, *args, labels=labels, colors=colors, baseline=baseline,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.stem)
def stem(
*args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
label=None,
use_line_collection=_api.deprecation._deprecated_parameter,
orientation='vertical', data=None):
return gca().stem(
*args, linefmt=linefmt, markerfmt=markerfmt, basefmt=basefmt,
bottom=bottom, label=label,
use_line_collection=use_line_collection,
orientation=orientation,
**({"data": data} if data is not None else {}))
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.step)
def step(x, y, *args, where='pre', data=None, **kwargs):
return gca().step(
x, y, *args, where=where,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.streamplot)
def streamplot(
x, y, u, v, density=1, linewidth=None, color=None, cmap=None,
norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1,
transform=None, zorder=None, start_points=None, maxlength=4.0,
integration_direction='both', broken_streamlines=True, *,
data=None):
__ret = gca().streamplot(
x, y, u, v, density=density, linewidth=linewidth, color=color,
cmap=cmap, norm=norm, arrowsize=arrowsize,
arrowstyle=arrowstyle, minlength=minlength,
transform=transform, zorder=zorder, start_points=start_points,
maxlength=maxlength,
integration_direction=integration_direction,
broken_streamlines=broken_streamlines,
**({"data": data} if data is not None else {}))
sci(__ret.lines)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.table)
def table(
cellText=None, cellColours=None, cellLoc='right',
colWidths=None, rowLabels=None, rowColours=None,
rowLoc='left', colLabels=None, colColours=None,
colLoc='center', loc='bottom', bbox=None, edges='closed',
**kwargs):
return gca().table(
cellText=cellText, cellColours=cellColours, cellLoc=cellLoc,
colWidths=colWidths, rowLabels=rowLabels,
rowColours=rowColours, rowLoc=rowLoc, colLabels=colLabels,
colColours=colColours, colLoc=colLoc, loc=loc, bbox=bbox,
edges=edges, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.text)
def text(x, y, s, fontdict=None, **kwargs):
return gca().text(x, y, s, fontdict=fontdict, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.tick_params)
def tick_params(axis='both', **kwargs):
return gca().tick_params(axis=axis, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.ticklabel_format)
def ticklabel_format(
*, axis='both', style='', scilimits=None, useOffset=None,
useLocale=None, useMathText=None):
return gca().ticklabel_format(
axis=axis, style=style, scilimits=scilimits,
useOffset=useOffset, useLocale=useLocale,
useMathText=useMathText)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.tricontour)
def tricontour(*args, **kwargs):
__ret = gca().tricontour(*args, **kwargs)
if __ret._A is not None: sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.tricontourf)
def tricontourf(*args, **kwargs):
__ret = gca().tricontourf(*args, **kwargs)
if __ret._A is not None: sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.tripcolor)
def tripcolor(
*args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None,
shading='flat', facecolors=None, **kwargs):
__ret = gca().tripcolor(
*args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
vmax=vmax, shading=shading, facecolors=facecolors, **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.triplot)
def triplot(*args, **kwargs):
return gca().triplot(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.violinplot)
def violinplot(
dataset, positions=None, vert=True, widths=0.5,
showmeans=False, showextrema=True, showmedians=False,
quantiles=None, points=100, bw_method=None, *, data=None):
return gca().violinplot(
dataset, positions=positions, vert=vert, widths=widths,
showmeans=showmeans, showextrema=showextrema,
showmedians=showmedians, quantiles=quantiles, points=points,
bw_method=bw_method,
**({"data": data} if data is not None else {}))
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.vlines)
def vlines(
x, ymin, ymax, colors=None, linestyles='solid', label='', *,
data=None, **kwargs):
return gca().vlines(
x, ymin, ymax, colors=colors, linestyles=linestyles,
label=label, **({"data": data} if data is not None else {}),
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.xcorr)
def xcorr(
x, y, normed=True, detrend=mlab.detrend_none, usevlines=True,
maxlags=10, *, data=None, **kwargs):
return gca().xcorr(
x, y, normed=normed, detrend=detrend, usevlines=usevlines,
maxlags=maxlags,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes._sci)
def sci(im):
return gca()._sci(im)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.set_title)
def title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs):
return gca().set_title(
label, fontdict=fontdict, loc=loc, pad=pad, y=y, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.set_xlabel)
def xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):
return gca().set_xlabel(
xlabel, fontdict=fontdict, labelpad=labelpad, loc=loc,
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.set_ylabel)
def ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):
return gca().set_ylabel(
ylabel, fontdict=fontdict, labelpad=labelpad, loc=loc,
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.set_xscale)
def xscale(value, **kwargs):
return gca().set_xscale(value, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Axes.set_yscale)
def yscale(value, **kwargs):
return gca().set_yscale(value, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def autumn():
"""
Set the colormap to 'autumn'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('autumn')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def bone():
"""
Set the colormap to 'bone'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('bone')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def cool():
"""
Set the colormap to 'cool'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('cool')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def copper():
"""
Set the colormap to 'copper'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('copper')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def flag():
"""
Set the colormap to 'flag'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('flag')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def gray():
"""
Set the colormap to 'gray'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('gray')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def hot():
"""
Set the colormap to 'hot'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('hot')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def hsv():
"""
Set the colormap to 'hsv'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('hsv')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def jet():
"""
Set the colormap to 'jet'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('jet')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def pink():
"""
Set the colormap to 'pink'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('pink')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def prism():
"""
Set the colormap to 'prism'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('prism')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def spring():
"""
Set the colormap to 'spring'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('spring')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def summer():
"""
Set the colormap to 'summer'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('summer')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def winter():
"""
Set the colormap to 'winter'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('winter')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def magma():
"""
Set the colormap to 'magma'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('magma')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def inferno():
"""
Set the colormap to 'inferno'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('inferno')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def plasma():
"""
Set the colormap to 'plasma'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('plasma')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def viridis():
"""
Set the colormap to 'viridis'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('viridis')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def nipy_spectral():
"""
Set the colormap to 'nipy_spectral'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap('nipy_spectral')