# 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
a MATLAB-like way of plotting.

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 object-oriented API is recommended for more complex plots.
"""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import six

import sys
import time
import warnings

from cycler import cycler
import matplotlib
import matplotlib.colorbar
from matplotlib import style
from matplotlib import _pylab_helpers, interactive
from matplotlib.cbook import dedent, silent_list, is_numlike
from matplotlib.cbook import _string_to_bool
from matplotlib.cbook import deprecated, warn_deprecated
from matplotlib import docstring
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.figure import Figure, figaspect
from matplotlib.gridspec import GridSpec
from matplotlib.image import imread as _imread
from matplotlib.image import imsave as _imsave
from matplotlib import rcParams, rcParamsDefault, get_backend
from matplotlib import rc_context
from matplotlib.rcsetup import interactive_bk as _interactive_bk
from matplotlib.artist import getp, get, Artist
from matplotlib.artist import setp as _setp
from matplotlib.axes import Axes, Subplot
from matplotlib.projections import PolarAxes
from matplotlib import mlab  # for csv2rec, detrend_none, window_hanning
from matplotlib.scale import get_scale_docs, get_scale_names

from matplotlib import cm
from matplotlib.cm import get_cmap, register_cmap

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 SubplotTool, 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
from matplotlib.backends import pylab_setup

## Backend detection ##
def _backend_selection():
    """ If rcParams['backend_fallback'] is true, check to see if the
        current backend is compatible with the current running event
        loop, and if not switches to a compatible one.
    """
    backend = rcParams['backend']
    if not rcParams['backend_fallback'] or backend not in _interactive_bk:
        return
    is_agg_backend = rcParams['backend'].endswith('Agg')
    if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'):
        import wx
        if wx.App.IsMainLoopRunning():
            rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend
    elif 'PyQt4.QtCore' in sys.modules and not backend == 'Qt4Agg':
        import PyQt4.QtGui
        if not PyQt4.QtGui.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt4Agg'
    elif 'PyQt5.QtCore' in sys.modules and not backend == 'Qt5Agg':
        import PyQt5.QtWidgets
        if not PyQt5.QtWidgets.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt5Agg'
    elif ('gtk' in sys.modules and
          backend not in ('GTK', 'GTKAgg', 'GTKCairo')):
        if 'gi' in sys.modules:
            from gi.repository import GObject
            ml = GObject.MainLoop
        else:
            import gobject
            ml = gobject.MainLoop
        if ml().is_running():
            rcParams['backend'] = 'gtk' + 'Agg' * is_agg_backend
    elif 'Tkinter' in sys.modules and not backend == 'TkAgg':
        # import Tkinter
        pass  # what if anything do we need to do for tkinter?

_backend_selection()

## Global ##

_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

_IP_REGISTERED = None
_INSTALL_FIG_OBSERVER = False


def install_repl_displayhook():
    """
    Install a repl display hook so that any stale figure are automatically
    redrawn when control is returned to the repl.

    This works with IPython terminals and kernels,
    as well as vanilla python shells.
    """
    global _IP_REGISTERED
    global _INSTALL_FIG_OBSERVER

    class _NotIPython(Exception):
        pass

    # see if we have IPython hooks around, if use them

    try:
        if 'IPython' in sys.modules:
            from IPython import get_ipython
            ip = get_ipython()
            if ip is None:
                raise _NotIPython()

            if _IP_REGISTERED:
                return

            def post_execute():
                if matplotlib.is_interactive():
                    draw_all()

            # IPython >= 2
            try:
                ip.events.register('post_execute', post_execute)
            except AttributeError:
                # IPython 1.x
                ip.register_post_execute(post_execute)

            _IP_REGISTERED = post_execute
            _INSTALL_FIG_OBSERVER = False

            # trigger IPython's eventloop integration, if available
            from IPython.core.pylabtools import backend2gui

            ipython_gui_name = backend2gui.get(get_backend())
            if ipython_gui_name:
                ip.enable_gui(ipython_gui_name)
        else:
            _INSTALL_FIG_OBSERVER = True

    # import failed or ipython is not running
    except (ImportError, _NotIPython):
        _INSTALL_FIG_OBSERVER = True


def uninstall_repl_displayhook():
    """
    Uninstalls the matplotlib display hook.

    .. warning

       Need IPython >= 2 for this to work.  For IPython < 2 will raise a
       ``NotImplementedError``

    .. warning

       If you are using vanilla python and have installed another
       display hook this will reset ``sys.displayhook`` to what ever
       function was there when matplotlib installed it's displayhook,
       possibly discarding your changes.
    """
    global _IP_REGISTERED
    global _INSTALL_FIG_OBSERVER
    if _IP_REGISTERED:
        from IPython import get_ipython
        ip = get_ipython()
        try:
            ip.events.unregister('post_execute', _IP_REGISTERED)
        except AttributeError:
            raise NotImplementedError("Can not unregister events "
                                      "in IPython < 2.0")
        _IP_REGISTERED = None

    if _INSTALL_FIG_OBSERVER:
        _INSTALL_FIG_OBSERVER = False


draw_all = _pylab_helpers.Gcf.draw_all


@docstring.copy_dedent(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 switch_backend(newbackend):
    """
    Switch the default backend.  This feature is **experimental**, and
    is only expected to work switching to an image backend.  e.g., if
    you have a bunch of PostScript scripts that you want to run from
    an interactive ipython session, you may want to switch to the PS
    backend before running them to avoid having a bunch of GUI windows
    popup.  If you try to interactively switch from one GUI backend to
    another, you will explode.

    Calling this command will close all open windows.
    """
    close('all')
    global _backend_mod, new_figure_manager, draw_if_interactive, _show
    matplotlib.use(newbackend, warn=False, force=True)
    from matplotlib.backends import pylab_setup
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()


def show(*args, **kw):
    """
    Display a figure.
    When running in ipython with its pylab mode, display all
    figures and return to the ipython prompt.

    In non-interactive mode, display all figures and block until
    the figures have been closed; in interactive mode it has no
    effect unless figures were created prior to a change from
    non-interactive to interactive mode (not recommended).  In
    that case it displays the figures but does not block.

    A single experimental keyword argument, *block*, may be
    set to True or False to override the blocking behavior
    described above.
    """
    global _show
    return _show(*args, **kw)


def isinteractive():
    """
    Return status of interactive mode.
    """
    return matplotlib.is_interactive()


def ioff():
    """Turn interactive mode off."""
    matplotlib.interactive(False)
    uninstall_repl_displayhook()


def ion():
    """Turn interactive mode on."""
    matplotlib.interactive(True)
    install_repl_displayhook()


def pause(interval):
    """
    Pause 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, see
    :mod:`matplotlib.animation`.

    Notes
    -----
    This function is experimental; its behavior may be changed or extended in a
    future release.
    """
    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)


@docstring.copy_dedent(matplotlib.rc)
def rc(*args, **kwargs):
    matplotlib.rc(*args, **kwargs)


@docstring.copy_dedent(matplotlib.rc_context)
def rc_context(rc=None, fname=None):
    return matplotlib.rc_context(rc, fname)


@docstring.copy_dedent(matplotlib.rcdefaults)
def rcdefaults():
    matplotlib.rcdefaults()
    if matplotlib.is_interactive():
        draw_all()


# The current "image" (ScalarMappable) is retrieved or set
# only via the pyplot interface using the following two
# functions:
def gci():
    """
    Get the current colorable artist.  Specifically, returns the
    current :class:`~matplotlib.cm.ScalarMappable` instance (image or
    patch collection), or *None* if no images or patch collections
    have been defined.  The commands :func:`~matplotlib.pyplot.imshow`
    and :func:`~matplotlib.pyplot.figimage` create
    :class:`~matplotlib.image.Image` instances, and the commands
    :func:`~matplotlib.pyplot.pcolor` and
    :func:`~matplotlib.pyplot.scatter` create
    :class:`~matplotlib.collections.Collection` instances.  The
    current image is an attribute of the current axes, or the nearest
    earlier axes in the current figure that contains an image.
    """
    return gcf()._gci()


def sci(im):
    """
    Set the current image.  This image will be the target of colormap
    commands like :func:`~matplotlib.pyplot.jet`,
    :func:`~matplotlib.pyplot.hot` or
    :func:`~matplotlib.pyplot.clim`).  The current image is an
    attribute of the current axes.
    """
    gca()._sci(im)


## Any Artist ##
# (getp is simply imported)
@docstring.copy(_setp)
def setp(*args, **kwargs):
    return _setp(*args, **kwargs)


def xkcd(scale=1, length=100, randomness=2):
    """
    Turns 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()
    """
    if rcParams['text.usetex']:
        raise RuntimeError(
            "xkcd mode is not compatible with text.usetex = True")

    from matplotlib import patheffects
    xkcd_ctx = rc_context({
        'font.family': ['xkcd', 'Humor Sans', '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,
    })
    xkcd_ctx.__enter__()

    # In order to make the call to `xkcd` that does not use a context manager
    # (cm) work, we need to enter into the cm ourselves, and return a dummy
    # cm that does nothing on entry and cleans up the xkcd context on exit.
    # Additionally, we need to keep a reference to the dummy cm because it
    # would otherwise be exited when GC'd.

    class dummy_ctx(object):
        def __enter__(self):
            pass

        __exit__ = xkcd_ctx.__exit__

    return dummy_ctx()


## Figures ##

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
           ):
    """
    Creates a new figure.

    Parameters
    ----------

    num : integer or string, optional, default: none
        If not provided, a new figure will be created, and the figure number
        will be incremented. The figure objects holds this number in a `number`
        attribute.
        If num is provided, and a figure with this id already exists, make
        it active, and returns a reference to it. If this figure does not
        exists, create it and returns it.
        If num is a string, the window title will be set to this figure's
        `num`.

    figsize : tuple of integers, optional, default: None
        width, height in inches. If not provided, defaults to rc
        figure.figsize.

    dpi : integer, optional, default: None
        resolution of the figure. If not provided, defaults to rc figure.dpi.

    facecolor :
        the background color. If not provided, defaults to rc figure.facecolor.

    edgecolor :
        the border color. If not provided, defaults to rc figure.edgecolor.

    frameon : bool, optional, default: True
        If False, suppress drawing the figure frame.

    FigureClass : class derived from matplotlib.figure.Figure
        Optionally use a custom Figure instance.

    clear : bool, optional, default: False
        If True and the figure already exists, then it is cleared.

    Returns
    -------
    figure : Figure
        The Figure instance returned will also be passed to new_figure_manager
        in the backends, which allows to hook custom Figure classes into the
        pylab interface. Additional kwargs will be passed to the figure init
        function.

    Notes
    -----
    If you are creating many figures, make sure you explicitly call "close"
    on the figures you are not using, because this will enable pylab
    to properly clean up the memory.

    rcParams defines the default values, which can be modified in the
    matplotlibrc file

    """

    if figsize is None:
        figsize = rcParams['figure.figsize']
    if dpi is None:
        dpi = rcParams['figure.dpi']
    if facecolor is None:
        facecolor = rcParams['figure.facecolor']
    if edgecolor is None:
        edgecolor = rcParams['figure.edgecolor']

    allnums = get_fignums()
    next_num = max(allnums) + 1 if allnums else 1
    figLabel = ''
    if num is None:
        num = next_num
    elif isinstance(num, six.string_types):
        figLabel = num
        allLabels = get_figlabels()
        if figLabel not in allLabels:
            if figLabel == 'all':
                warnings.warn("close('all') closes all existing figures")
            num = next_num
        else:
            inum = allLabels.index(figLabel)
            num = allnums[inum]
    else:
        num = int(num)  # crude validation of num argument

    figManager = _pylab_helpers.Gcf.get_fig_manager(num)
    if figManager is None:
        max_open_warning = rcParams['figure.max_open_warning']

        if (max_open_warning >= 1 and len(allnums) >= max_open_warning):
            warnings.warn(
                "More than %d figures have been opened. Figures "
                "created through the pyplot interface "
                "(`matplotlib.pyplot.figure`) are retained until "
                "explicitly closed and may consume too much memory. "
                "(To control this warning, see the rcParam "
                "`figure.max_open_warning`)." %
                max_open_warning, RuntimeWarning)

        if get_backend().lower() == 'ps':
            dpi = 72

        figManager = new_figure_manager(num, figsize=figsize,
                                        dpi=dpi,
                                        facecolor=facecolor,
                                        edgecolor=edgecolor,
                                        frameon=frameon,
                                        FigureClass=FigureClass,
                                        **kwargs)

        if figLabel:
            figManager.set_window_title(figLabel)
            figManager.canvas.figure.set_label(figLabel)

        # make this figure current on button press event
        def make_active(event):
            _pylab_helpers.Gcf.set_active(figManager)

        cid = figManager.canvas.mpl_connect('button_press_event', make_active)
        figManager._cidgcf = cid

        _pylab_helpers.Gcf.set_active(figManager)
        fig = figManager.canvas.figure
        fig.number = num

        # 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.
        if matplotlib.is_interactive():
            draw_if_interactive()

        if _INSTALL_FIG_OBSERVER:
            fig.stale_callback = _auto_draw_if_interactive

    if clear:
        figManager.canvas.figure.clear()

    return figManager.canvas.figure


def _auto_draw_if_interactive(fig, val):
    """
    This is 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():
        fig.canvas.draw_idle()


def gcf():
    """Get a reference to the current figure."""
    figManager = _pylab_helpers.Gcf.get_active()
    if figManager is not None:
        return figManager.canvas.figure
    else:
        return figure()


def fignum_exists(num):
    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."""
    figManagers = _pylab_helpers.Gcf.get_all_fig_managers()
    figManagers.sort(key=lambda m: m.num)
    return [m.canvas.figure.get_label() for m in figManagers]


def get_current_fig_manager():
    figManager = _pylab_helpers.Gcf.get_active()
    if figManager is None:
        gcf()  # creates an active figure as a side effect
        figManager = _pylab_helpers.Gcf.get_active()
    return figManager


@docstring.copy_dedent(FigureCanvasBase.mpl_connect)
def connect(s, func):
    return get_current_fig_manager().canvas.mpl_connect(s, func)


@docstring.copy_dedent(FigureCanvasBase.mpl_disconnect)
def disconnect(cid):
    return get_current_fig_manager().canvas.mpl_disconnect(cid)


def close(*args):
    """
    Close a figure window.

    ``close()`` by itself closes the current figure

    ``close(fig)`` closes the `.Figure` instance *fig*

    ``close(num)`` closes the figure number *num*

    ``close(name)`` where *name* is a string, closes figure with that label

    ``close('all')`` closes all the figure windows
    """

    if len(args) == 0:
        figManager = _pylab_helpers.Gcf.get_active()
        if figManager is None:
            return
        else:
            _pylab_helpers.Gcf.destroy(figManager.num)
    elif len(args) == 1:
        arg = args[0]
        if arg == 'all':
            _pylab_helpers.Gcf.destroy_all()
        elif isinstance(arg, six.integer_types):
            _pylab_helpers.Gcf.destroy(arg)
        elif hasattr(arg, 'int'):
            # if we are dealing with a type UUID, we
            # can use its integer representation
            _pylab_helpers.Gcf.destroy(arg.int)
        elif isinstance(arg, six.string_types):
            allLabels = get_figlabels()
            if arg in allLabels:
                num = get_fignums()[allLabels.index(arg)]
                _pylab_helpers.Gcf.destroy(num)
        elif isinstance(arg, Figure):
            _pylab_helpers.Gcf.destroy_fig(arg)
        else:
            raise TypeError('Unrecognized argument type %s to close' % type(arg))
    else:
        raise TypeError('close takes 0 or 1 arguments')


def clf():
    """
    Clear the current figure.
    """
    gcf().clf()


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 (:func:`.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.

    A more object-oriented alternative, given any
    :class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
    was created using a :mod:`~matplotlib.pyplot` function, is::

        fig.canvas.draw_idle()
    """
    get_current_fig_manager().canvas.draw_idle()


@docstring.copy_dedent(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


@docstring.copy_dedent(Figure.ginput)
def ginput(*args, **kwargs):
    """
    Blocking call to interact with the figure.

    This will wait for *n* clicks from the user and return a list of the
    coordinates of each click.

    If *timeout* is negative, does not timeout.
    """
    return gcf().ginput(*args, **kwargs)


@docstring.copy_dedent(Figure.waitforbuttonpress)
def waitforbuttonpress(*args, **kwargs):
    """
    Blocking call to interact with the figure.

    This will wait for *n* key or mouse clicks from the user and
    return a list containing True's for keyboard clicks and False's
    for mouse clicks.

    If *timeout* is negative, does not timeout.
    """
    return gcf().waitforbuttonpress(*args, **kwargs)


# Putting things in figures

@docstring.copy_dedent(Figure.text)
def figtext(*args, **kwargs):
    return gcf().text(*args, **kwargs)


@docstring.copy_dedent(Figure.suptitle)
def suptitle(*args, **kwargs):
    return gcf().suptitle(*args, **kwargs)


@docstring.copy_dedent(Figure.figimage)
def figimage(*args, **kwargs):
    return gcf().figimage(*args, **kwargs)


def figlegend(*args, **kwargs):
    """
    Place a legend in the figure.

    *labels*
      a sequence of strings

    *handles*
      a sequence of :class:`~matplotlib.lines.Line2D` or
      :class:`~matplotlib.patches.Patch` instances

    *loc*
      can be a string or an integer specifying the legend
      location

    A :class:`matplotlib.legend.Legend` instance is returned.

    Examples
    --------

    To make a legend from existing artists on every axes::

      figlegend()

    To make a legend for a list of lines and labels::

      figlegend( (line1, line2, line3),
                 ('label1', 'label2', 'label3'),
                 'upper right' )

    .. seealso::

       :func:`~matplotlib.pyplot.legend`

    """
    return gcf().legend(*args, **kwargs)


## Figure and Axes hybrid ##

_hold_msg = """pyplot.hold is deprecated.
    Future behavior will be consistent with the long-time default:
    plot commands add elements without first clearing the
    Axes and/or Figure."""

@deprecated("2.0", message=_hold_msg)
def hold(b=None):
    """
    Set the hold state.  If *b* is None (default), toggle the
    hold state, else set the hold state to boolean value *b*::

      hold()      # toggle hold
      hold(True)  # hold is on
      hold(False) # hold is off

    When *hold* is *True*, subsequent plot commands will add elements to
    the current axes.  When *hold* is *False*, the current axes and
    figure will be cleared on the next plot command.

    """

    fig = gcf()
    ax = fig.gca()

    if b is not None:
        b = bool(b)
    fig._hold = b
    ax._hold = b

    # b=None toggles the hold state, so let's get get the current hold
    # state; but should pyplot hold toggle the rc setting - me thinks
    # not
    b = ax._hold

    # The comment above looks ancient; and probably the line below,
    # contrary to the comment, is equally ancient.  It will trigger
    # a second warning, but "Oh, well...".
    rc('axes', hold=b)

@deprecated("2.0", message=_hold_msg)
def ishold():
    """
    Return the hold status of the current axes.
    """
    return gca()._hold


@deprecated("2.0", message=_hold_msg)
def over(func, *args, **kwargs):
    """
    Call a function with hold(True).

    Calls::

      func(*args, **kwargs)

    with ``hold(True)`` and then restores the hold state.

    """
    ax = gca()
    h = ax._hold
    ax._hold = True
    func(*args, **kwargs)
    ax._hold = h

## Axes ##


def axes(arg=None, **kwargs):
    """
    Add an axes to the current figure and make it the current axes.

    Parameters
    ----------
    arg : None or 4-tuple or Axes
        The exact behavior of this function depends on the type:

        - *None*: A new full window axes is added using
          ``subplot(111, **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.
        - `.Axes`: This is equivalent to `.pyplot.sca`. It sets the current
          axes to *arg*. Note: This implicitly changes the current figure to
          the parent of *arg*.

          .. note:: The use of an Axes as an argument is deprecated and will be
                    removed in v3.0. Please use `.pyplot.sca` instead.

    Other Parameters
    ----------------
    **kwargs :
        For allowed keyword arguments see `.pyplot.subplot` and
        `.Figure.add_axes` respectively. Some common keyword arguments are
        listed below:

        ========= =========== =================================================
        kwarg     Accepts     Description
        ========= =========== =================================================
        facecolor color       the axes background color
        frameon   bool        whether to display the frame
        sharex    otherax     share x-axis with *otherax*
        sharey    otherax     share y-axis with *otherax*
        polar     bool        whether to use polar axes
        aspect    [str | num] ['equal', 'auto'] or a number.  If a number, the
                              ratio of y-unit/x-unit in screen-space.  See also
                              `~.Axes.set_aspect`.
        ========= =========== =================================================

    Returns
    -------
    axes : Axes
        The created or activated axes.

    Examples
    --------
    Creating a new full window axes::

        >>> plt.axes()

    Creating a new axes with specified dimensions and some kwargs::

        >>> plt.axes((left, bottom, width, height), facecolor='w')

    """

    if arg is None:
        return subplot(111, **kwargs)

    if isinstance(arg, Axes):
        warn_deprecated("2.2",
                        message="Using pyplot.axes(ax) with ax an Axes "
                                "argument is deprecated. Please use "
                                "pyplot.sca(ax) instead.")
        ax = arg
        sca(ax)
        return ax
    else:
        rect = arg
        return gcf().add_axes(rect, **kwargs)


def delaxes(ax=None):
    """
    Remove the given `Axes` *ax* from the current figure. If *ax* is *None*,
    the current axes is removed. A KeyError is raised if the axes doesn't exist.
    """
    if ax is None:
        ax = gca()
    gcf().delaxes(ax)


def sca(ax):
    """
    Set the current Axes instance to *ax*.

    The current Figure is updated to the parent of *ax*.
    """
    managers = _pylab_helpers.Gcf.get_all_fig_managers()
    for m in managers:
        if ax in m.canvas.figure.axes:
            _pylab_helpers.Gcf.set_active(m)
            m.canvas.figure.sca(ax)
            return
    raise ValueError("Axes instance argument was not found in a figure.")


def gca(**kwargs):
    """
    Get the current :class:`~matplotlib.axes.Axes` instance on the
    current figure matching the given keyword args, or create one.

    Examples
    --------
    To get the current polar axes on the current figure::

        plt.gca(projection='polar')

    If the current axes doesn't exist, or isn't a polar one, the appropriate
    axes will be created and then returned.

    See Also
    --------
    matplotlib.figure.Figure.gca : The figure's gca method.
    """
    return gcf().gca(**kwargs)

# More ways of creating axes:


def subplot(*args, **kwargs):
    """
    Return a subplot axes at the given grid position.

    Call signature::

       subplot(nrows, ncols, index, **kwargs)

    In the current figure, create and return an `.Axes`, at position *index*
    of a (virtual) grid of *nrows* by *ncols* axes.  Indexes go from 1 to
    ``nrows * ncols``, incrementing in row-major order.

    If *nrows*, *ncols* and *index* are all less than 10, they can also be
    given as a single, concatenated, three-digit number.

    For example, ``subplot(2, 3, 3)`` and ``subplot(233)`` both create an
    `.Axes` at the top right corner of the current figure, occupying half of
    the figure height and a third of the figure width.

    .. note::

       Creating a subplot will delete any pre-existing subplot 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)
          plt.plot(range(12))
          plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background

       If you do not want this behavior, use the
       :meth:`~matplotlib.figure.Figure.add_subplot` method or the
       :func:`~matplotlib.pyplot.axes` function instead.

    Keyword arguments:

      *facecolor*:
        The background color of the subplot, which can be any valid
        color specifier.  See :mod:`matplotlib.colors` for more
        information.

      *polar*:
        A boolean flag indicating whether the subplot plot should be
        a polar projection.  Defaults to *False*.

      *projection*:
        A string giving the name of a custom projection to be used
        for the subplot. This projection must have been previously
        registered. See :mod:`matplotlib.projections`.

    .. seealso::

        :func:`~matplotlib.pyplot.axes`
            For additional information on :func:`axes` and
            :func:`subplot` keyword arguments.

        :file:`gallery/pie_and_polar_charts/polar_scatter.py`
            For an example

    **Example:**

    .. plot:: gallery/subplots_axes_and_figures/subplot.py

    """
    # 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) :
        warnings.warn("The subplot index argument to subplot() appears"
                      " to be a boolean. Did you intend to use subplots()?")

    fig = gcf()
    a = fig.add_subplot(*args, **kwargs)
    bbox = a.bbox
    byebye = []
    for other in fig.axes:
        if other==a: continue
        if bbox.fully_overlaps(other.bbox):
            byebye.append(other)
    for ax in byebye: delaxes(ax)

    return a


def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
             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, optional, 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 visible.  Similarly, when subplots
        have a shared y-axis along a row, only the y tick labels of the first
        column subplot are visible.

    squeeze : bool, optional, default: True
        - If True, extra dimensions are squeezed out from the returned Axes
          object:

            - if only one subplot is constructed (nrows=ncols=1), the
              resulting single Axes object is returned as a scalar.
            - for Nx1 or 1xN subplots, the returned object is a 1D numpy
              object array of Axes objects are returned as numpy 1D arrays.
            - for NxM, subplots with N>1 and M>1 are returned as a 2D arrays.

        - 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.

    subplot_kw : dict, optional
        Dict with keywords passed to the
        :meth:`~matplotlib.figure.Figure.add_subplot` call used to create each
        subplot.

    gridspec_kw : dict, optional
        Dict with keywords passed to the
        :class:`~matplotlib.gridspec.GridSpec` constructor used to create the
        grid the subplots are placed on.

    **fig_kw :
        All additional keyword arguments are passed to the :func:`figure` call.

    Returns
    -------
    fig : :class:`matplotlib.figure.Figure` object

    ax : Axes object or array of Axes objects.

        ax can be either a single :class:`matplotlib.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.

    Examples
    --------
    First create some toy data:

    >>> x = np.linspace(0, 2*np.pi, 400)
    >>> y = np.sin(x**2)

    Creates just a figure and only one subplot

    >>> fig, ax = plt.subplots()
    >>> ax.plot(x, y)
    >>> ax.set_title('Simple plot')

    Creates two subplots and unpacks 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)

    Creates four polar axes, and accesses them through the returned array

    >>> fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))
    >>> axes[0, 0].plot(x, y)
    >>> axes[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)

    See Also
    --------
    figure
    subplot
    """
    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)
    return fig, axs


def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):
    """
    Create an axis at specific location inside a regular grid.

    Parameters
    ----------
    shape : sequence of 2 ints
        Shape of grid in which to place axis.
        First entry is number of rows, second entry is number of columns.

    loc : sequence of 2 ints
        Location to place axis within grid.
        First entry is row number, second entry is column number.

    rowspan : int
        Number of rows for the axis to span to the right.

    colspan : int
        Number of columns for the axis to span downwards.

    fig : `Figure`, optional
        Figure to place axis in. Defaults to current figure.

    **kwargs
        Additional keyword arguments are handed to `add_subplot`.


    Notes
    -----
    The following call ::

        subplot2grid(shape, loc, rowspan=1, colspan=1)

    is identical to ::

        gridspec=GridSpec(shape[0], shape[1])
        subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan)
        subplot(subplotspec)
    """

    if fig is None:
        fig = gcf()

    s1, s2 = shape
    subplotspec = GridSpec(s1, s2).new_subplotspec(loc,
                                                   rowspan=rowspan,
                                                   colspan=colspan)
    a = fig.add_subplot(subplotspec, **kwargs)
    bbox = a.bbox
    byebye = []
    for other in fig.axes:
        if other == a:
            continue
        if bbox.fully_overlaps(other.bbox):
            byebye.append(other)
    for ax in byebye:
        delaxes(ax)

    return a


def twinx(ax=None):
    """
    Make a second axes that shares the *x*-axis.  The new axes will
    overlay *ax* (or the current axes if *ax* is *None*).  The ticks
    for *ax2* will be placed on the right, and the *ax2* instance is
    returned.

    .. seealso::

       :file:`examples/api_examples/two_scales.py`
          For an example
    """
    if ax is None:
        ax=gca()
    ax1 = ax.twinx()
    return ax1


def twiny(ax=None):
    """
    Make a second axes that shares the *y*-axis.  The new axis will
    overlay *ax* (or the current axes if *ax* is *None*).  The ticks
    for *ax2* will be placed on the top, and the *ax2* instance is
    returned.
    """
    if ax is None:
        ax=gca()
    ax1 = ax.twiny()
    return ax1


def subplots_adjust(*args, **kwargs):
    """
    Tune the subplot layout.

    call signature::

      subplots_adjust(left=None, bottom=None, right=None, top=None,
                      wspace=None, hspace=None)

    The parameter meanings (and suggested defaults) are::

      left  = 0.125  # the left side of the subplots of the figure
      right = 0.9    # the right side of the subplots of the figure
      bottom = 0.1   # the bottom of the subplots of the figure
      top = 0.9      # the top of the subplots of the figure
      wspace = 0.2   # the amount of width reserved for space between subplots,
                     # expressed as a fraction of the average axis width
      hspace = 0.2   # the amount of height reserved for space between subplots,
                     # expressed as a fraction of the average axis height

    The actual defaults are controlled by the rc file
    """
    fig = gcf()
    fig.subplots_adjust(*args, **kwargs)


def subplot_tool(targetfig=None):
    """
    Launch a subplot tool window for a figure.

    A :class:`matplotlib.widgets.SubplotTool` instance is returned.
    """
    tbar = rcParams['toolbar'] # turn off the navigation toolbar for the toolfig
    rcParams['toolbar'] = 'None'
    if targetfig is None:
        manager = get_current_fig_manager()
        targetfig = manager.canvas.figure
    else:
        # find the manager for this figure
        for manager in _pylab_helpers.Gcf._activeQue:
            if manager.canvas.figure==targetfig: break
        else: raise RuntimeError('Could not find manager for targetfig')

    toolfig = figure(figsize=(6,3))
    toolfig.subplots_adjust(top=0.9)
    ret =  SubplotTool(targetfig, toolfig)
    rcParams['toolbar'] = tbar
    _pylab_helpers.Gcf.set_active(manager)  # restore the current figure
    return ret


def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None):
    """
    Automatically adjust subplot parameters to give specified padding.

    Parameters
    ----------
    pad : float
        padding between the figure edge and the edges of subplots, as a fraction of the font-size.
    h_pad, w_pad : float
        padding (height/width) between edges of adjacent subplots.
        Defaults to `pad_inches`.
    rect : if rect is given, it is interpreted as a rectangle
        (left, bottom, right, top) in the normalized figure
        coordinate that the whole subplots area (including
        labels) will fit into. Default is (0, 0, 1, 1).

    """
    fig = gcf()
    fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)


def box(on=None):
    """
    Turn the axes box on or off.

    Parameters
    ----------
    on : bool or None
        The new axes box state.  If ``None``, toggle the state.
    """
    ax = gca()
    on = _string_to_bool(on)
    if on is None:
        on = not ax.get_frame_on()
    ax.set_frame_on(on)


def title(s, *args, **kwargs):
    """
    Set a title of the current axes.

    Set one of the three available axes titles. The available titles are
    positioned above the axes in the center, flush with the left edge,
    and flush with the right edge.

    .. seealso::
        See :func:`~matplotlib.pyplot.text` for adding text
        to the current axes

    Parameters
    ----------
    label : str
        Text to use for the title

    fontdict : dict
        A dictionary controlling the appearance of the title text,
        the default `fontdict` is:

            {'fontsize': rcParams['axes.titlesize'],
            'fontweight' : rcParams['axes.titleweight'],
            'verticalalignment': 'baseline',
            'horizontalalignment': loc}

    loc : {'center', 'left', 'right'}, str, optional
        Which title to set, defaults to 'center'

    Returns
    -------
    text : :class:`~matplotlib.text.Text`
        The matplotlib text instance representing the title

    Other parameters
    ----------------
    kwargs : text properties
        Other keyword arguments are text properties, see
        :class:`~matplotlib.text.Text` for a list of valid text
        properties.

    """
    return gca().set_title(s, *args, **kwargs)

## Axis ##


def axis(*v, **kwargs):
    """
    Convenience method to get or set axis properties.

    Calling with no arguments::

      >>> axis()

    returns the current axes limits ``[xmin, xmax, ymin, ymax]``.::

      >>> axis(v)

    sets the min and max of the x and y axes, with
    ``v = [xmin, xmax, ymin, ymax]``.::

      >>> axis('off')

    turns off the axis lines and labels.::

      >>> axis('equal')

    changes limits of *x* or *y* axis so that equal increments of *x*
    and *y* have the same length; a circle is circular.::

      >>> axis('scaled')

    achieves the same result by changing the dimensions of the plot box instead
    of the axis data limits.::

      >>> axis('tight')

    changes *x* and *y* axis limits such that all data is shown. If
    all data is already shown, it will move it to the center of the
    figure without modifying (*xmax* - *xmin*) or (*ymax* -
    *ymin*). Note this is slightly different than in MATLAB.::

      >>> axis('image')

    is 'scaled' with the axis limits equal to the data limits.::

      >>> axis('auto')

    and::

      >>> axis('normal')

    are deprecated. They restore default behavior; axis limits are automatically
    scaled to make the data fit comfortably within the plot box.

    if ``len(*v)==0``, you can pass in *xmin*, *xmax*, *ymin*, *ymax*
    as kwargs selectively to alter just those limits without changing
    the others.

      >>> axis('square')

    changes the limit ranges (*xmax*-*xmin*) and (*ymax*-*ymin*) of
    the *x* and *y* axes to be the same, and have the same scaling,
    resulting in a square plot.

    The xmin, xmax, ymin, ymax tuple is returned

    .. seealso::

        :func:`xlim`, :func:`ylim`
           For setting the x- and y-limits individually.
    """
    return gca().axis(*v, **kwargs)


def xlabel(s, *args, **kwargs):
    """
    Set the *x* axis label of the current axis.

    Default override is::

      override = {
          'fontsize'            : 'small',
          'verticalalignment'   : 'top',
          'horizontalalignment' : 'center'
          }

    .. seealso::

        :func:`~matplotlib.pyplot.text`
            For information on how override and the optional args work
    """
    return gca().set_xlabel(s, *args, **kwargs)


def ylabel(s, *args, **kwargs):
    """
    Set the *y* axis label of the current axis.

    Defaults override is::

        override = {
           'fontsize'            : 'small',
           'verticalalignment'   : 'center',
           'horizontalalignment' : 'right',
           'rotation'='vertical' : }

    .. seealso::

        :func:`~matplotlib.pyplot.text`
            For information on how override and the optional args
            work.
    """
    return gca().set_ylabel(s, *args, **kwargs)


def xlim(*args, **kwargs):
    """
    Get or set the *x* limits of the current axes.

    ::

      xmin, xmax = xlim()   # return the current xlim
      xlim( (xmin, xmax) )  # set the xlim to xmin, xmax
      xlim( xmin, xmax )    # set the xlim to xmin, xmax

    If you do not specify args, you can pass the xmin and xmax as
    kwargs, e.g.::

      xlim(xmax=3) # adjust the max leaving min unchanged
      xlim(xmin=1) # adjust the min leaving max unchanged

    Setting limits turns autoscaling off for the x-axis.

    The new axis limits are returned as a length 2 tuple.

    """
    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.

    ::

      ymin, ymax = ylim()   # return the current ylim
      ylim( (ymin, ymax) )  # set the ylim to ymin, ymax
      ylim( ymin, ymax )    # set the ylim to ymin, ymax

    If you do not specify args, you can pass the *ymin* and *ymax* as
    kwargs, e.g.::

      ylim(ymax=3) # adjust the max leaving min unchanged
      ylim(ymin=1) # adjust the min leaving max unchanged

    Setting limits turns autoscaling off for the y-axis.

    The new axis limits are returned as a length 2 tuple.
    """
    ax = gca()
    if not args and not kwargs:
        return ax.get_ylim()
    ret = ax.set_ylim(*args, **kwargs)
    return ret


@docstring.dedent_interpd
def xscale(*args, **kwargs):
    """
    Set the scaling of the *x*-axis.

    call signature::

      xscale(scale, **kwargs)

    The available scales are: %(scale)s

    Different keywords may be accepted, depending on the scale:

    %(scale_docs)s
    """
    gca().set_xscale(*args, **kwargs)


@docstring.dedent_interpd
def yscale(*args, **kwargs):
    """
    Set the scaling of the *y*-axis.

    call signature::

      yscale(scale, **kwargs)

    The available scales are: %(scale)s

    Different keywords may be accepted, depending on the scale:

    %(scale_docs)s
    """
    gca().set_yscale(*args, **kwargs)


def xticks(*args, **kwargs):
    """
    Get or set the *x*-limits of the current tick locations and labels.

    ::

      # return locs, labels where locs is an array of tick locations and
      # labels is an array of tick labels.
      locs, labels = xticks()

      # set the locations of the xticks
      xticks( arange(6) )

      # set the locations and labels of the xticks
      xticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )

    The keyword args, if any, are :class:`~matplotlib.text.Text`
    properties. For example, to rotate long labels::

      xticks( arange(12), calendar.month_name[1:13], rotation=17 )
    """
    ax = gca()

    if len(args)==0:
        locs = ax.get_xticks()
        labels = ax.get_xticklabels()
    elif len(args)==1:
        locs = ax.set_xticks(args[0])
        labels = ax.get_xticklabels()
    elif len(args)==2:
        locs = ax.set_xticks(args[0])
        labels = ax.set_xticklabels(args[1], **kwargs)
    else: raise TypeError('Illegal number of arguments to xticks')
    if len(kwargs):
        for l in labels:
            l.update(kwargs)

    return locs, silent_list('Text xticklabel', labels)


def yticks(*args, **kwargs):
    """
    Get or set the *y*-limits of the current tick locations and labels.

    ::

      # return locs, labels where locs is an array of tick locations and
      # labels is an array of tick labels.
      locs, labels = yticks()

      # set the locations of the yticks
      yticks( arange(6) )

      # set the locations and labels of the yticks
      yticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )

    The keyword args, if any, are :class:`~matplotlib.text.Text`
    properties. For example, to rotate long labels::

      yticks( arange(12), calendar.month_name[1:13], rotation=45 )
    """
    ax = gca()

    if len(args)==0:
        locs = ax.get_yticks()
        labels = ax.get_yticklabels()
    elif len(args)==1:
        locs = ax.set_yticks(args[0])
        labels = ax.get_yticklabels()
    elif len(args)==2:
        locs = ax.set_yticks(args[0])
        labels = ax.set_yticklabels(args[1], **kwargs)
    else: raise TypeError('Illegal number of arguments to yticks')
    if len(kwargs):
        for l in labels:
            l.update(kwargs)


    return ( locs,
             silent_list('Text yticklabel', labels)
             )


def minorticks_on():
    """
    Display minor ticks on the current plot.

    Displaying minor ticks reduces performance; turn them off using
    minorticks_off() if drawing speed is a problem.
    """
    gca().minorticks_on()


def minorticks_off():
    """
    Remove minor ticks from the current plot.
    """
    gca().minorticks_off()


def rgrids(*args, **kwargs):
    """
    Get or set the radial gridlines on a polar plot.

    call signatures::

      lines, labels = rgrids()
      lines, labels = rgrids(radii, labels=None, angle=22.5, **kwargs)

    When called with no arguments, :func:`rgrid` simply returns the
    tuple (*lines*, *labels*), where *lines* is an array of radial
    gridlines (:class:`~matplotlib.lines.Line2D` instances) and
    *labels* is an array of tick labels
    (:class:`~matplotlib.text.Text` instances). When called with
    arguments, the labels will appear at the specified radial
    distances and angles.

    *labels*, if not *None*, is a len(*radii*) list of strings of the
    labels to use at each angle.

    If *labels* is None, the rformatter will be used

    Examples::

      # set the locations of the radial gridlines and labels
      lines, labels = rgrids( (0.25, 0.5, 1.0) )

      # set the locations and labels of the radial gridlines and labels
      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 len(args)==0:
        lines = ax.yaxis.get_gridlines()
        labels = ax.yaxis.get_ticklabels()
    else:
        lines, labels = ax.set_rgrids(*args, **kwargs)

    return ( silent_list('Line2D rgridline', lines),
             silent_list('Text rgridlabel', labels) )


def thetagrids(*args, **kwargs):
    """
    Get or set the theta locations of the gridlines in a polar plot.

    If no arguments are passed, return a tuple (*lines*, *labels*)
    where *lines* is an array of radial gridlines
    (:class:`~matplotlib.lines.Line2D` instances) and *labels* is an
    array of tick labels (:class:`~matplotlib.text.Text` instances)::

      lines, labels = thetagrids()

    Otherwise the syntax is::

      lines, labels = thetagrids(angles, labels=None, fmt='%d', frac = 1.1)

    set the angles at which to place the theta grids (these gridlines
    are equal along the theta dimension).

    *angles* is in degrees.

    *labels*, if not *None*, is a len(angles) list of strings of the
    labels to use at each angle.

    If *labels* is *None*, the labels will be ``fmt%angle``.

    *frac* is the fraction of the polar axes radius at which to place
    the label (1 is the edge). e.g., 1.05 is outside the axes and 0.95
    is inside the axes.

    Return value is a list of tuples (*lines*, *labels*):

      - *lines* are :class:`~matplotlib.lines.Line2D` instances

      - *labels* are :class:`~matplotlib.text.Text` instances.

    Note that on input, the *labels* argument is a list of strings,
    and on output it is a list of :class:`~matplotlib.text.Text`
    instances.

    Examples::

      # set the locations of the radial gridlines and labels
      lines, labels = thetagrids( range(45,360,90) )

      # set the locations and labels of the radial gridlines and labels
      lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') )
    """
    ax = gca()
    if not isinstance(ax, PolarAxes):
        raise RuntimeError('rgrids only defined for polar axes')
    if len(args)==0:
        lines = ax.xaxis.get_ticklines()
        labels = ax.xaxis.get_ticklabels()
    else:
        lines, labels = ax.set_thetagrids(*args, **kwargs)

    return (silent_list('Line2D thetagridline', lines),
            silent_list('Text thetagridlabel', labels)
            )


## Plotting Info ##

def plotting():
    pass


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.

    import inspect

    exclude = {'colormaps', 'colors', 'connect', 'disconnect',
               'get_plot_commands', 'get_current_fig_manager', 'ginput',
               'plotting', 'waitforbuttonpress'}
    exclude |= set(colormaps())
    this_module = inspect.getmodule(get_plot_commands)

    commands = set()
    for name, obj in list(six.iteritems(globals())):
        if name.startswith('_') or name in exclude:
            continue
        if inspect.isfunction(obj) and inspect.getmodule(obj) is this_module:
            commands.add(name)

    return sorted(commands)


@deprecated('2.1')
def colors():
    """
    This is a do-nothing function to provide you with help on how
    matplotlib handles colors.

    Commands which take color arguments can use several formats to
    specify the colors.  For the basic built-in colors, you can use a
    single letter

      =====   =======
      Alias   Color
      =====   =======
      'b'     blue
      'g'     green
      'r'     red
      'c'     cyan
      'm'     magenta
      'y'     yellow
      'k'     black
      'w'     white
      =====   =======

    For a greater range of colors, you have two options.  You can
    specify the color using an html hex string, as in::

      color = '#eeefff'

    or you can pass an R,G,B tuple, where each of R,G,B are in the
    range [0,1].

    You can also use any legal html name for a color, for example::

      color = 'red'
      color = 'burlywood'
      color = 'chartreuse'

    The example below creates a subplot with a dark
    slate gray background::

       subplot(111, facecolor=(0.1843, 0.3098, 0.3098))

    Here is an example that creates a pale turquoise title::

      title('Is this the best color?', color='#afeeee')

    """
    pass


def colormaps():
    """
    Matplotlib provides a number of colormaps, and others can be added using
    :func:`~matplotlib.cm.register_cmap`.  This function documents the built-in
    colormaps, and will also return a list of all registered colormaps if called.

    You can set the colormap for an image, pcolor, scatter, etc,
    using a keyword argument::

      imshow(X, cmap=cm.hot)

    or using the :func:`set_cmap` function::

      imshow(X)
      pyplot.set_cmap('hot')
      pyplot.set_cmap('jet')

    In interactive mode, :func:`set_cmap` will update the colormap post-hoc,
    allowing you to see which one works best for your data.

    All built-in colormaps can be reversed by appending ``_r``: For instance,
    ``gray_r`` is the reverse of ``gray``.

    There are several common color schemes used in visualization:

    Sequential schemes
      for unipolar data that progresses from low to high
    Diverging schemes
      for bipolar data that emphasizes positive or negative deviations from a
      central value
    Cyclic schemes
      meant for plotting values that wrap around at the
      endpoints, such as phase angle, wind direction, or time of day
    Qualitative schemes
      for nominal data that has no inherent ordering, where color is used
      only to distinguish categories

    Matplotlib ships with 4 perceptually uniform color maps which are
    the recommended color maps for sequential data:

      =========   ===================================================
      Colormap    Description
      =========   ===================================================
      inferno     perceptually uniform shades of black-red-yellow
      magma       perceptually uniform shades of black-red-white
      plasma      perceptually uniform shades of blue-red-yellow
      viridis     perceptually uniform shades of blue-green-yellow
      =========   ===================================================

    The following colormaps are based on the `ColorBrewer
    <http://colorbrewer2.org>`_ color specifications and designs developed by
    Cynthia Brewer:

    ColorBrewer Diverging (luminance is highest at the midpoint, and
    decreases towards differently-colored endpoints):

      ========  ===================================
      Colormap  Description
      ========  ===================================
      BrBG      brown, white, blue-green
      PiYG      pink, white, yellow-green
      PRGn      purple, white, green
      PuOr      orange, white, purple
      RdBu      red, white, blue
      RdGy      red, white, gray
      RdYlBu    red, yellow, blue
      RdYlGn    red, yellow, green
      Spectral  red, orange, yellow, green, blue
      ========  ===================================

    ColorBrewer Sequential (luminance decreases monotonically):

      ========  ====================================
      Colormap  Description
      ========  ====================================
      Blues     white to dark blue
      BuGn      white, light blue, dark green
      BuPu      white, light blue, dark purple
      GnBu      white, light green, dark blue
      Greens    white to dark green
      Greys     white to black (not linear)
      Oranges   white, orange, dark brown
      OrRd      white, orange, dark red
      PuBu      white, light purple, dark blue
      PuBuGn    white, light purple, dark green
      PuRd      white, light purple, dark red
      Purples   white to dark purple
      RdPu      white, pink, dark purple
      Reds      white to dark red
      YlGn      light yellow, dark green
      YlGnBu    light yellow, light green, dark blue
      YlOrBr    light yellow, orange, dark brown
      YlOrRd    light yellow, orange, dark red
      ========  ====================================

    ColorBrewer Qualitative:

    (For plotting nominal data, :class:`ListedColormap` is used,
    not :class:`LinearSegmentedColormap`.  Different sets of colors are
    recommended for different numbers of categories.)

    * Accent
    * Dark2
    * Paired
    * Pastel1
    * Pastel2
    * Set1
    * Set2
    * Set3

    A set of colormaps derived from those of the same name provided
    with Matlab are also included:

      =========   =======================================================
      Colormap    Description
      =========   =======================================================
      autumn      sequential linearly-increasing shades of red-orange-yellow
      bone        sequential increasing black-white color map with
                  a tinge of blue, to emulate X-ray film
      cool        linearly-decreasing shades of cyan-magenta
      copper      sequential increasing shades of black-copper
      flag        repetitive red-white-blue-black pattern (not cyclic at
                  endpoints)
      gray        sequential linearly-increasing black-to-white
                  grayscale
      hot         sequential black-red-yellow-white, to emulate blackbody
                  radiation from an object at increasing temperatures
      hsv         cyclic red-yellow-green-cyan-blue-magenta-red, formed
                  by changing the hue component in the HSV color space
      jet         a spectral map with dark endpoints, blue-cyan-yellow-red;
                  based on a fluid-jet simulation by NCSA [#]_
      pink        sequential increasing pastel black-pink-white, meant
                  for sepia tone colorization of photographs
      prism       repetitive red-yellow-green-blue-purple-...-green pattern
                  (not cyclic at endpoints)
      spring      linearly-increasing shades of magenta-yellow
      summer      sequential linearly-increasing shades of green-yellow
      winter      linearly-increasing shades of blue-green
      =========   =======================================================

    A set of palettes from the `Yorick scientific visualisation
    package <https://dhmunro.github.io/yorick-doc/>`_, an evolution of
    the GIST package, both by David H. Munro are included:

      ============  =======================================================
      Colormap      Description
      ============  =======================================================
      gist_earth    mapmaker's colors from dark blue deep ocean to green
                    lowlands to brown highlands to white mountains
      gist_heat     sequential increasing black-red-orange-white, to emulate
                    blackbody radiation from an iron bar as it grows hotter
      gist_ncar     pseudo-spectral black-blue-green-yellow-red-purple-white
                    colormap from National Center for Atmospheric
                    Research [#]_
      gist_rainbow  runs through the colors in spectral order from red to
                    violet at full saturation (like *hsv* but not cyclic)
      gist_stern    "Stern special" color table from Interactive Data
                    Language software
      ============  =======================================================


    Other miscellaneous schemes:

      ============= =======================================================
      Colormap      Description
      ============= =======================================================
      afmhot        sequential black-orange-yellow-white blackbody
                    spectrum, commonly used in atomic force microscopy
      brg           blue-red-green
      bwr           diverging blue-white-red
      coolwarm      diverging blue-gray-red, meant to avoid issues with 3D
                    shading, color blindness, and ordering of colors [#]_
      CMRmap        "Default colormaps on color images often reproduce to
                    confusing grayscale images. The proposed colormap
                    maintains an aesthetically pleasing color image that
                    automatically reproduces to a monotonic grayscale with
                    discrete, quantifiable saturation levels." [#]_
      cubehelix     Unlike most other color schemes cubehelix was designed
                    by D.A. Green to be monotonically increasing in terms
                    of perceived brightness. Also, when printed on a black
                    and white postscript printer, the scheme results in a
                    greyscale with monotonically increasing brightness.
                    This color scheme is named cubehelix because the r,g,b
                    values produced can be visualised as a squashed helix
                    around the diagonal in the r,g,b color cube.
      gnuplot       gnuplot's traditional pm3d scheme
                    (black-blue-red-yellow)
      gnuplot2      sequential color printable as gray
                    (black-blue-violet-yellow-white)
      ocean         green-blue-white
      rainbow       spectral purple-blue-green-yellow-orange-red colormap
                    with diverging luminance
      seismic       diverging blue-white-red
      nipy_spectral black-purple-blue-green-yellow-red-white spectrum,
                    originally from the Neuroimaging in Python project
      terrain       mapmaker's colors, blue-green-yellow-brown-white,
                    originally from IGOR Pro
      ============= =======================================================

    The following colormaps are redundant and may be removed in future
    versions.  It's recommended to use the names in the descriptions
    instead, which produce identical output:

      =========  =======================================================
      Colormap   Description
      =========  =======================================================
      gist_gray  identical to *gray*
      gist_yarg  identical to *gray_r*
      binary     identical to *gray_r*
      spectral   identical to *nipy_spectral* [#]_
      =========  =======================================================

    .. rubric:: Footnotes

    .. [#] Rainbow colormaps, ``jet`` in particular, are considered a poor
      choice for scientific visualization by many researchers: `Rainbow Color
      Map (Still) Considered Harmful
      <http://ieeexplore.ieee.org/document/4118486/?arnumber=4118486>`_

    .. [#] Resembles "BkBlAqGrYeOrReViWh200" from NCAR Command
      Language. See `Color Table Gallery
      <https://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml>`_

    .. [#] See `Diverging Color Maps for Scientific Visualization
      <http://www.kennethmoreland.com/color-maps/>`_ by Kenneth Moreland.

    .. [#] See `A Color Map for Effective Black-and-White Rendering of
      Color-Scale Images
      <https://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m>`_
      by Carey Rappaport

    .. [#] Changed to distinguish from ColorBrewer's *Spectral* map.
      :func:`spectral` still works, but
      ``set_cmap('nipy_spectral')`` is recommended for clarity.


    """
    return sorted(cm.cmap_d)


def _setup_pyplot_info_docstrings():
    """
    Generates the plotting and docstring.

    These must be done after the entire module is imported, so it is
    called from the end of this module, which is generated by
    boilerplate.py.
    """
    # Generate the plotting docstring
    import re

    def pad(s, l):
        """Pad string *s* to length *l*."""
        if l < len(s):
            return s[:l]
        return s + ' ' * (l - len(s))

    commands = get_plot_commands()

    first_sentence = re.compile(r"(?:\s*).+?\.(?:\s+|$)", flags=re.DOTALL)

    # Collect the first sentence of the docstring for all of the
    # plotting commands.
    rows = []
    max_name = 0
    max_summary = 0
    for name in commands:
        doc = globals()[name].__doc__
        summary = ''
        if doc is not None:
            match = first_sentence.match(doc)
            if match is not None:
                summary = match.group(0).strip().replace('\n', ' ')
        name = '`%s`' % name
        rows.append([name, summary])
        max_name = max(max_name, len(name))
        max_summary = max(max_summary, len(summary))

    lines = []
    sep = '=' * max_name + ' ' + '=' * max_summary
    lines.append(sep)
    lines.append(' '.join([pad("Function", max_name),
                           pad("Description", max_summary)]))
    lines.append(sep)
    for name, summary in rows:
        lines.append(' '.join([pad(name, max_name),
                               pad(summary, max_summary)]))
    lines.append(sep)

    plotting.__doc__ = '\n'.join(lines)

## Plotting part 1: manually generated functions and wrappers ##

def colorbar(mappable=None, cax=None, ax=None, **kw):
    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).')
    if ax is None:
        ax = gca()

    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
    return ret
colorbar.__doc__ = matplotlib.colorbar.colorbar_doc


def clim(vmin=None, vmax=None):
    """
    Set the color limits of the current image.

    To apply clim to all axes images do::

      clim(0, 0.5)

    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, for example::

      for im in gca().get_images():
          im.set_clim(0, 0.05)

    """
    im = gci()
    if im is None:
        raise RuntimeError('You must first define an image, e.g., with imshow')

    im.set_clim(vmin, vmax)


def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap)



@docstring.copy_dedent(_imread)
def imread(*args, **kwargs):
    return _imread(*args, **kwargs)


@docstring.copy_dedent(_imsave)
def imsave(*args, **kwargs):
    return _imsave(*args, **kwargs)


def matshow(A, fignum=None, **kw):
    """
    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.

    With the exception of *fignum*, keyword arguments are passed to
    :func:`~matplotlib.pyplot.imshow`.  You may set the *origin*
    kwarg to "lower" if you want the first row in the array to be
    at the bottom instead of the top.


    *fignum*: [ None | integer | False ]
      By default, :func:`matshow` creates a new figure window with
      automatic numbering.  If *fignum* is given as an integer, the
      created figure will use this figure number.  Because of how
      :func:`matshow` tries to set the figure aspect ratio to be the
      one of the array, if you provide the number of an already
      existing figure, strange things may happen.

      If *fignum* is *False* or 0, a new figure window will **NOT** be created.
    """
    A = np.asanyarray(A)
    if fignum is False or fignum is 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, **kw)
    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 :func:`~matplotlib.pyplot.plot`.

    """
    # If an axis already exists, check if it has a polar projection
    if gcf().get_axes():
        if not isinstance(gca(), PolarAxes):
            warnings.warn('Trying to create polar plot on an axis that does '
                          'not have a polar projection.')
    ax = gca(polar=True)
    ret = ax.plot(*args, **kwargs)
    return ret


def plotfile(fname, cols=(0,), plotfuncs=None,
             comments='#', skiprows=0, checkrows=5, delimiter=',',
             names=None, subplots=True, newfig=True, **kwargs):
    """
    Plot the data in a file.

    *cols* is a sequence of column identifiers to plot.  An identifier
    is either an int or a string.  If it is an int, it indicates the
    column number.  If it is a string, it indicates the column header.
    matplotlib will make column headers lower case, replace spaces with
    underscores, and remove all illegal characters; so ``'Adj Close*'``
    will have name ``'adj_close'``.

    - If len(*cols*) == 1, only that column will be plotted on the *y* axis.

    - If len(*cols*) > 1, the first element will be an identifier for
      data for the *x* axis and the remaining elements will be the
      column indexes for multiple subplots if *subplots* is *True*
      (the default), or for lines in a single subplot if *subplots*
      is *False*.

    *plotfuncs*, if not *None*, is a dictionary mapping identifier to
    an :class:`~matplotlib.axes.Axes` plotting function as a string.
    Default is 'plot', other choices are 'semilogy', 'fill', 'bar',
    etc.  You must use the same type of identifier in the *cols*
    vector as you use in the *plotfuncs* dictionary, e.g., integer
    column numbers in both or column names in both. If *subplots*
    is *False*, then including any function such as 'semilogy'
    that changes the axis scaling will set the scaling for all
    columns.

    *comments*, *skiprows*, *checkrows*, *delimiter*, and *names*
    are all passed on to :func:`matplotlib.pylab.csv2rec` to
    load the data into a record array.

    If *newfig* is *True*, the plot always will be made in a new figure;
    if *False*, it will be made in the current figure if one exists,
    else in a new figure.

    kwargs are passed on to plotting functions.

    Example usage::

      # plot the 2nd and 4th column against the 1st in two subplots
      plotfile(fname, (0,1,3))

      # plot using column names; specify an alternate plot type for volume
      plotfile(fname, ('date', 'volume', 'adj_close'),
                                    plotfuncs={'volume': 'semilogy'})

    Note: plotfile is intended as a convenience for quickly plotting
    data from flat files; it is not intended as an alternative
    interface to general plotting with pyplot or matplotlib.
    """

    if newfig:
        fig = figure()
    else:
        fig = gcf()

    if len(cols)<1:
        raise ValueError('must have at least one column of data')

    if plotfuncs is None:
        plotfuncs = dict()
    from matplotlib.cbook import mplDeprecation
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', mplDeprecation)
        r = mlab.csv2rec(fname, comments=comments, skiprows=skiprows,
                         checkrows=checkrows, delimiter=delimiter, names=names)

    def getname_val(identifier):
        'return the name and column data for identifier'
        if isinstance(identifier, six.string_types):
            return identifier, r[identifier]
        elif is_numlike(identifier):
            name = r.dtype.names[int(identifier)]
            return name, r[name]
        else:
            raise TypeError('identifier must be a string or integer')

    xname, x = getname_val(cols[0])
    ynamelist = []

    if len(cols)==1:
        ax1 = fig.add_subplot(1,1,1)
        funcname = plotfuncs.get(cols[0], 'plot')
        func = getattr(ax1, funcname)
        func(x, **kwargs)
        ax1.set_ylabel(xname)
    else:
        N = len(cols)
        for i in range(1,N):
            if subplots:
                if i==1:
                    ax = ax1 = fig.add_subplot(N-1,1,i)
                else:
                    ax = fig.add_subplot(N-1,1,i, sharex=ax1)
            elif i==1:
                ax = fig.add_subplot(1,1,1)

            yname, y = getname_val(cols[i])
            ynamelist.append(yname)

            funcname = plotfuncs.get(cols[i], 'plot')
            func = getattr(ax, funcname)

            func(x, y, **kwargs)
            if subplots:
                ax.set_ylabel(yname)
            if ax.is_last_row():
                ax.set_xlabel(xname)
            else:
                ax.set_xlabel('')

    if not subplots:
        ax.legend(ynamelist, loc='best')

    if xname=='date':
        fig.autofmt_xdate()


def _autogen_docstring(base):
    """Autogenerated wrappers will get their docstring from a base function
    with an addendum."""
    #msg = "\n\nAdditional kwargs: hold = [True|False] overrides default hold state"
    msg = ''
    addendum = docstring.Appender(msg, '\n\n')
    return lambda func: addendum(docstring.copy_dedent(base)(func))

# This function cannot be generated by boilerplate.py because it may
# return an image or a line.
@_autogen_docstring(Axes.spy)
def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', **kwargs):
    ax = gca()
    hold = kwargs.pop('hold', None)
    # allow callers to override the hold state by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs)
    finally:
        ax._hold = washold
    if isinstance(ret, cm.ScalarMappable):
        sci(ret)
    return ret

# just to be safe.  Interactive mode can be turned on without
# calling `plt.ion()` so register it again here.
# This is safe because multiple calls to `install_repl_displayhook`
# are no-ops and the registered function respect `mpl.is_interactive()`
# to determine if they should trigger a draw.
install_repl_displayhook()

################# REMAINING CONTENT GENERATED BY boilerplate.py ##############


# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.acorr)
def acorr(x, hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.acorr(x, data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.angle_spectrum)
def angle_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None,
                   hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.angle_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to,
                                sides=sides, data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.arrow)
def arrow(x, y, dx, dy, hold=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.arrow(x, y, dx, dy, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.axhline)
def axhline(y=0, xmin=0, xmax=1, hold=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.axhline(y=y, xmin=xmin, xmax=xmax, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.axhspan)
def axhspan(ymin, ymax, xmin=0, xmax=1, hold=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.axvline)
def axvline(x=0, ymin=0, ymax=1, hold=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.axvline(x=x, ymin=ymin, ymax=ymax, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.axvspan)
def axvspan(xmin, xmax, ymin=0, ymax=1, hold=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.bar)
def bar(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.bar(*args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.barh)
def barh(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.barh(*args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.broken_barh)
def broken_barh(xranges, yrange, hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.broken_barh(xranges, yrange, data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(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_xticks=True, autorange=False, zorder=None,
            hold=None, data=None):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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_xticks=manage_xticks, autorange=autorange,
                         zorder=zorder, data=data)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(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, hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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,
                        **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.clabel)
def clabel(CS, *args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.clabel(CS, *args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.contour)
def contour(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.contour(*args, **kwargs)
    finally:
        ax._hold = washold
    if ret._A is not None: sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.contourf)
def contourf(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.contourf(*args, **kwargs)
    finally:
        ax._hold = washold
    if ret._A is not None: sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(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, hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(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,
             hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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,
                          **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.eventplot)
def eventplot(positions, orientation='horizontal', lineoffsets=1, linelengths=1,
              linewidths=None, colors=None, linestyles='solid', hold=None,
              data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.eventplot(positions, orientation=orientation,
                           lineoffsets=lineoffsets, linelengths=linelengths,
                           linewidths=linewidths, colors=colors,
                           linestyles=linestyles, data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.fill)
def fill(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.fill(*args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.fill_between)
def fill_between(x, y1, y2=0, where=None, interpolate=False, step=None,
                 hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.fill_between(x, y1, y2=y2, where=where,
                              interpolate=interpolate, step=step, data=data,
                              **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.fill_betweenx)
def fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False,
                  hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.fill_betweenx(y, x1, x2=x2, where=where, step=step,
                               interpolate=interpolate, data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(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, hold=None,
           data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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, **kwargs)
    finally:
        ax._hold = washold
    sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.hist)
def hist(x, bins=None, range=None, density=None, weights=None, cumulative=False,
         bottom=None, histtype='bar', align='mid', orientation='vertical',
         rwidth=None, log=False, color=None, label=None, stacked=False,
         normed=None, hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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, normed=normed, data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.hist2d)
def hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None,
           cmax=None, hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.hist2d(x, y, bins=bins, range=range, normed=normed,
                        weights=weights, cmin=cmin, cmax=cmax, data=data,
                        **kwargs)
    finally:
        ax._hold = washold
    sci(ret[-1])
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.hlines)
def hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', hold=None,
           data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.hlines(y, xmin, xmax, colors=colors, linestyles=linestyles,
                        label=label, data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.imshow)
def imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None,
           vmin=None, vmax=None, origin=None, extent=None, shape=None,
           filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None,
           hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.imshow(X, cmap=cmap, norm=norm, aspect=aspect,
                        interpolation=interpolation, alpha=alpha, vmin=vmin,
                        vmax=vmax, origin=origin, extent=extent, shape=shape,
                        filternorm=filternorm, filterrad=filterrad,
                        imlim=imlim, resample=resample, url=url, data=data,
                        **kwargs)
    finally:
        ax._hold = washold
    sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.loglog)
def loglog(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.loglog(*args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.magnitude_spectrum)
def magnitude_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None,
                       sides=None, scale=None, hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.magnitude_spectrum(x, Fs=Fs, Fc=Fc, window=window,
                                    pad_to=pad_to, sides=sides, scale=scale,
                                    data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.pcolor)
def pcolor(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.pcolor(*args, **kwargs)
    finally:
        ax._hold = washold
    sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.pcolormesh)
def pcolormesh(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.pcolormesh(*args, **kwargs)
    finally:
        ax._hold = washold
    sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.phase_spectrum)
def phase_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None,
                   hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.phase_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to,
                                sides=sides, data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.pie)
def pie(x, explode=None, labels=None, colors=None, autopct=None,
        pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
        radius=None, counterclock=True, wedgeprops=None, textprops=None,
        center=(0, 0), frame=False, rotatelabels=False, hold=None, data=None):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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, data=data)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.plot)
def plot(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.plot(*args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.plot_date)
def plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, hold=None,
              data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.plot_date(x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate,
                           data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(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, hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.quiver)
def quiver(*args, **kw):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kw.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.quiver(*args, **kw)
    finally:
        ax._hold = washold
    sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.quiverkey)
def quiverkey(*args, **kw):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kw.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.quiverkey(*args, **kw)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.scatter)
def scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None,
            vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None,
            hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.scatter(x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
                         vmin=vmin, vmax=vmax, alpha=alpha,
                         linewidths=linewidths, verts=verts,
                         edgecolors=edgecolors, data=data, **kwargs)
    finally:
        ax._hold = washold
    sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.semilogx)
def semilogx(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.semilogx(*args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.semilogy)
def semilogy(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.semilogy(*args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(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,
             hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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, **kwargs)
    finally:
        ax._hold = washold
    sci(ret[-1])
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.stackplot)
def stackplot(x, *args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.stackplot(x, *args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.stem)
def stem(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.stem(*args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.step)
def step(x, y, *args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.step(x, y, *args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(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', hold=None, data=None):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.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,
                            data=data)
    finally:
        ax._hold = washold
    sci(ret.lines)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.tricontour)
def tricontour(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.tricontour(*args, **kwargs)
    finally:
        ax._hold = washold
    if ret._A is not None: sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.tricontourf)
def tricontourf(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.tricontourf(*args, **kwargs)
    finally:
        ax._hold = washold
    if ret._A is not None: sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.tripcolor)
def tripcolor(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.tripcolor(*args, **kwargs)
    finally:
        ax._hold = washold
    sci(ret)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.triplot)
def triplot(*args, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.triplot(*args, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.violinplot)
def violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False,
               showextrema=True, showmedians=False, points=100, bw_method=None,
               hold=None, data=None):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.violinplot(dataset, positions=positions, vert=vert,
                            widths=widths, showmeans=showmeans,
                            showextrema=showextrema, showmedians=showmedians,
                            points=points, bw_method=bw_method, data=data)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.vlines)
def vlines(x, ymin, ymax, colors='k', linestyles='solid', label='', hold=None,
           data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.vlines(x, ymin, ymax, colors=colors, linestyles=linestyles,
                        label=label, data=data, **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.xcorr)
def xcorr(x, y, normed=True, detrend=mlab.detrend_none, usevlines=True,
          maxlags=10, hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.xcorr(x, y, normed=normed, detrend=detrend,
                       usevlines=usevlines, maxlags=maxlags, data=data,
                       **kwargs)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.barbs)
def barbs(*args, **kw):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold
    hold = kw.pop('hold', None)
    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.barbs(*args, **kw)
    finally:
        ax._hold = washold

    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.cla)
def cla():
    ret = gca().cla()
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.grid)
def grid(b=None, which='major', axis='both', **kwargs):
    ret = gca().grid(b=b, which=which, axis=axis, **kwargs)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.legend)
def legend(*args, **kwargs):
    ret = gca().legend(*args, **kwargs)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.table)
def table(**kwargs):
    ret = gca().table(**kwargs)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.text)
def text(x, y, s, fontdict=None, withdash=False, **kwargs):
    ret = gca().text(x, y, s, fontdict=fontdict, withdash=withdash, **kwargs)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.annotate)
def annotate(*args, **kwargs):
    ret = gca().annotate(*args, **kwargs)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.ticklabel_format)
def ticklabel_format(**kwargs):
    ret = gca().ticklabel_format(**kwargs)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.locator_params)
def locator_params(axis='both', tight=None, **kwargs):
    ret = gca().locator_params(axis=axis, tight=tight, **kwargs)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.tick_params)
def tick_params(axis='both', **kwargs):
    ret = gca().tick_params(axis=axis, **kwargs)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.margins)
def margins(*args, **kw):
    ret = gca().margins(*args, **kw)
    return ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@docstring.copy_dedent(Axes.autoscale)
def autoscale(enable=True, axis='both', tight=None):
    ret = gca().autoscale(enable=enable, axis=axis, tight=tight)
    return ret

# 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")


# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
def spectral():
    """
    Set the colormap to "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.
    """
    from matplotlib.cbook import warn_deprecated
    warn_deprecated(
                    "2.0",
                    name="spectral",
                    obj_type="colormap"
                    )
    set_cmap("spectral")

_setup_pyplot_info_docstrings()
