1# Note: The first part of this file can be modified in place, but the latter
2# part is autogenerated by the boilerplate.py script.
3
4"""
5`matplotlib.pyplot` is a state-based interface to matplotlib. It provides
6a MATLAB-like way of plotting.
7
8pyplot is mainly intended for interactive plots and simple cases of programmatic
9plot generation::
10
11    import numpy as np
12    import matplotlib.pyplot as plt
13
14    x = np.arange(0, 5, 0.1)
15    y = np.sin(x)
16    plt.plot(x, y)
17
18The object-oriented API is recommended for more complex plots.
19"""
20from __future__ import (absolute_import, division, print_function,
21                        unicode_literals)
22
23import six
24
25import sys
26import time
27import warnings
28
29from cycler import cycler
30import matplotlib
31import matplotlib.colorbar
32from matplotlib import style
33from matplotlib import _pylab_helpers, interactive
34from matplotlib.cbook import dedent, silent_list, is_numlike
35from matplotlib.cbook import _string_to_bool
36from matplotlib.cbook import deprecated, warn_deprecated
37from matplotlib import docstring
38from matplotlib.backend_bases import FigureCanvasBase
39from matplotlib.figure import Figure, figaspect
40from matplotlib.gridspec import GridSpec
41from matplotlib.image import imread as _imread
42from matplotlib.image import imsave as _imsave
43from matplotlib import rcParams, rcParamsDefault, get_backend
44from matplotlib import rc_context
45from matplotlib.rcsetup import interactive_bk as _interactive_bk
46from matplotlib.artist import getp, get, Artist
47from matplotlib.artist import setp as _setp
48from matplotlib.axes import Axes, Subplot
49from matplotlib.projections import PolarAxes
50from matplotlib import mlab  # for csv2rec, detrend_none, window_hanning
51from matplotlib.scale import get_scale_docs, get_scale_names
52
53from matplotlib import cm
54from matplotlib.cm import get_cmap, register_cmap
55
56import numpy as np
57
58# We may not need the following imports here:
59from matplotlib.colors import Normalize
60from matplotlib.lines import Line2D
61from matplotlib.text import Text, Annotation
62from matplotlib.patches import Polygon, Rectangle, Circle, Arrow
63from matplotlib.widgets import SubplotTool, Button, Slider, Widget
64
65from .ticker import TickHelper, Formatter, FixedFormatter, NullFormatter,\
66           FuncFormatter, FormatStrFormatter, ScalarFormatter,\
67           LogFormatter, LogFormatterExponent, LogFormatterMathtext,\
68           Locator, IndexLocator, FixedLocator, NullLocator,\
69           LinearLocator, LogLocator, AutoLocator, MultipleLocator,\
70           MaxNLocator
71from matplotlib.backends import pylab_setup
72
73## Backend detection ##
74def _backend_selection():
75    """ If rcParams['backend_fallback'] is true, check to see if the
76        current backend is compatible with the current running event
77        loop, and if not switches to a compatible one.
78    """
79    backend = rcParams['backend']
80    if not rcParams['backend_fallback'] or backend not in _interactive_bk:
81        return
82    is_agg_backend = rcParams['backend'].endswith('Agg')
83    if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'):
84        import wx
85        if wx.App.IsMainLoopRunning():
86            rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend
87    elif 'PyQt4.QtCore' in sys.modules and not backend == 'Qt4Agg':
88        import PyQt4.QtGui
89        if not PyQt4.QtGui.qApp.startingUp():
90            # The mainloop is running.
91            rcParams['backend'] = 'qt4Agg'
92    elif 'PyQt5.QtCore' in sys.modules and not backend == 'Qt5Agg':
93        import PyQt5.QtWidgets
94        if not PyQt5.QtWidgets.qApp.startingUp():
95            # The mainloop is running.
96            rcParams['backend'] = 'qt5Agg'
97    elif ('gtk' in sys.modules and
98          backend not in ('GTK', 'GTKAgg', 'GTKCairo')):
99        if 'gi' in sys.modules:
100            from gi.repository import GObject
101            ml = GObject.MainLoop
102        else:
103            import gobject
104            ml = gobject.MainLoop
105        if ml().is_running():
106            rcParams['backend'] = 'gtk' + 'Agg' * is_agg_backend
107    elif 'Tkinter' in sys.modules and not backend == 'TkAgg':
108        # import Tkinter
109        pass  # what if anything do we need to do for tkinter?
110
111_backend_selection()
112
113## Global ##
114
115_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
116
117_IP_REGISTERED = None
118_INSTALL_FIG_OBSERVER = False
119
120
121def install_repl_displayhook():
122    """
123    Install a repl display hook so that any stale figure are automatically
124    redrawn when control is returned to the repl.
125
126    This works with IPython terminals and kernels,
127    as well as vanilla python shells.
128    """
129    global _IP_REGISTERED
130    global _INSTALL_FIG_OBSERVER
131
132    class _NotIPython(Exception):
133        pass
134
135    # see if we have IPython hooks around, if use them
136
137    try:
138        if 'IPython' in sys.modules:
139            from IPython import get_ipython
140            ip = get_ipython()
141            if ip is None:
142                raise _NotIPython()
143
144            if _IP_REGISTERED:
145                return
146
147            def post_execute():
148                if matplotlib.is_interactive():
149                    draw_all()
150
151            # IPython >= 2
152            try:
153                ip.events.register('post_execute', post_execute)
154            except AttributeError:
155                # IPython 1.x
156                ip.register_post_execute(post_execute)
157
158            _IP_REGISTERED = post_execute
159            _INSTALL_FIG_OBSERVER = False
160
161            # trigger IPython's eventloop integration, if available
162            from IPython.core.pylabtools import backend2gui
163
164            ipython_gui_name = backend2gui.get(get_backend())
165            if ipython_gui_name:
166                ip.enable_gui(ipython_gui_name)
167        else:
168            _INSTALL_FIG_OBSERVER = True
169
170    # import failed or ipython is not running
171    except (ImportError, _NotIPython):
172        _INSTALL_FIG_OBSERVER = True
173
174
175def uninstall_repl_displayhook():
176    """
177    Uninstalls the matplotlib display hook.
178
179    .. warning
180
181       Need IPython >= 2 for this to work.  For IPython < 2 will raise a
182       ``NotImplementedError``
183
184    .. warning
185
186       If you are using vanilla python and have installed another
187       display hook this will reset ``sys.displayhook`` to what ever
188       function was there when matplotlib installed it's displayhook,
189       possibly discarding your changes.
190    """
191    global _IP_REGISTERED
192    global _INSTALL_FIG_OBSERVER
193    if _IP_REGISTERED:
194        from IPython import get_ipython
195        ip = get_ipython()
196        try:
197            ip.events.unregister('post_execute', _IP_REGISTERED)
198        except AttributeError:
199            raise NotImplementedError("Can not unregister events "
200                                      "in IPython < 2.0")
201        _IP_REGISTERED = None
202
203    if _INSTALL_FIG_OBSERVER:
204        _INSTALL_FIG_OBSERVER = False
205
206
207draw_all = _pylab_helpers.Gcf.draw_all
208
209
210@docstring.copy_dedent(Artist.findobj)
211def findobj(o=None, match=None, include_self=True):
212    if o is None:
213        o = gcf()
214    return o.findobj(match, include_self=include_self)
215
216
217def switch_backend(newbackend):
218    """
219    Switch the default backend.  This feature is **experimental**, and
220    is only expected to work switching to an image backend.  e.g., if
221    you have a bunch of PostScript scripts that you want to run from
222    an interactive ipython session, you may want to switch to the PS
223    backend before running them to avoid having a bunch of GUI windows
224    popup.  If you try to interactively switch from one GUI backend to
225    another, you will explode.
226
227    Calling this command will close all open windows.
228    """
229    close('all')
230    global _backend_mod, new_figure_manager, draw_if_interactive, _show
231    matplotlib.use(newbackend, warn=False, force=True)
232    from matplotlib.backends import pylab_setup
233    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
234
235
236def show(*args, **kw):
237    """
238    Display a figure.
239    When running in ipython with its pylab mode, display all
240    figures and return to the ipython prompt.
241
242    In non-interactive mode, display all figures and block until
243    the figures have been closed; in interactive mode it has no
244    effect unless figures were created prior to a change from
245    non-interactive to interactive mode (not recommended).  In
246    that case it displays the figures but does not block.
247
248    A single experimental keyword argument, *block*, may be
249    set to True or False to override the blocking behavior
250    described above.
251    """
252    global _show
253    return _show(*args, **kw)
254
255
256def isinteractive():
257    """
258    Return status of interactive mode.
259    """
260    return matplotlib.is_interactive()
261
262
263def ioff():
264    """Turn interactive mode off."""
265    matplotlib.interactive(False)
266    uninstall_repl_displayhook()
267
268
269def ion():
270    """Turn interactive mode on."""
271    matplotlib.interactive(True)
272    install_repl_displayhook()
273
274
275def pause(interval):
276    """
277    Pause for *interval* seconds.
278
279    If there is an active figure, it will be updated and displayed before the
280    pause, and the GUI event loop (if any) will run during the pause.
281
282    This can be used for crude animation.  For more complex animation, see
283    :mod:`matplotlib.animation`.
284
285    Notes
286    -----
287    This function is experimental; its behavior may be changed or extended in a
288    future release.
289    """
290    manager = _pylab_helpers.Gcf.get_active()
291    if manager is not None:
292        canvas = manager.canvas
293        if canvas.figure.stale:
294            canvas.draw_idle()
295        show(block=False)
296        canvas.start_event_loop(interval)
297    else:
298        time.sleep(interval)
299
300
301@docstring.copy_dedent(matplotlib.rc)
302def rc(*args, **kwargs):
303    matplotlib.rc(*args, **kwargs)
304
305
306@docstring.copy_dedent(matplotlib.rc_context)
307def rc_context(rc=None, fname=None):
308    return matplotlib.rc_context(rc, fname)
309
310
311@docstring.copy_dedent(matplotlib.rcdefaults)
312def rcdefaults():
313    matplotlib.rcdefaults()
314    if matplotlib.is_interactive():
315        draw_all()
316
317
318# The current "image" (ScalarMappable) is retrieved or set
319# only via the pyplot interface using the following two
320# functions:
321def gci():
322    """
323    Get the current colorable artist.  Specifically, returns the
324    current :class:`~matplotlib.cm.ScalarMappable` instance (image or
325    patch collection), or *None* if no images or patch collections
326    have been defined.  The commands :func:`~matplotlib.pyplot.imshow`
327    and :func:`~matplotlib.pyplot.figimage` create
328    :class:`~matplotlib.image.Image` instances, and the commands
329    :func:`~matplotlib.pyplot.pcolor` and
330    :func:`~matplotlib.pyplot.scatter` create
331    :class:`~matplotlib.collections.Collection` instances.  The
332    current image is an attribute of the current axes, or the nearest
333    earlier axes in the current figure that contains an image.
334    """
335    return gcf()._gci()
336
337
338def sci(im):
339    """
340    Set the current image.  This image will be the target of colormap
341    commands like :func:`~matplotlib.pyplot.jet`,
342    :func:`~matplotlib.pyplot.hot` or
343    :func:`~matplotlib.pyplot.clim`).  The current image is an
344    attribute of the current axes.
345    """
346    gca()._sci(im)
347
348
349## Any Artist ##
350# (getp is simply imported)
351@docstring.copy(_setp)
352def setp(*args, **kwargs):
353    return _setp(*args, **kwargs)
354
355
356def xkcd(scale=1, length=100, randomness=2):
357    """
358    Turns on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode.
359    This will only have effect on things drawn after this function is
360    called.
361
362    For best results, the "Humor Sans" font should be installed: it is
363    not included with matplotlib.
364
365    Parameters
366    ----------
367    scale : float, optional
368        The amplitude of the wiggle perpendicular to the source line.
369    length : float, optional
370        The length of the wiggle along the line.
371    randomness : float, optional
372        The scale factor by which the length is shrunken or expanded.
373
374    Notes
375    -----
376    This function works by a number of rcParams, so it will probably
377    override others you have set before.
378
379    If you want the effects of this function to be temporary, it can
380    be used as a context manager, for example::
381
382        with plt.xkcd():
383            # This figure will be in XKCD-style
384            fig1 = plt.figure()
385            # ...
386
387        # This figure will be in regular style
388        fig2 = plt.figure()
389    """
390    if rcParams['text.usetex']:
391        raise RuntimeError(
392            "xkcd mode is not compatible with text.usetex = True")
393
394    from matplotlib import patheffects
395    return rc_context({
396        'font.family': ['xkcd', 'Humor Sans', 'Comic Sans MS'],
397        'font.size': 14.0,
398        'path.sketch': (scale, length, randomness),
399        'path.effects': [patheffects.withStroke(linewidth=4, foreground="w")],
400        'axes.linewidth': 1.5,
401        'lines.linewidth': 2.0,
402        'figure.facecolor': 'white',
403        'grid.linewidth': 0.0,
404        'axes.grid': False,
405        'axes.unicode_minus': False,
406        'axes.edgecolor': 'black',
407        'xtick.major.size': 8,
408        'xtick.major.width': 3,
409        'ytick.major.size': 8,
410        'ytick.major.width': 3,
411    })
412
413
414## Figures ##
415
416def figure(num=None,  # autoincrement if None, else integer from 1-N
417           figsize=None,  # defaults to rc figure.figsize
418           dpi=None,  # defaults to rc figure.dpi
419           facecolor=None,  # defaults to rc figure.facecolor
420           edgecolor=None,  # defaults to rc figure.edgecolor
421           frameon=True,
422           FigureClass=Figure,
423           clear=False,
424           **kwargs
425           ):
426    """
427    Creates a new figure.
428
429    Parameters
430    ----------
431
432    num : integer or string, optional, default: none
433        If not provided, a new figure will be created, and the figure number
434        will be incremented. The figure objects holds this number in a `number`
435        attribute.
436        If num is provided, and a figure with this id already exists, make
437        it active, and returns a reference to it. If this figure does not
438        exists, create it and returns it.
439        If num is a string, the window title will be set to this figure's
440        `num`.
441
442    figsize : tuple of integers, optional, default: None
443        width, height in inches. If not provided, defaults to rc
444        figure.figsize.
445
446    dpi : integer, optional, default: None
447        resolution of the figure. If not provided, defaults to rc figure.dpi.
448
449    facecolor :
450        the background color. If not provided, defaults to rc figure.facecolor.
451
452    edgecolor :
453        the border color. If not provided, defaults to rc figure.edgecolor.
454
455    frameon : bool, optional, default: True
456        If False, suppress drawing the figure frame.
457
458    FigureClass : class derived from matplotlib.figure.Figure
459        Optionally use a custom Figure instance.
460
461    clear : bool, optional, default: False
462        If True and the figure already exists, then it is cleared.
463
464    Returns
465    -------
466    figure : Figure
467        The Figure instance returned will also be passed to new_figure_manager
468        in the backends, which allows to hook custom Figure classes into the
469        pylab interface. Additional kwargs will be passed to the figure init
470        function.
471
472    Notes
473    -----
474    If you are creating many figures, make sure you explicitly call "close"
475    on the figures you are not using, because this will enable pylab
476    to properly clean up the memory.
477
478    rcParams defines the default values, which can be modified in the
479    matplotlibrc file
480
481    """
482
483    if figsize is None:
484        figsize = rcParams['figure.figsize']
485    if dpi is None:
486        dpi = rcParams['figure.dpi']
487    if facecolor is None:
488        facecolor = rcParams['figure.facecolor']
489    if edgecolor is None:
490        edgecolor = rcParams['figure.edgecolor']
491
492    allnums = get_fignums()
493    next_num = max(allnums) + 1 if allnums else 1
494    figLabel = ''
495    if num is None:
496        num = next_num
497    elif isinstance(num, six.string_types):
498        figLabel = num
499        allLabels = get_figlabels()
500        if figLabel not in allLabels:
501            if figLabel == 'all':
502                warnings.warn("close('all') closes all existing figures")
503            num = next_num
504        else:
505            inum = allLabels.index(figLabel)
506            num = allnums[inum]
507    else:
508        num = int(num)  # crude validation of num argument
509
510    figManager = _pylab_helpers.Gcf.get_fig_manager(num)
511    if figManager is None:
512        max_open_warning = rcParams['figure.max_open_warning']
513
514        if (max_open_warning >= 1 and len(allnums) >= max_open_warning):
515            warnings.warn(
516                "More than %d figures have been opened. Figures "
517                "created through the pyplot interface "
518                "(`matplotlib.pyplot.figure`) are retained until "
519                "explicitly closed and may consume too much memory. "
520                "(To control this warning, see the rcParam "
521                "`figure.max_open_warning`)." %
522                max_open_warning, RuntimeWarning)
523
524        if get_backend().lower() == 'ps':
525            dpi = 72
526
527        figManager = new_figure_manager(num, figsize=figsize,
528                                        dpi=dpi,
529                                        facecolor=facecolor,
530                                        edgecolor=edgecolor,
531                                        frameon=frameon,
532                                        FigureClass=FigureClass,
533                                        **kwargs)
534
535        if figLabel:
536            figManager.set_window_title(figLabel)
537            figManager.canvas.figure.set_label(figLabel)
538
539        # make this figure current on button press event
540        def make_active(event):
541            _pylab_helpers.Gcf.set_active(figManager)
542
543        cid = figManager.canvas.mpl_connect('button_press_event', make_active)
544        figManager._cidgcf = cid
545
546        _pylab_helpers.Gcf.set_active(figManager)
547        fig = figManager.canvas.figure
548        fig.number = num
549
550        # make sure backends (inline) that we don't ship that expect this
551        # to be called in plotting commands to make the figure call show
552        # still work.  There is probably a better way to do this in the
553        # FigureManager base class.
554        if matplotlib.is_interactive():
555            draw_if_interactive()
556
557        if _INSTALL_FIG_OBSERVER:
558            fig.stale_callback = _auto_draw_if_interactive
559
560    if clear:
561        figManager.canvas.figure.clear()
562
563    return figManager.canvas.figure
564
565
566def _auto_draw_if_interactive(fig, val):
567    """
568    This is an internal helper function for making sure that auto-redrawing
569    works as intended in the plain python repl.
570
571    Parameters
572    ----------
573    fig : Figure
574        A figure object which is assumed to be associated with a canvas
575    """
576    if val and matplotlib.is_interactive() and not fig.canvas.is_saving():
577        fig.canvas.draw_idle()
578
579
580def gcf():
581    """Get a reference to the current figure."""
582    figManager = _pylab_helpers.Gcf.get_active()
583    if figManager is not None:
584        return figManager.canvas.figure
585    else:
586        return figure()
587
588
589def fignum_exists(num):
590    return _pylab_helpers.Gcf.has_fignum(num) or num in get_figlabels()
591
592
593def get_fignums():
594    """Return a list of existing figure numbers."""
595    return sorted(_pylab_helpers.Gcf.figs)
596
597
598def get_figlabels():
599    """Return a list of existing figure labels."""
600    figManagers = _pylab_helpers.Gcf.get_all_fig_managers()
601    figManagers.sort(key=lambda m: m.num)
602    return [m.canvas.figure.get_label() for m in figManagers]
603
604
605def get_current_fig_manager():
606    figManager = _pylab_helpers.Gcf.get_active()
607    if figManager is None:
608        gcf()  # creates an active figure as a side effect
609        figManager = _pylab_helpers.Gcf.get_active()
610    return figManager
611
612
613@docstring.copy_dedent(FigureCanvasBase.mpl_connect)
614def connect(s, func):
615    return get_current_fig_manager().canvas.mpl_connect(s, func)
616
617
618@docstring.copy_dedent(FigureCanvasBase.mpl_disconnect)
619def disconnect(cid):
620    return get_current_fig_manager().canvas.mpl_disconnect(cid)
621
622
623def close(*args):
624    """
625    Close a figure window.
626
627    ``close()`` by itself closes the current figure
628
629    ``close(fig)`` closes the `.Figure` instance *fig*
630
631    ``close(num)`` closes the figure number *num*
632
633    ``close(name)`` where *name* is a string, closes figure with that label
634
635    ``close('all')`` closes all the figure windows
636    """
637
638    if len(args) == 0:
639        figManager = _pylab_helpers.Gcf.get_active()
640        if figManager is None:
641            return
642        else:
643            _pylab_helpers.Gcf.destroy(figManager.num)
644    elif len(args) == 1:
645        arg = args[0]
646        if arg == 'all':
647            _pylab_helpers.Gcf.destroy_all()
648        elif isinstance(arg, six.integer_types):
649            _pylab_helpers.Gcf.destroy(arg)
650        elif hasattr(arg, 'int'):
651            # if we are dealing with a type UUID, we
652            # can use its integer representation
653            _pylab_helpers.Gcf.destroy(arg.int)
654        elif isinstance(arg, six.string_types):
655            allLabels = get_figlabels()
656            if arg in allLabels:
657                num = get_fignums()[allLabels.index(arg)]
658                _pylab_helpers.Gcf.destroy(num)
659        elif isinstance(arg, Figure):
660            _pylab_helpers.Gcf.destroy_fig(arg)
661        else:
662            raise TypeError('Unrecognized argument type %s to close' % type(arg))
663    else:
664        raise TypeError('close takes 0 or 1 arguments')
665
666
667def clf():
668    """
669    Clear the current figure.
670    """
671    gcf().clf()
672
673
674def draw():
675    """Redraw the current figure.
676
677    This is used to update a figure that has been altered, but not
678    automatically re-drawn.  If interactive mode is on (:func:`.ion()`), this
679    should be only rarely needed, but there may be ways to modify the state of
680    a figure without marking it as `stale`.  Please report these cases as
681    bugs.
682
683    A more object-oriented alternative, given any
684    :class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
685    was created using a :mod:`~matplotlib.pyplot` function, is::
686
687        fig.canvas.draw_idle()
688    """
689    get_current_fig_manager().canvas.draw_idle()
690
691
692@docstring.copy_dedent(Figure.savefig)
693def savefig(*args, **kwargs):
694    fig = gcf()
695    res = fig.savefig(*args, **kwargs)
696    fig.canvas.draw_idle()   # need this if 'transparent=True' to reset colors
697    return res
698
699
700@docstring.copy_dedent(Figure.ginput)
701def ginput(*args, **kwargs):
702    """
703    Blocking call to interact with the figure.
704
705    This will wait for *n* clicks from the user and return a list of the
706    coordinates of each click.
707
708    If *timeout* is negative, does not timeout.
709    """
710    return gcf().ginput(*args, **kwargs)
711
712
713@docstring.copy_dedent(Figure.waitforbuttonpress)
714def waitforbuttonpress(*args, **kwargs):
715    """
716    Blocking call to interact with the figure.
717
718    This will wait for *n* key or mouse clicks from the user and
719    return a list containing True's for keyboard clicks and False's
720    for mouse clicks.
721
722    If *timeout* is negative, does not timeout.
723    """
724    return gcf().waitforbuttonpress(*args, **kwargs)
725
726
727# Putting things in figures
728
729@docstring.copy_dedent(Figure.text)
730def figtext(*args, **kwargs):
731    return gcf().text(*args, **kwargs)
732
733
734@docstring.copy_dedent(Figure.suptitle)
735def suptitle(*args, **kwargs):
736    return gcf().suptitle(*args, **kwargs)
737
738
739@docstring.copy_dedent(Figure.figimage)
740def figimage(*args, **kwargs):
741    return gcf().figimage(*args, **kwargs)
742
743
744def figlegend(*args, **kwargs):
745    """
746    Place a legend in the figure.
747
748    *labels*
749      a sequence of strings
750
751    *handles*
752      a sequence of :class:`~matplotlib.lines.Line2D` or
753      :class:`~matplotlib.patches.Patch` instances
754
755    *loc*
756      can be a string or an integer specifying the legend
757      location
758
759    A :class:`matplotlib.legend.Legend` instance is returned.
760
761    Examples
762    --------
763
764    To make a legend from existing artists on every axes::
765
766      figlegend()
767
768    To make a legend for a list of lines and labels::
769
770      figlegend( (line1, line2, line3),
771                 ('label1', 'label2', 'label3'),
772                 'upper right' )
773
774    .. seealso::
775
776       :func:`~matplotlib.pyplot.legend`
777
778    """
779    return gcf().legend(*args, **kwargs)
780
781
782## Figure and Axes hybrid ##
783
784_hold_msg = """pyplot.hold is deprecated.
785    Future behavior will be consistent with the long-time default:
786    plot commands add elements without first clearing the
787    Axes and/or Figure."""
788
789@deprecated("2.0", message=_hold_msg)
790def hold(b=None):
791    """
792    Set the hold state.  If *b* is None (default), toggle the
793    hold state, else set the hold state to boolean value *b*::
794
795      hold()      # toggle hold
796      hold(True)  # hold is on
797      hold(False) # hold is off
798
799    When *hold* is *True*, subsequent plot commands will add elements to
800    the current axes.  When *hold* is *False*, the current axes and
801    figure will be cleared on the next plot command.
802
803    """
804
805    fig = gcf()
806    ax = fig.gca()
807
808    if b is not None:
809        b = bool(b)
810    fig._hold = b
811    ax._hold = b
812
813    # b=None toggles the hold state, so let's get get the current hold
814    # state; but should pyplot hold toggle the rc setting - me thinks
815    # not
816    b = ax._hold
817
818    # The comment above looks ancient; and probably the line below,
819    # contrary to the comment, is equally ancient.  It will trigger
820    # a second warning, but "Oh, well...".
821    rc('axes', hold=b)
822
823@deprecated("2.0", message=_hold_msg)
824def ishold():
825    """
826    Return the hold status of the current axes.
827    """
828    return gca()._hold
829
830
831@deprecated("2.0", message=_hold_msg)
832def over(func, *args, **kwargs):
833    """
834    Call a function with hold(True).
835
836    Calls::
837
838      func(*args, **kwargs)
839
840    with ``hold(True)`` and then restores the hold state.
841
842    """
843    ax = gca()
844    h = ax._hold
845    ax._hold = True
846    func(*args, **kwargs)
847    ax._hold = h
848
849## Axes ##
850
851
852def axes(arg=None, **kwargs):
853    """
854    Add an axes to the current figure and make it the current axes.
855
856    Parameters
857    ----------
858    arg : None or 4-tuple or Axes
859        The exact behavior of this function depends on the type:
860
861        - *None*: A new full window axes is added using
862          ``subplot(111, **kwargs)``
863        - 4-tuple of floats *rect* = ``[left, bottom, width, height]``.
864          A new axes is added with dimensions *rect* in normalized
865          (0, 1) units using `~.Figure.add_axes` on the current figure.
866        - `~matplotlib.axes.Axes`: This is equivalent to `.pyplot.sca`.
867          It sets the current axes to *arg*. Note: This implicitly
868          changes the current figure to the parent of *arg*.
869
870          .. note:: The use of an Axes as an argument is deprecated and will be
871                    removed in v3.0. Please use `.pyplot.sca` instead.
872
873    Other Parameters
874    ----------------
875    **kwargs :
876        For allowed keyword arguments see `.pyplot.subplot` and
877        `.Figure.add_axes` respectively. Some common keyword arguments are
878        listed below:
879
880        ========= =========== =================================================
881        kwarg     Accepts     Description
882        ========= =========== =================================================
883        facecolor color       the axes background color
884        frameon   bool        whether to display the frame
885        sharex    otherax     share x-axis with *otherax*
886        sharey    otherax     share y-axis with *otherax*
887        polar     bool        whether to use polar axes
888        aspect    [str | num] ['equal', 'auto'] or a number.  If a number, the
889                              ratio of y-unit/x-unit in screen-space.  See also
890                              `~.Axes.set_aspect`.
891        ========= =========== =================================================
892
893    Returns
894    -------
895    axes : Axes
896        The created or activated axes.
897
898    Examples
899    --------
900    Creating a new full window axes::
901
902        >>> plt.axes()
903
904    Creating a new axes with specified dimensions and some kwargs::
905
906        >>> plt.axes((left, bottom, width, height), facecolor='w')
907
908    """
909
910    if arg is None:
911        return subplot(111, **kwargs)
912
913    if isinstance(arg, Axes):
914        warn_deprecated("2.2",
915                        message="Using pyplot.axes(ax) with ax an Axes "
916                                "argument is deprecated. Please use "
917                                "pyplot.sca(ax) instead.")
918        ax = arg
919        sca(ax)
920        return ax
921    else:
922        rect = arg
923        return gcf().add_axes(rect, **kwargs)
924
925
926def delaxes(ax=None):
927    """
928    Remove the given `Axes` *ax* from the current figure. If *ax* is *None*,
929    the current axes is removed. A KeyError is raised if the axes doesn't exist.
930    """
931    if ax is None:
932        ax = gca()
933    gcf().delaxes(ax)
934
935
936def sca(ax):
937    """
938    Set the current Axes instance to *ax*.
939
940    The current Figure is updated to the parent of *ax*.
941    """
942    managers = _pylab_helpers.Gcf.get_all_fig_managers()
943    for m in managers:
944        if ax in m.canvas.figure.axes:
945            _pylab_helpers.Gcf.set_active(m)
946            m.canvas.figure.sca(ax)
947            return
948    raise ValueError("Axes instance argument was not found in a figure.")
949
950
951def gca(**kwargs):
952    """
953    Get the current :class:`~matplotlib.axes.Axes` instance on the
954    current figure matching the given keyword args, or create one.
955
956    Examples
957    --------
958    To get the current polar axes on the current figure::
959
960        plt.gca(projection='polar')
961
962    If the current axes doesn't exist, or isn't a polar one, the appropriate
963    axes will be created and then returned.
964
965    See Also
966    --------
967    matplotlib.figure.Figure.gca : The figure's gca method.
968    """
969    return gcf().gca(**kwargs)
970
971# More ways of creating axes:
972
973
974def subplot(*args, **kwargs):
975    """
976    Return a subplot axes at the given grid position.
977
978    Call signature::
979
980       subplot(nrows, ncols, index, **kwargs)
981
982    In the current figure, create and return an `~matplotlib.axes.Axes`,
983    at position *index* of a (virtual) grid of *nrows* by *ncols* axes.
984    Indexes go from 1 to ``nrows * ncols``, incrementing in row-major order.
985
986    If *nrows*, *ncols* and *index* are all less than 10, they can also be
987    given as a single, concatenated, three-digit number.
988
989    For example, ``subplot(2, 3, 3)`` and ``subplot(233)`` both create an
990    `matplotlib.axes.Axes` at the top right corner of the current figure,
991    occupying half of the figure height and a third of the figure width.
992
993    .. note::
994
995       Creating a subplot will delete any pre-existing subplot that overlaps
996       with it beyond sharing a boundary::
997
998          import matplotlib.pyplot as plt
999          # plot a line, implicitly creating a subplot(111)
1000          plt.plot([1,2,3])
1001          # now create a subplot which represents the top plot of a grid
1002          # with 2 rows and 1 column. Since this subplot will overlap the
1003          # first, the plot (and its axes) previously created, will be removed
1004          plt.subplot(211)
1005          plt.plot(range(12))
1006          plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background
1007
1008       If you do not want this behavior, use the
1009       :meth:`~matplotlib.figure.Figure.add_subplot` method or the
1010       :func:`~matplotlib.pyplot.axes` function instead.
1011
1012    Keyword arguments:
1013
1014      *facecolor*:
1015        The background color of the subplot, which can be any valid
1016        color specifier.  See :mod:`matplotlib.colors` for more
1017        information.
1018
1019      *polar*:
1020        A boolean flag indicating whether the subplot plot should be
1021        a polar projection.  Defaults to *False*.
1022
1023      *projection*:
1024        A string giving the name of a custom projection to be used
1025        for the subplot. This projection must have been previously
1026        registered. See :mod:`matplotlib.projections`.
1027
1028    .. seealso::
1029
1030        :func:`~matplotlib.pyplot.axes`
1031            For additional information on :func:`axes` and
1032            :func:`subplot` keyword arguments.
1033
1034        :file:`gallery/pie_and_polar_charts/polar_scatter.py`
1035            For an example
1036
1037    **Example:**
1038
1039    .. plot:: gallery/subplots_axes_and_figures/subplot.py
1040
1041    """
1042    # if subplot called without arguments, create subplot(1,1,1)
1043    if len(args)==0:
1044        args=(1,1,1)
1045
1046    # This check was added because it is very easy to type
1047    # subplot(1, 2, False) when subplots(1, 2, False) was intended
1048    # (sharex=False, that is). In most cases, no error will
1049    # ever occur, but mysterious behavior can result because what was
1050    # intended to be the sharex argument is instead treated as a
1051    # subplot index for subplot()
1052    if len(args) >= 3 and isinstance(args[2], bool) :
1053        warnings.warn("The subplot index argument to subplot() appears"
1054                      " to be a boolean. Did you intend to use subplots()?")
1055
1056    fig = gcf()
1057    a = fig.add_subplot(*args, **kwargs)
1058    bbox = a.bbox
1059    byebye = []
1060    for other in fig.axes:
1061        if other==a: continue
1062        if bbox.fully_overlaps(other.bbox):
1063            byebye.append(other)
1064    for ax in byebye: delaxes(ax)
1065
1066    return a
1067
1068
1069def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
1070             subplot_kw=None, gridspec_kw=None, **fig_kw):
1071    """
1072    Create a figure and a set of subplots
1073
1074    This utility wrapper makes it convenient to create common layouts of
1075    subplots, including the enclosing figure object, in a single call.
1076
1077    Parameters
1078    ----------
1079    nrows, ncols : int, optional, default: 1
1080        Number of rows/columns of the subplot grid.
1081
1082    sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
1083        Controls sharing of properties among x (`sharex`) or y (`sharey`)
1084        axes:
1085
1086            - True or 'all': x- or y-axis will be shared among all
1087              subplots.
1088            - False or 'none': each subplot x- or y-axis will be
1089              independent.
1090            - 'row': each subplot row will share an x- or y-axis.
1091            - 'col': each subplot column will share an x- or y-axis.
1092
1093        When subplots have a shared x-axis along a column, only the x tick
1094        labels of the bottom subplot are created. Similarly, when subplots
1095        have a shared y-axis along a row, only the y tick labels of the first
1096        column subplot are created. To later turn other subplots' ticklabels
1097        on, use :meth:`~matplotlib.axes.Axes.tick_params`.
1098
1099    squeeze : bool, optional, default: True
1100        - If True, extra dimensions are squeezed out from the returned
1101          array of Axes:
1102
1103            - if only one subplot is constructed (nrows=ncols=1), the
1104              resulting single Axes object is returned as a scalar.
1105            - for Nx1 or 1xM subplots, the returned object is a 1D numpy
1106              object array of Axes objects.
1107            - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
1108
1109        - If False, no squeezing at all is done: the returned Axes object is
1110          always a 2D array containing Axes instances, even if it ends up
1111          being 1x1.
1112
1113    subplot_kw : dict, optional
1114        Dict with keywords passed to the
1115        :meth:`~matplotlib.figure.Figure.add_subplot` call used to create each
1116        subplot.
1117
1118    gridspec_kw : dict, optional
1119        Dict with keywords passed to the
1120        :class:`~matplotlib.gridspec.GridSpec` constructor used to create the
1121        grid the subplots are placed on.
1122
1123    **fig_kw :
1124        All additional keyword arguments are passed to the :func:`figure` call.
1125
1126    Returns
1127    -------
1128    fig : :class:`matplotlib.figure.Figure` object
1129
1130    ax : Axes object or array of Axes objects.
1131
1132        ax can be either a single :class:`matplotlib.axes.Axes` object or an
1133        array of Axes objects if more than one subplot was created.  The
1134        dimensions of the resulting array can be controlled with the squeeze
1135        keyword, see above.
1136
1137    Examples
1138    --------
1139    First create some toy data:
1140
1141    >>> x = np.linspace(0, 2*np.pi, 400)
1142    >>> y = np.sin(x**2)
1143
1144    Creates just a figure and only one subplot
1145
1146    >>> fig, ax = plt.subplots()
1147    >>> ax.plot(x, y)
1148    >>> ax.set_title('Simple plot')
1149
1150    Creates two subplots and unpacks the output array immediately
1151
1152    >>> f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
1153    >>> ax1.plot(x, y)
1154    >>> ax1.set_title('Sharing Y axis')
1155    >>> ax2.scatter(x, y)
1156
1157    Creates four polar axes, and accesses them through the returned array
1158
1159    >>> fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))
1160    >>> axes[0, 0].plot(x, y)
1161    >>> axes[1, 1].scatter(x, y)
1162
1163    Share a X axis with each column of subplots
1164
1165    >>> plt.subplots(2, 2, sharex='col')
1166
1167    Share a Y axis with each row of subplots
1168
1169    >>> plt.subplots(2, 2, sharey='row')
1170
1171    Share both X and Y axes with all subplots
1172
1173    >>> plt.subplots(2, 2, sharex='all', sharey='all')
1174
1175    Note that this is the same as
1176
1177    >>> plt.subplots(2, 2, sharex=True, sharey=True)
1178
1179    See Also
1180    --------
1181    figure
1182    subplot
1183    """
1184    fig = figure(**fig_kw)
1185    axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
1186                       squeeze=squeeze, subplot_kw=subplot_kw,
1187                       gridspec_kw=gridspec_kw)
1188    return fig, axs
1189
1190
1191def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):
1192    """
1193    Create an axis at specific location inside a regular grid.
1194
1195    Parameters
1196    ----------
1197    shape : sequence of 2 ints
1198        Shape of grid in which to place axis.
1199        First entry is number of rows, second entry is number of columns.
1200
1201    loc : sequence of 2 ints
1202        Location to place axis within grid.
1203        First entry is row number, second entry is column number.
1204
1205    rowspan : int
1206        Number of rows for the axis to span to the right.
1207
1208    colspan : int
1209        Number of columns for the axis to span downwards.
1210
1211    fig : `Figure`, optional
1212        Figure to place axis in. Defaults to current figure.
1213
1214    **kwargs
1215        Additional keyword arguments are handed to `add_subplot`.
1216
1217
1218    Notes
1219    -----
1220    The following call ::
1221
1222        subplot2grid(shape, loc, rowspan=1, colspan=1)
1223
1224    is identical to ::
1225
1226        gridspec=GridSpec(shape[0], shape[1])
1227        subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan)
1228        subplot(subplotspec)
1229    """
1230
1231    if fig is None:
1232        fig = gcf()
1233
1234    s1, s2 = shape
1235    subplotspec = GridSpec(s1, s2).new_subplotspec(loc,
1236                                                   rowspan=rowspan,
1237                                                   colspan=colspan)
1238    a = fig.add_subplot(subplotspec, **kwargs)
1239    bbox = a.bbox
1240    byebye = []
1241    for other in fig.axes:
1242        if other == a:
1243            continue
1244        if bbox.fully_overlaps(other.bbox):
1245            byebye.append(other)
1246    for ax in byebye:
1247        delaxes(ax)
1248
1249    return a
1250
1251
1252def twinx(ax=None):
1253    """
1254    Make a second axes that shares the *x*-axis.  The new axes will
1255    overlay *ax* (or the current axes if *ax* is *None*).  The ticks
1256    for *ax2* will be placed on the right, and the *ax2* instance is
1257    returned.
1258
1259    .. seealso::
1260
1261       :file:`examples/api_examples/two_scales.py`
1262          For an example
1263    """
1264    if ax is None:
1265        ax=gca()
1266    ax1 = ax.twinx()
1267    return ax1
1268
1269
1270def twiny(ax=None):
1271    """
1272    Make a second axes that shares the *y*-axis.  The new axis will
1273    overlay *ax* (or the current axes if *ax* is *None*).  The ticks
1274    for *ax2* will be placed on the top, and the *ax2* instance is
1275    returned.
1276    """
1277    if ax is None:
1278        ax=gca()
1279    ax1 = ax.twiny()
1280    return ax1
1281
1282
1283def subplots_adjust(*args, **kwargs):
1284    """
1285    Tune the subplot layout.
1286
1287    call signature::
1288
1289      subplots_adjust(left=None, bottom=None, right=None, top=None,
1290                      wspace=None, hspace=None)
1291
1292    The parameter meanings (and suggested defaults) are::
1293
1294      left  = 0.125  # the left side of the subplots of the figure
1295      right = 0.9    # the right side of the subplots of the figure
1296      bottom = 0.1   # the bottom of the subplots of the figure
1297      top = 0.9      # the top of the subplots of the figure
1298      wspace = 0.2   # the amount of width reserved for space between subplots,
1299                     # expressed as a fraction of the average axis width
1300      hspace = 0.2   # the amount of height reserved for space between subplots,
1301                     # expressed as a fraction of the average axis height
1302
1303    The actual defaults are controlled by the rc file
1304    """
1305    fig = gcf()
1306    fig.subplots_adjust(*args, **kwargs)
1307
1308
1309def subplot_tool(targetfig=None):
1310    """
1311    Launch a subplot tool window for a figure.
1312
1313    A :class:`matplotlib.widgets.SubplotTool` instance is returned.
1314    """
1315    tbar = rcParams['toolbar'] # turn off the navigation toolbar for the toolfig
1316    rcParams['toolbar'] = 'None'
1317    if targetfig is None:
1318        manager = get_current_fig_manager()
1319        targetfig = manager.canvas.figure
1320    else:
1321        # find the manager for this figure
1322        for manager in _pylab_helpers.Gcf._activeQue:
1323            if manager.canvas.figure==targetfig: break
1324        else: raise RuntimeError('Could not find manager for targetfig')
1325
1326    toolfig = figure(figsize=(6,3))
1327    toolfig.subplots_adjust(top=0.9)
1328    ret =  SubplotTool(targetfig, toolfig)
1329    rcParams['toolbar'] = tbar
1330    _pylab_helpers.Gcf.set_active(manager)  # restore the current figure
1331    return ret
1332
1333
1334def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None):
1335    """
1336    Automatically adjust subplot parameters to give specified padding.
1337
1338    Parameters
1339    ----------
1340    pad : float
1341        padding between the figure edge and the edges of subplots, as a fraction of the font-size.
1342    h_pad, w_pad : float
1343        padding (height/width) between edges of adjacent subplots.
1344        Defaults to `pad_inches`.
1345    rect : if rect is given, it is interpreted as a rectangle
1346        (left, bottom, right, top) in the normalized figure
1347        coordinate that the whole subplots area (including
1348        labels) will fit into. Default is (0, 0, 1, 1).
1349
1350    """
1351    fig = gcf()
1352    fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
1353
1354
1355def box(on=None):
1356    """
1357    Turn the axes box on or off on the current axes.
1358
1359    Parameters
1360    ----------
1361    on : bool or None
1362        The new `~matplotlib.axes.Axes` box state. If ``None``, toggle
1363        the state.
1364
1365    See Also
1366    --------
1367    :meth:`matplotlib.axes.Axes.set_frame_on`
1368    :meth:`matplotlib.axes.Axes.get_frame_on`
1369    """
1370    ax = gca()
1371    if on is None:
1372        on = not ax.get_frame_on()
1373    on = _string_to_bool(on)
1374    ax.set_frame_on(on)
1375
1376
1377def title(s, *args, **kwargs):
1378    """
1379    Set a title of the current axes.
1380
1381    Set one of the three available axes titles. The available titles are
1382    positioned above the axes in the center, flush with the left edge,
1383    and flush with the right edge.
1384
1385    .. seealso::
1386        See :func:`~matplotlib.pyplot.text` for adding text
1387        to the current axes
1388
1389    Parameters
1390    ----------
1391    label : str
1392        Text to use for the title
1393
1394    fontdict : dict
1395        A dictionary controlling the appearance of the title text,
1396        the default `fontdict` is:
1397
1398            {'fontsize': rcParams['axes.titlesize'],
1399            'fontweight' : rcParams['axes.titleweight'],
1400            'verticalalignment': 'baseline',
1401            'horizontalalignment': loc}
1402
1403    loc : {'center', 'left', 'right'}, str, optional
1404        Which title to set, defaults to 'center'
1405
1406    Returns
1407    -------
1408    text : :class:`~matplotlib.text.Text`
1409        The matplotlib text instance representing the title
1410
1411    Other parameters
1412    ----------------
1413    kwargs : text properties
1414        Other keyword arguments are text properties, see
1415        :class:`~matplotlib.text.Text` for a list of valid text
1416        properties.
1417
1418    """
1419    return gca().set_title(s, *args, **kwargs)
1420
1421## Axis ##
1422
1423
1424def axis(*v, **kwargs):
1425    """
1426    Convenience method to get or set axis properties.
1427
1428    Calling with no arguments::
1429
1430      >>> axis()
1431
1432    returns the current axes limits ``[xmin, xmax, ymin, ymax]``.::
1433
1434      >>> axis(v)
1435
1436    sets the min and max of the x and y axes, with
1437    ``v = [xmin, xmax, ymin, ymax]``.::
1438
1439      >>> axis('off')
1440
1441    turns off the axis lines and labels.::
1442
1443      >>> axis('equal')
1444
1445    changes limits of *x* or *y* axis so that equal increments of *x*
1446    and *y* have the same length; a circle is circular.::
1447
1448      >>> axis('scaled')
1449
1450    achieves the same result by changing the dimensions of the plot box instead
1451    of the axis data limits.::
1452
1453      >>> axis('tight')
1454
1455    changes *x* and *y* axis limits such that all data is shown. If
1456    all data is already shown, it will move it to the center of the
1457    figure without modifying (*xmax* - *xmin*) or (*ymax* -
1458    *ymin*). Note this is slightly different than in MATLAB.::
1459
1460      >>> axis('image')
1461
1462    is 'scaled' with the axis limits equal to the data limits.::
1463
1464      >>> axis('auto')
1465
1466    and::
1467
1468      >>> axis('normal')
1469
1470    are deprecated. They restore default behavior; axis limits are automatically
1471    scaled to make the data fit comfortably within the plot box.
1472
1473    if ``len(*v)==0``, you can pass in *xmin*, *xmax*, *ymin*, *ymax*
1474    as kwargs selectively to alter just those limits without changing
1475    the others.
1476
1477      >>> axis('square')
1478
1479    changes the limit ranges (*xmax*-*xmin*) and (*ymax*-*ymin*) of
1480    the *x* and *y* axes to be the same, and have the same scaling,
1481    resulting in a square plot.
1482
1483    The xmin, xmax, ymin, ymax tuple is returned
1484
1485    .. seealso::
1486
1487        :func:`xlim`, :func:`ylim`
1488           For setting the x- and y-limits individually.
1489    """
1490    return gca().axis(*v, **kwargs)
1491
1492
1493def xlabel(s, *args, **kwargs):
1494    """
1495    Set the x-axis label of the current axes.
1496
1497    Call signature::
1498
1499        xlabel(label, fontdict=None, labelpad=None, **kwargs)
1500
1501    This is the pyplot equivalent of calling `.set_xlabel` on the current axes.
1502    See there for a full parameter description.
1503    """
1504    return gca().set_xlabel(s, *args, **kwargs)
1505
1506
1507def ylabel(s, *args, **kwargs):
1508    """
1509    Set the y-axis label of the current axes.
1510
1511    Call signature::
1512
1513        ylabel(label, fontdict=None, labelpad=None, **kwargs)
1514
1515    This is the pyplot equivalent of calling `.set_ylabel` on the current axes.
1516    See there for a full parameter description.
1517    """
1518    return gca().set_ylabel(s, *args, **kwargs)
1519
1520
1521def xlim(*args, **kwargs):
1522    """
1523    Get or set the x limits of the current axes.
1524
1525    Call signatures::
1526
1527        xmin, xmax = xlim()  # return the current xlim
1528        xlim((xmin, xmax))   # set the xlim to xmin, xmax
1529        xlim(xmin, xmax)     # set the xlim to xmin, xmax
1530
1531    If you do not specify args, you can pass *xmin* or *xmax* as kwargs, i.e.::
1532
1533        xlim(xmax=3)  # adjust the max leaving min unchanged
1534        xlim(xmin=1)  # adjust the min leaving max unchanged
1535
1536    Setting limits turns autoscaling off for the x-axis.
1537
1538    Returns
1539    -------
1540    xmin, xmax
1541        A tuple of the new x-axis limits.
1542
1543    Notes
1544    -----
1545    Calling this function with no arguments (e.g. ``xlim()``) is the pyplot
1546    equivalent of calling `~.Axes.get_xlim` on the current axes.
1547    Calling this function with arguments is the pyplot equivalent of calling
1548    `~.Axes.set_xlim` on the current axes. All arguments are passed though.
1549    """
1550    ax = gca()
1551    if not args and not kwargs:
1552        return ax.get_xlim()
1553    ret = ax.set_xlim(*args, **kwargs)
1554    return ret
1555
1556
1557def ylim(*args, **kwargs):
1558    """
1559    Get or set the y-limits of the current axes.
1560
1561    Call signatures::
1562
1563        ymin, ymax = ylim()  # return the current ylim
1564        ylim((ymin, ymax))   # set the ylim to ymin, ymax
1565        ylim(ymin, ymax)     # set the ylim to ymin, ymax
1566
1567    If you do not specify args, you can alternatively pass *ymin* or *ymax* as
1568    kwargs, i.e.::
1569
1570        ylim(ymax=3)  # adjust the max leaving min unchanged
1571        ylim(ymin=1)  # adjust the min leaving max unchanged
1572
1573    Setting limits turns autoscaling off for the y-axis.
1574
1575    Returns
1576    -------
1577    ymin, ymax
1578        A tuple of the new y-axis limits.
1579
1580    Notes
1581    -----
1582    Calling this function with no arguments (e.g. ``ylim()``) is the pyplot
1583    equivalent of calling `~.Axes.get_ylim` on the current axes.
1584    Calling this function with arguments is the pyplot equivalent of calling
1585    `~.Axes.set_ylim` on the current axes. All arguments are passed though.
1586    """
1587    ax = gca()
1588    if not args and not kwargs:
1589        return ax.get_ylim()
1590    ret = ax.set_ylim(*args, **kwargs)
1591    return ret
1592
1593
1594@docstring.dedent_interpd
1595def xscale(*args, **kwargs):
1596    """
1597    Set the scaling of the x-axis.
1598
1599    Call signature::
1600
1601        xscale(scale, **kwargs)
1602
1603    Parameters
1604    ----------
1605    scale : [%(scale)s]
1606        The scaling type.
1607    **kwargs
1608        Additional parameters depend on *scale*. See Notes.
1609
1610    Notes
1611    -----
1612    This is the pyplot equivalent of calling `~.Axes.set_xscale` on the
1613    current axes.
1614
1615    Different keywords may be accepted, depending on the scale:
1616
1617    %(scale_docs)s
1618    """
1619    gca().set_xscale(*args, **kwargs)
1620
1621
1622@docstring.dedent_interpd
1623def yscale(*args, **kwargs):
1624    """
1625    Set the scaling of the y-axis.
1626
1627    Call signature::
1628
1629        yscale(scale, **kwargs)
1630
1631    Parameters
1632    ----------
1633    scale : [%(scale)s]
1634        The scaling type.
1635    **kwargs
1636        Additional parameters depend on *scale*. See Notes.
1637
1638    Notes
1639    -----
1640    This is the pyplot equivalent of calling `~.Axes.set_yscale` on the
1641    current axes.
1642
1643    Different keywords may be accepted, depending on the scale:
1644
1645    %(scale_docs)s
1646    """
1647    gca().set_yscale(*args, **kwargs)
1648
1649
1650def xticks(*args, **kwargs):
1651    """
1652    Get or set the current tick locations and labels of the x-axis.
1653
1654    Call signatures::
1655
1656        locs, labels = xticks()           # Get locations and labels
1657
1658        xticks(locs, [labels], **kwargs)  # Set locations and labels
1659
1660    Parameters
1661    ----------
1662    locs : array_like
1663        A list of positions at which ticks should be placed. You can pass an
1664        empty list to disable xticks.
1665
1666    labels : array_like, optional
1667        A list of explicit labels to place at the given *locs*.
1668
1669    **kwargs
1670        :class:`.Text` properties can be used to control the appearance of
1671        the labels.
1672
1673    Returns
1674    -------
1675    locs
1676        An array of label locations.
1677    labels
1678        A list of `.Text` objects.
1679
1680    Notes
1681    -----
1682    Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
1683    equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
1684    the current axes.
1685    Calling this function with arguments is the pyplot equivalent of calling
1686    `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
1687
1688    Examples
1689    --------
1690    Get the current locations and labels:
1691
1692        >>> locs, labels = xticks()
1693
1694    Set label locations:
1695
1696        >>> xticks(np.arange(0, 1, step=0.2))
1697
1698    Set text labels:
1699
1700        >>> xticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
1701
1702    Set text labels and properties:
1703
1704        >>> xticks(np.arange(12), calendar.month_name[1:13], rotation=20)
1705
1706    Disable xticks:
1707
1708        >>> xticks([])
1709    """
1710    ax = gca()
1711
1712    if len(args)==0:
1713        locs = ax.get_xticks()
1714        labels = ax.get_xticklabels()
1715    elif len(args)==1:
1716        locs = ax.set_xticks(args[0])
1717        labels = ax.get_xticklabels()
1718    elif len(args)==2:
1719        locs = ax.set_xticks(args[0])
1720        labels = ax.set_xticklabels(args[1], **kwargs)
1721    else: raise TypeError('Illegal number of arguments to xticks')
1722    if len(kwargs):
1723        for l in labels:
1724            l.update(kwargs)
1725
1726    return locs, silent_list('Text xticklabel', labels)
1727
1728
1729def yticks(*args, **kwargs):
1730    """
1731    Get or set the current tick locations and labels of the y-axis.
1732
1733    Call signatures::
1734
1735        locs, labels = yticks()           # Get locations and labels
1736
1737        yticks(locs, [labels], **kwargs)  # Set locations and labels
1738
1739    Parameters
1740    ----------
1741    locs : array_like
1742        A list of positions at which ticks should be placed. You can pass an
1743        empty list to disable yticks.
1744
1745    labels : array_like, optional
1746        A list of explicit labels to place at the given *locs*.
1747
1748    **kwargs
1749        :class:`.Text` properties can be used to control the appearance of
1750        the labels.
1751
1752    Returns
1753    -------
1754    locs
1755        An array of label locations.
1756    labels
1757        A list of `.Text` objects.
1758
1759    Notes
1760    -----
1761    Calling this function with no arguments (e.g. ``yticks()``) is the pyplot
1762    equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on
1763    the current axes.
1764    Calling this function with arguments is the pyplot equivalent of calling
1765    `~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current axes.
1766
1767    Examples
1768    --------
1769    Get the current locations and labels:
1770
1771        >>> locs, labels = yticks()
1772
1773    Set label locations:
1774
1775        >>> yticks(np.arange(0, 1, step=0.2))
1776
1777    Set text labels:
1778
1779        >>> yticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
1780
1781    Set text labels and properties:
1782
1783        >>> yticks(np.arange(12), calendar.month_name[1:13], rotation=45)
1784
1785    Disable yticks:
1786
1787        >>> yticks([])
1788    """
1789    ax = gca()
1790
1791    if len(args)==0:
1792        locs = ax.get_yticks()
1793        labels = ax.get_yticklabels()
1794    elif len(args)==1:
1795        locs = ax.set_yticks(args[0])
1796        labels = ax.get_yticklabels()
1797    elif len(args)==2:
1798        locs = ax.set_yticks(args[0])
1799        labels = ax.set_yticklabels(args[1], **kwargs)
1800    else: raise TypeError('Illegal number of arguments to yticks')
1801    if len(kwargs):
1802        for l in labels:
1803            l.update(kwargs)
1804
1805
1806    return ( locs,
1807             silent_list('Text yticklabel', labels)
1808             )
1809
1810
1811def minorticks_on():
1812    """
1813    Display minor ticks on the current plot.
1814
1815    Displaying minor ticks reduces performance; turn them off using
1816    minorticks_off() if drawing speed is a problem.
1817    """
1818    gca().minorticks_on()
1819
1820
1821def minorticks_off():
1822    """
1823    Remove minor ticks from the current plot.
1824    """
1825    gca().minorticks_off()
1826
1827
1828def rgrids(*args, **kwargs):
1829    """
1830    Get or set the radial gridlines on a polar plot.
1831
1832    call signatures::
1833
1834      lines, labels = rgrids()
1835      lines, labels = rgrids(radii, labels=None, angle=22.5, **kwargs)
1836
1837    When called with no arguments, :func:`rgrid` simply returns the
1838    tuple (*lines*, *labels*), where *lines* is an array of radial
1839    gridlines (:class:`~matplotlib.lines.Line2D` instances) and
1840    *labels* is an array of tick labels
1841    (:class:`~matplotlib.text.Text` instances). When called with
1842    arguments, the labels will appear at the specified radial
1843    distances and angles.
1844
1845    *labels*, if not *None*, is a len(*radii*) list of strings of the
1846    labels to use at each angle.
1847
1848    If *labels* is None, the rformatter will be used
1849
1850    Examples::
1851
1852      # set the locations of the radial gridlines and labels
1853      lines, labels = rgrids( (0.25, 0.5, 1.0) )
1854
1855      # set the locations and labels of the radial gridlines and labels
1856      lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' )
1857
1858    """
1859    ax = gca()
1860    if not isinstance(ax, PolarAxes):
1861        raise RuntimeError('rgrids only defined for polar axes')
1862    if len(args)==0:
1863        lines = ax.yaxis.get_gridlines()
1864        labels = ax.yaxis.get_ticklabels()
1865    else:
1866        lines, labels = ax.set_rgrids(*args, **kwargs)
1867
1868    return ( silent_list('Line2D rgridline', lines),
1869             silent_list('Text rgridlabel', labels) )
1870
1871
1872def thetagrids(*args, **kwargs):
1873    """
1874    Get or set the theta locations of the gridlines in a polar plot.
1875
1876    If no arguments are passed, return a tuple (*lines*, *labels*)
1877    where *lines* is an array of radial gridlines
1878    (:class:`~matplotlib.lines.Line2D` instances) and *labels* is an
1879    array of tick labels (:class:`~matplotlib.text.Text` instances)::
1880
1881      lines, labels = thetagrids()
1882
1883    Otherwise the syntax is::
1884
1885      lines, labels = thetagrids(angles, labels=None, fmt='%d', frac = 1.1)
1886
1887    set the angles at which to place the theta grids (these gridlines
1888    are equal along the theta dimension).
1889
1890    *angles* is in degrees.
1891
1892    *labels*, if not *None*, is a len(angles) list of strings of the
1893    labels to use at each angle.
1894
1895    If *labels* is *None*, the labels will be ``fmt%angle``.
1896
1897    *frac* is the fraction of the polar axes radius at which to place
1898    the label (1 is the edge). e.g., 1.05 is outside the axes and 0.95
1899    is inside the axes.
1900
1901    Return value is a list of tuples (*lines*, *labels*):
1902
1903      - *lines* are :class:`~matplotlib.lines.Line2D` instances
1904
1905      - *labels* are :class:`~matplotlib.text.Text` instances.
1906
1907    Note that on input, the *labels* argument is a list of strings,
1908    and on output it is a list of :class:`~matplotlib.text.Text`
1909    instances.
1910
1911    Examples::
1912
1913      # set the locations of the radial gridlines and labels
1914      lines, labels = thetagrids( range(45,360,90) )
1915
1916      # set the locations and labels of the radial gridlines and labels
1917      lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') )
1918    """
1919    ax = gca()
1920    if not isinstance(ax, PolarAxes):
1921        raise RuntimeError('rgrids only defined for polar axes')
1922    if len(args)==0:
1923        lines = ax.xaxis.get_ticklines()
1924        labels = ax.xaxis.get_ticklabels()
1925    else:
1926        lines, labels = ax.set_thetagrids(*args, **kwargs)
1927
1928    return (silent_list('Line2D thetagridline', lines),
1929            silent_list('Text thetagridlabel', labels)
1930            )
1931
1932
1933## Plotting Info ##
1934
1935def plotting():
1936    pass
1937
1938
1939def get_plot_commands():
1940    """
1941    Get a sorted list of all of the plotting commands.
1942    """
1943    # This works by searching for all functions in this module and
1944    # removing a few hard-coded exclusions, as well as all of the
1945    # colormap-setting functions, and anything marked as private with
1946    # a preceding underscore.
1947
1948    import inspect
1949
1950    exclude = {'colormaps', 'colors', 'connect', 'disconnect',
1951               'get_plot_commands', 'get_current_fig_manager', 'ginput',
1952               'plotting', 'waitforbuttonpress'}
1953    exclude |= set(colormaps())
1954    this_module = inspect.getmodule(get_plot_commands)
1955
1956    commands = set()
1957    for name, obj in list(six.iteritems(globals())):
1958        if name.startswith('_') or name in exclude:
1959            continue
1960        if inspect.isfunction(obj) and inspect.getmodule(obj) is this_module:
1961            commands.add(name)
1962
1963    return sorted(commands)
1964
1965
1966@deprecated('2.1')
1967def colors():
1968    """
1969    This is a do-nothing function to provide you with help on how
1970    matplotlib handles colors.
1971
1972    Commands which take color arguments can use several formats to
1973    specify the colors.  For the basic built-in colors, you can use a
1974    single letter
1975
1976      =====   =======
1977      Alias   Color
1978      =====   =======
1979      'b'     blue
1980      'g'     green
1981      'r'     red
1982      'c'     cyan
1983      'm'     magenta
1984      'y'     yellow
1985      'k'     black
1986      'w'     white
1987      =====   =======
1988
1989    For a greater range of colors, you have two options.  You can
1990    specify the color using an html hex string, as in::
1991
1992      color = '#eeefff'
1993
1994    or you can pass an R,G,B tuple, where each of R,G,B are in the
1995    range [0,1].
1996
1997    You can also use any legal html name for a color, for example::
1998
1999      color = 'red'
2000      color = 'burlywood'
2001      color = 'chartreuse'
2002
2003    The example below creates a subplot with a dark
2004    slate gray background::
2005
2006       subplot(111, facecolor=(0.1843, 0.3098, 0.3098))
2007
2008    Here is an example that creates a pale turquoise title::
2009
2010      title('Is this the best color?', color='#afeeee')
2011
2012    """
2013    pass
2014
2015
2016def colormaps():
2017    """
2018    Matplotlib provides a number of colormaps, and others can be added using
2019    :func:`~matplotlib.cm.register_cmap`.  This function documents the built-in
2020    colormaps, and will also return a list of all registered colormaps if called.
2021
2022    You can set the colormap for an image, pcolor, scatter, etc,
2023    using a keyword argument::
2024
2025      imshow(X, cmap=cm.hot)
2026
2027    or using the :func:`set_cmap` function::
2028
2029      imshow(X)
2030      pyplot.set_cmap('hot')
2031      pyplot.set_cmap('jet')
2032
2033    In interactive mode, :func:`set_cmap` will update the colormap post-hoc,
2034    allowing you to see which one works best for your data.
2035
2036    All built-in colormaps can be reversed by appending ``_r``: For instance,
2037    ``gray_r`` is the reverse of ``gray``.
2038
2039    There are several common color schemes used in visualization:
2040
2041    Sequential schemes
2042      for unipolar data that progresses from low to high
2043    Diverging schemes
2044      for bipolar data that emphasizes positive or negative deviations from a
2045      central value
2046    Cyclic schemes
2047      meant for plotting values that wrap around at the
2048      endpoints, such as phase angle, wind direction, or time of day
2049    Qualitative schemes
2050      for nominal data that has no inherent ordering, where color is used
2051      only to distinguish categories
2052
2053    Matplotlib ships with 4 perceptually uniform color maps which are
2054    the recommended color maps for sequential data:
2055
2056      =========   ===================================================
2057      Colormap    Description
2058      =========   ===================================================
2059      inferno     perceptually uniform shades of black-red-yellow
2060      magma       perceptually uniform shades of black-red-white
2061      plasma      perceptually uniform shades of blue-red-yellow
2062      viridis     perceptually uniform shades of blue-green-yellow
2063      =========   ===================================================
2064
2065    The following colormaps are based on the `ColorBrewer
2066    <http://colorbrewer2.org>`_ color specifications and designs developed by
2067    Cynthia Brewer:
2068
2069    ColorBrewer Diverging (luminance is highest at the midpoint, and
2070    decreases towards differently-colored endpoints):
2071
2072      ========  ===================================
2073      Colormap  Description
2074      ========  ===================================
2075      BrBG      brown, white, blue-green
2076      PiYG      pink, white, yellow-green
2077      PRGn      purple, white, green
2078      PuOr      orange, white, purple
2079      RdBu      red, white, blue
2080      RdGy      red, white, gray
2081      RdYlBu    red, yellow, blue
2082      RdYlGn    red, yellow, green
2083      Spectral  red, orange, yellow, green, blue
2084      ========  ===================================
2085
2086    ColorBrewer Sequential (luminance decreases monotonically):
2087
2088      ========  ====================================
2089      Colormap  Description
2090      ========  ====================================
2091      Blues     white to dark blue
2092      BuGn      white, light blue, dark green
2093      BuPu      white, light blue, dark purple
2094      GnBu      white, light green, dark blue
2095      Greens    white to dark green
2096      Greys     white to black (not linear)
2097      Oranges   white, orange, dark brown
2098      OrRd      white, orange, dark red
2099      PuBu      white, light purple, dark blue
2100      PuBuGn    white, light purple, dark green
2101      PuRd      white, light purple, dark red
2102      Purples   white to dark purple
2103      RdPu      white, pink, dark purple
2104      Reds      white to dark red
2105      YlGn      light yellow, dark green
2106      YlGnBu    light yellow, light green, dark blue
2107      YlOrBr    light yellow, orange, dark brown
2108      YlOrRd    light yellow, orange, dark red
2109      ========  ====================================
2110
2111    ColorBrewer Qualitative:
2112
2113    (For plotting nominal data, :class:`ListedColormap` is used,
2114    not :class:`LinearSegmentedColormap`.  Different sets of colors are
2115    recommended for different numbers of categories.)
2116
2117    * Accent
2118    * Dark2
2119    * Paired
2120    * Pastel1
2121    * Pastel2
2122    * Set1
2123    * Set2
2124    * Set3
2125
2126    A set of colormaps derived from those of the same name provided
2127    with Matlab are also included:
2128
2129      =========   =======================================================
2130      Colormap    Description
2131      =========   =======================================================
2132      autumn      sequential linearly-increasing shades of red-orange-yellow
2133      bone        sequential increasing black-white color map with
2134                  a tinge of blue, to emulate X-ray film
2135      cool        linearly-decreasing shades of cyan-magenta
2136      copper      sequential increasing shades of black-copper
2137      flag        repetitive red-white-blue-black pattern (not cyclic at
2138                  endpoints)
2139      gray        sequential linearly-increasing black-to-white
2140                  grayscale
2141      hot         sequential black-red-yellow-white, to emulate blackbody
2142                  radiation from an object at increasing temperatures
2143      hsv         cyclic red-yellow-green-cyan-blue-magenta-red, formed
2144                  by changing the hue component in the HSV color space
2145      jet         a spectral map with dark endpoints, blue-cyan-yellow-red;
2146                  based on a fluid-jet simulation by NCSA [#]_
2147      pink        sequential increasing pastel black-pink-white, meant
2148                  for sepia tone colorization of photographs
2149      prism       repetitive red-yellow-green-blue-purple-...-green pattern
2150                  (not cyclic at endpoints)
2151      spring      linearly-increasing shades of magenta-yellow
2152      summer      sequential linearly-increasing shades of green-yellow
2153      winter      linearly-increasing shades of blue-green
2154      =========   =======================================================
2155
2156    A set of palettes from the `Yorick scientific visualisation
2157    package <https://dhmunro.github.io/yorick-doc/>`_, an evolution of
2158    the GIST package, both by David H. Munro are included:
2159
2160      ============  =======================================================
2161      Colormap      Description
2162      ============  =======================================================
2163      gist_earth    mapmaker's colors from dark blue deep ocean to green
2164                    lowlands to brown highlands to white mountains
2165      gist_heat     sequential increasing black-red-orange-white, to emulate
2166                    blackbody radiation from an iron bar as it grows hotter
2167      gist_ncar     pseudo-spectral black-blue-green-yellow-red-purple-white
2168                    colormap from National Center for Atmospheric
2169                    Research [#]_
2170      gist_rainbow  runs through the colors in spectral order from red to
2171                    violet at full saturation (like *hsv* but not cyclic)
2172      gist_stern    "Stern special" color table from Interactive Data
2173                    Language software
2174      ============  =======================================================
2175
2176
2177    Other miscellaneous schemes:
2178
2179      ============= =======================================================
2180      Colormap      Description
2181      ============= =======================================================
2182      afmhot        sequential black-orange-yellow-white blackbody
2183                    spectrum, commonly used in atomic force microscopy
2184      brg           blue-red-green
2185      bwr           diverging blue-white-red
2186      coolwarm      diverging blue-gray-red, meant to avoid issues with 3D
2187                    shading, color blindness, and ordering of colors [#]_
2188      CMRmap        "Default colormaps on color images often reproduce to
2189                    confusing grayscale images. The proposed colormap
2190                    maintains an aesthetically pleasing color image that
2191                    automatically reproduces to a monotonic grayscale with
2192                    discrete, quantifiable saturation levels." [#]_
2193      cubehelix     Unlike most other color schemes cubehelix was designed
2194                    by D.A. Green to be monotonically increasing in terms
2195                    of perceived brightness. Also, when printed on a black
2196                    and white postscript printer, the scheme results in a
2197                    greyscale with monotonically increasing brightness.
2198                    This color scheme is named cubehelix because the r,g,b
2199                    values produced can be visualised as a squashed helix
2200                    around the diagonal in the r,g,b color cube.
2201      gnuplot       gnuplot's traditional pm3d scheme
2202                    (black-blue-red-yellow)
2203      gnuplot2      sequential color printable as gray
2204                    (black-blue-violet-yellow-white)
2205      ocean         green-blue-white
2206      rainbow       spectral purple-blue-green-yellow-orange-red colormap
2207                    with diverging luminance
2208      seismic       diverging blue-white-red
2209      nipy_spectral black-purple-blue-green-yellow-red-white spectrum,
2210                    originally from the Neuroimaging in Python project
2211      terrain       mapmaker's colors, blue-green-yellow-brown-white,
2212                    originally from IGOR Pro
2213      ============= =======================================================
2214
2215    The following colormaps are redundant and may be removed in future
2216    versions.  It's recommended to use the names in the descriptions
2217    instead, which produce identical output:
2218
2219      =========  =======================================================
2220      Colormap   Description
2221      =========  =======================================================
2222      gist_gray  identical to *gray*
2223      gist_yarg  identical to *gray_r*
2224      binary     identical to *gray_r*
2225      spectral   identical to *nipy_spectral* [#]_
2226      =========  =======================================================
2227
2228    .. rubric:: Footnotes
2229
2230    .. [#] Rainbow colormaps, ``jet`` in particular, are considered a poor
2231      choice for scientific visualization by many researchers: `Rainbow Color
2232      Map (Still) Considered Harmful
2233      <http://ieeexplore.ieee.org/document/4118486/?arnumber=4118486>`_
2234
2235    .. [#] Resembles "BkBlAqGrYeOrReViWh200" from NCAR Command
2236      Language. See `Color Table Gallery
2237      <https://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml>`_
2238
2239    .. [#] See `Diverging Color Maps for Scientific Visualization
2240      <http://www.kennethmoreland.com/color-maps/>`_ by Kenneth Moreland.
2241
2242    .. [#] See `A Color Map for Effective Black-and-White Rendering of
2243      Color-Scale Images
2244      <https://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m>`_
2245      by Carey Rappaport
2246
2247    .. [#] Changed to distinguish from ColorBrewer's *Spectral* map.
2248      :func:`spectral` still works, but
2249      ``set_cmap('nipy_spectral')`` is recommended for clarity.
2250
2251
2252    """
2253    return sorted(cm.cmap_d)
2254
2255
2256def _setup_pyplot_info_docstrings():
2257    """
2258    Generates the plotting and docstring.
2259
2260    These must be done after the entire module is imported, so it is
2261    called from the end of this module, which is generated by
2262    boilerplate.py.
2263    """
2264    # Generate the plotting docstring
2265    import re
2266
2267    def pad(s, l):
2268        """Pad string *s* to length *l*."""
2269        if l < len(s):
2270            return s[:l]
2271        return s + ' ' * (l - len(s))
2272
2273    commands = get_plot_commands()
2274
2275    first_sentence = re.compile(r"(?:\s*).+?\.(?:\s+|$)", flags=re.DOTALL)
2276
2277    # Collect the first sentence of the docstring for all of the
2278    # plotting commands.
2279    rows = []
2280    max_name = 0
2281    max_summary = 0
2282    for name in commands:
2283        doc = globals()[name].__doc__
2284        summary = ''
2285        if doc is not None:
2286            match = first_sentence.match(doc)
2287            if match is not None:
2288                summary = match.group(0).strip().replace('\n', ' ')
2289        name = '`%s`' % name
2290        rows.append([name, summary])
2291        max_name = max(max_name, len(name))
2292        max_summary = max(max_summary, len(summary))
2293
2294    lines = []
2295    sep = '=' * max_name + ' ' + '=' * max_summary
2296    lines.append(sep)
2297    lines.append(' '.join([pad("Function", max_name),
2298                           pad("Description", max_summary)]))
2299    lines.append(sep)
2300    for name, summary in rows:
2301        lines.append(' '.join([pad(name, max_name),
2302                               pad(summary, max_summary)]))
2303    lines.append(sep)
2304
2305    plotting.__doc__ = '\n'.join(lines)
2306
2307## Plotting part 1: manually generated functions and wrappers ##
2308
2309def colorbar(mappable=None, cax=None, ax=None, **kw):
2310    if mappable is None:
2311        mappable = gci()
2312        if mappable is None:
2313            raise RuntimeError('No mappable was found to use for colorbar '
2314                               'creation. First define a mappable such as '
2315                               'an image (with imshow) or a contour set ('
2316                               'with contourf).')
2317    if ax is None:
2318        ax = gca()
2319
2320    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
2321    return ret
2322colorbar.__doc__ = matplotlib.colorbar.colorbar_doc
2323
2324
2325def clim(vmin=None, vmax=None):
2326    """
2327    Set the color limits of the current image.
2328
2329    To apply clim to all axes images do::
2330
2331      clim(0, 0.5)
2332
2333    If either *vmin* or *vmax* is None, the image min/max respectively
2334    will be used for color scaling.
2335
2336    If you want to set the clim of multiple images,
2337    use, for example::
2338
2339      for im in gca().get_images():
2340          im.set_clim(0, 0.05)
2341
2342    """
2343    im = gci()
2344    if im is None:
2345        raise RuntimeError('You must first define an image, e.g., with imshow')
2346
2347    im.set_clim(vmin, vmax)
2348
2349
2350def set_cmap(cmap):
2351    """
2352    Set the default colormap.  Applies to the current image if any.
2353    See help(colormaps) for more information.
2354
2355    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
2356    the name of a registered colormap.
2357
2358    See :func:`matplotlib.cm.register_cmap` and
2359    :func:`matplotlib.cm.get_cmap`.
2360    """
2361    cmap = cm.get_cmap(cmap)
2362
2363    rc('image', cmap=cmap.name)
2364    im = gci()
2365
2366    if im is not None:
2367        im.set_cmap(cmap)
2368
2369
2370
2371@docstring.copy_dedent(_imread)
2372def imread(*args, **kwargs):
2373    return _imread(*args, **kwargs)
2374
2375
2376@docstring.copy_dedent(_imsave)
2377def imsave(*args, **kwargs):
2378    return _imsave(*args, **kwargs)
2379
2380
2381def matshow(A, fignum=None, **kwargs):
2382    """
2383    Display an array as a matrix in a new figure window.
2384
2385    The origin is set at the upper left hand corner and rows (first
2386    dimension of the array) are displayed horizontally.  The aspect
2387    ratio of the figure window is that of the array, unless this would
2388    make an excessively short or narrow figure.
2389
2390    Tick labels for the xaxis are placed on top.
2391
2392    Parameters
2393    ----------
2394    A : array-like(M, N)
2395        The matrix to be displayed.
2396
2397    fignum : None or int or False
2398        If *None*, create a new figure window with automatic numbering.
2399
2400        If *fignum* is an integer, draw into the figure with the given number
2401        (create it if it does not exist).
2402
2403        If 0 or *False*, use the current axes if it exists instead of creating
2404        a new figure.
2405
2406        .. note::
2407
2408           Because of how `.Axes.matshow` tries to set the figure aspect
2409           ratio to be the one of the array, strange things may happen if you
2410           reuse an existing figure.
2411
2412    Returns
2413    -------
2414    image : `~matplotlib.image.AxesImage`
2415
2416    Other Parameters
2417    ----------------
2418    **kwargs : `~matplotlib.axes.Axes.imshow` arguments
2419
2420    """
2421    A = np.asanyarray(A)
2422    if fignum is False or fignum is 0:
2423        ax = gca()
2424    else:
2425        # Extract actual aspect ratio of array and make appropriately sized figure
2426        fig = figure(fignum, figsize=figaspect(A))
2427        ax  = fig.add_axes([0.15, 0.09, 0.775, 0.775])
2428
2429    im = ax.matshow(A, **kwargs)
2430    sci(im)
2431
2432    return im
2433
2434
2435def polar(*args, **kwargs):
2436    """
2437    Make a polar plot.
2438
2439    call signature::
2440
2441      polar(theta, r, **kwargs)
2442
2443    Multiple *theta*, *r* arguments are supported, with format
2444    strings, as in :func:`~matplotlib.pyplot.plot`.
2445
2446    """
2447    # If an axis already exists, check if it has a polar projection
2448    if gcf().get_axes():
2449        if not isinstance(gca(), PolarAxes):
2450            warnings.warn('Trying to create polar plot on an axis that does '
2451                          'not have a polar projection.')
2452    ax = gca(polar=True)
2453    ret = ax.plot(*args, **kwargs)
2454    return ret
2455
2456
2457def plotfile(fname, cols=(0,), plotfuncs=None,
2458             comments='#', skiprows=0, checkrows=5, delimiter=',',
2459             names=None, subplots=True, newfig=True, **kwargs):
2460    """
2461    Plot the data in a file.
2462
2463    *cols* is a sequence of column identifiers to plot.  An identifier
2464    is either an int or a string.  If it is an int, it indicates the
2465    column number.  If it is a string, it indicates the column header.
2466    matplotlib will make column headers lower case, replace spaces with
2467    underscores, and remove all illegal characters; so ``'Adj Close*'``
2468    will have name ``'adj_close'``.
2469
2470    - If len(*cols*) == 1, only that column will be plotted on the *y* axis.
2471
2472    - If len(*cols*) > 1, the first element will be an identifier for
2473      data for the *x* axis and the remaining elements will be the
2474      column indexes for multiple subplots if *subplots* is *True*
2475      (the default), or for lines in a single subplot if *subplots*
2476      is *False*.
2477
2478    *plotfuncs*, if not *None*, is a dictionary mapping identifier to
2479    an :class:`~matplotlib.axes.Axes` plotting function as a string.
2480    Default is 'plot', other choices are 'semilogy', 'fill', 'bar',
2481    etc.  You must use the same type of identifier in the *cols*
2482    vector as you use in the *plotfuncs* dictionary, e.g., integer
2483    column numbers in both or column names in both. If *subplots*
2484    is *False*, then including any function such as 'semilogy'
2485    that changes the axis scaling will set the scaling for all
2486    columns.
2487
2488    *comments*, *skiprows*, *checkrows*, *delimiter*, and *names*
2489    are all passed on to :func:`matplotlib.pylab.csv2rec` to
2490    load the data into a record array.
2491
2492    If *newfig* is *True*, the plot always will be made in a new figure;
2493    if *False*, it will be made in the current figure if one exists,
2494    else in a new figure.
2495
2496    kwargs are passed on to plotting functions.
2497
2498    Example usage::
2499
2500      # plot the 2nd and 4th column against the 1st in two subplots
2501      plotfile(fname, (0,1,3))
2502
2503      # plot using column names; specify an alternate plot type for volume
2504      plotfile(fname, ('date', 'volume', 'adj_close'),
2505                                    plotfuncs={'volume': 'semilogy'})
2506
2507    Note: plotfile is intended as a convenience for quickly plotting
2508    data from flat files; it is not intended as an alternative
2509    interface to general plotting with pyplot or matplotlib.
2510    """
2511
2512    if newfig:
2513        fig = figure()
2514    else:
2515        fig = gcf()
2516
2517    if len(cols)<1:
2518        raise ValueError('must have at least one column of data')
2519
2520    if plotfuncs is None:
2521        plotfuncs = dict()
2522    from matplotlib.cbook import mplDeprecation
2523    with warnings.catch_warnings():
2524        warnings.simplefilter('ignore', mplDeprecation)
2525        r = mlab.csv2rec(fname, comments=comments, skiprows=skiprows,
2526                         checkrows=checkrows, delimiter=delimiter, names=names)
2527
2528    def getname_val(identifier):
2529        'return the name and column data for identifier'
2530        if isinstance(identifier, six.string_types):
2531            return identifier, r[identifier]
2532        elif is_numlike(identifier):
2533            name = r.dtype.names[int(identifier)]
2534            return name, r[name]
2535        else:
2536            raise TypeError('identifier must be a string or integer')
2537
2538    xname, x = getname_val(cols[0])
2539    ynamelist = []
2540
2541    if len(cols)==1:
2542        ax1 = fig.add_subplot(1,1,1)
2543        funcname = plotfuncs.get(cols[0], 'plot')
2544        func = getattr(ax1, funcname)
2545        func(x, **kwargs)
2546        ax1.set_ylabel(xname)
2547    else:
2548        N = len(cols)
2549        for i in range(1,N):
2550            if subplots:
2551                if i==1:
2552                    ax = ax1 = fig.add_subplot(N-1,1,i)
2553                else:
2554                    ax = fig.add_subplot(N-1,1,i, sharex=ax1)
2555            elif i==1:
2556                ax = fig.add_subplot(1,1,1)
2557
2558            yname, y = getname_val(cols[i])
2559            ynamelist.append(yname)
2560
2561            funcname = plotfuncs.get(cols[i], 'plot')
2562            func = getattr(ax, funcname)
2563
2564            func(x, y, **kwargs)
2565            if subplots:
2566                ax.set_ylabel(yname)
2567            if ax.is_last_row():
2568                ax.set_xlabel(xname)
2569            else:
2570                ax.set_xlabel('')
2571
2572    if not subplots:
2573        ax.legend(ynamelist, loc='best')
2574
2575    if xname=='date':
2576        fig.autofmt_xdate()
2577
2578
2579def _autogen_docstring(base):
2580    """Autogenerated wrappers will get their docstring from a base function
2581    with an addendum."""
2582    #msg = "\n\nAdditional kwargs: hold = [True|False] overrides default hold state"
2583    msg = ''
2584    addendum = docstring.Appender(msg, '\n\n')
2585    return lambda func: addendum(docstring.copy_dedent(base)(func))
2586
2587# This function cannot be generated by boilerplate.py because it may
2588# return an image or a line.
2589@_autogen_docstring(Axes.spy)
2590def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', **kwargs):
2591    ax = gca()
2592    hold = kwargs.pop('hold', None)
2593    # allow callers to override the hold state by passing hold=True|False
2594    washold = ax._hold
2595
2596    if hold is not None:
2597        ax._hold = hold
2598        from matplotlib.cbook import mplDeprecation
2599        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2600                      mplDeprecation)
2601    try:
2602        ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs)
2603    finally:
2604        ax._hold = washold
2605    if isinstance(ret, cm.ScalarMappable):
2606        sci(ret)
2607    return ret
2608
2609# just to be safe.  Interactive mode can be turned on without
2610# calling `plt.ion()` so register it again here.
2611# This is safe because multiple calls to `install_repl_displayhook`
2612# are no-ops and the registered function respect `mpl.is_interactive()`
2613# to determine if they should trigger a draw.
2614install_repl_displayhook()
2615
2616################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
2617
2618
2619# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2620@_autogen_docstring(Axes.acorr)
2621def acorr(x, hold=None, data=None, **kwargs):
2622    ax = gca()
2623    # Deprecated: allow callers to override the hold state
2624    # by passing hold=True|False
2625    washold = ax._hold
2626
2627    if hold is not None:
2628        ax._hold = hold
2629        from matplotlib.cbook import mplDeprecation
2630        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2631                      mplDeprecation)
2632    try:
2633        ret = ax.acorr(x, data=data, **kwargs)
2634    finally:
2635        ax._hold = washold
2636
2637    return ret
2638
2639# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2640@_autogen_docstring(Axes.angle_spectrum)
2641def angle_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None,
2642                   hold=None, data=None, **kwargs):
2643    ax = gca()
2644    # Deprecated: allow callers to override the hold state
2645    # by passing hold=True|False
2646    washold = ax._hold
2647
2648    if hold is not None:
2649        ax._hold = hold
2650        from matplotlib.cbook import mplDeprecation
2651        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2652                      mplDeprecation)
2653    try:
2654        ret = ax.angle_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to,
2655                                sides=sides, data=data, **kwargs)
2656    finally:
2657        ax._hold = washold
2658
2659    return ret
2660
2661# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2662@_autogen_docstring(Axes.arrow)
2663def arrow(x, y, dx, dy, hold=None, **kwargs):
2664    ax = gca()
2665    # Deprecated: allow callers to override the hold state
2666    # by passing hold=True|False
2667    washold = ax._hold
2668
2669    if hold is not None:
2670        ax._hold = hold
2671        from matplotlib.cbook import mplDeprecation
2672        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2673                      mplDeprecation)
2674    try:
2675        ret = ax.arrow(x, y, dx, dy, **kwargs)
2676    finally:
2677        ax._hold = washold
2678
2679    return ret
2680
2681# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2682@_autogen_docstring(Axes.axhline)
2683def axhline(y=0, xmin=0, xmax=1, hold=None, **kwargs):
2684    ax = gca()
2685    # Deprecated: allow callers to override the hold state
2686    # by passing hold=True|False
2687    washold = ax._hold
2688
2689    if hold is not None:
2690        ax._hold = hold
2691        from matplotlib.cbook import mplDeprecation
2692        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2693                      mplDeprecation)
2694    try:
2695        ret = ax.axhline(y=y, xmin=xmin, xmax=xmax, **kwargs)
2696    finally:
2697        ax._hold = washold
2698
2699    return ret
2700
2701# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2702@_autogen_docstring(Axes.axhspan)
2703def axhspan(ymin, ymax, xmin=0, xmax=1, hold=None, **kwargs):
2704    ax = gca()
2705    # Deprecated: allow callers to override the hold state
2706    # by passing hold=True|False
2707    washold = ax._hold
2708
2709    if hold is not None:
2710        ax._hold = hold
2711        from matplotlib.cbook import mplDeprecation
2712        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2713                      mplDeprecation)
2714    try:
2715        ret = ax.axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs)
2716    finally:
2717        ax._hold = washold
2718
2719    return ret
2720
2721# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2722@_autogen_docstring(Axes.axvline)
2723def axvline(x=0, ymin=0, ymax=1, hold=None, **kwargs):
2724    ax = gca()
2725    # Deprecated: allow callers to override the hold state
2726    # by passing hold=True|False
2727    washold = ax._hold
2728
2729    if hold is not None:
2730        ax._hold = hold
2731        from matplotlib.cbook import mplDeprecation
2732        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2733                      mplDeprecation)
2734    try:
2735        ret = ax.axvline(x=x, ymin=ymin, ymax=ymax, **kwargs)
2736    finally:
2737        ax._hold = washold
2738
2739    return ret
2740
2741# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2742@_autogen_docstring(Axes.axvspan)
2743def axvspan(xmin, xmax, ymin=0, ymax=1, hold=None, **kwargs):
2744    ax = gca()
2745    # Deprecated: allow callers to override the hold state
2746    # by passing hold=True|False
2747    washold = ax._hold
2748
2749    if hold is not None:
2750        ax._hold = hold
2751        from matplotlib.cbook import mplDeprecation
2752        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2753                      mplDeprecation)
2754    try:
2755        ret = ax.axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)
2756    finally:
2757        ax._hold = washold
2758
2759    return ret
2760
2761# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2762@_autogen_docstring(Axes.bar)
2763def bar(*args, **kwargs):
2764    ax = gca()
2765    # Deprecated: allow callers to override the hold state
2766    # by passing hold=True|False
2767    washold = ax._hold
2768    hold = kwargs.pop('hold', None)
2769    if hold is not None:
2770        ax._hold = hold
2771        from matplotlib.cbook import mplDeprecation
2772        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2773                      mplDeprecation)
2774    try:
2775        ret = ax.bar(*args, **kwargs)
2776    finally:
2777        ax._hold = washold
2778
2779    return ret
2780
2781# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2782@_autogen_docstring(Axes.barh)
2783def barh(*args, **kwargs):
2784    ax = gca()
2785    # Deprecated: allow callers to override the hold state
2786    # by passing hold=True|False
2787    washold = ax._hold
2788    hold = kwargs.pop('hold', None)
2789    if hold is not None:
2790        ax._hold = hold
2791        from matplotlib.cbook import mplDeprecation
2792        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2793                      mplDeprecation)
2794    try:
2795        ret = ax.barh(*args, **kwargs)
2796    finally:
2797        ax._hold = washold
2798
2799    return ret
2800
2801# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2802@_autogen_docstring(Axes.broken_barh)
2803def broken_barh(xranges, yrange, hold=None, data=None, **kwargs):
2804    ax = gca()
2805    # Deprecated: allow callers to override the hold state
2806    # by passing hold=True|False
2807    washold = ax._hold
2808
2809    if hold is not None:
2810        ax._hold = hold
2811        from matplotlib.cbook import mplDeprecation
2812        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2813                      mplDeprecation)
2814    try:
2815        ret = ax.broken_barh(xranges, yrange, data=data, **kwargs)
2816    finally:
2817        ax._hold = washold
2818
2819    return ret
2820
2821# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2822@_autogen_docstring(Axes.boxplot)
2823def boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None,
2824            widths=None, patch_artist=None, bootstrap=None, usermedians=None,
2825            conf_intervals=None, meanline=None, showmeans=None, showcaps=None,
2826            showbox=None, showfliers=None, boxprops=None, labels=None,
2827            flierprops=None, medianprops=None, meanprops=None, capprops=None,
2828            whiskerprops=None, manage_xticks=True, autorange=False, zorder=None,
2829            hold=None, data=None):
2830    ax = gca()
2831    # Deprecated: allow callers to override the hold state
2832    # by passing hold=True|False
2833    washold = ax._hold
2834
2835    if hold is not None:
2836        ax._hold = hold
2837        from matplotlib.cbook import mplDeprecation
2838        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2839                      mplDeprecation)
2840    try:
2841        ret = ax.boxplot(x, notch=notch, sym=sym, vert=vert, whis=whis,
2842                         positions=positions, widths=widths,
2843                         patch_artist=patch_artist, bootstrap=bootstrap,
2844                         usermedians=usermedians,
2845                         conf_intervals=conf_intervals, meanline=meanline,
2846                         showmeans=showmeans, showcaps=showcaps,
2847                         showbox=showbox, showfliers=showfliers,
2848                         boxprops=boxprops, labels=labels,
2849                         flierprops=flierprops, medianprops=medianprops,
2850                         meanprops=meanprops, capprops=capprops,
2851                         whiskerprops=whiskerprops,
2852                         manage_xticks=manage_xticks, autorange=autorange,
2853                         zorder=zorder, data=data)
2854    finally:
2855        ax._hold = washold
2856
2857    return ret
2858
2859# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2860@_autogen_docstring(Axes.cohere)
2861def cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
2862           window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default',
2863           scale_by_freq=None, hold=None, data=None, **kwargs):
2864    ax = gca()
2865    # Deprecated: allow callers to override the hold state
2866    # by passing hold=True|False
2867    washold = ax._hold
2868
2869    if hold is not None:
2870        ax._hold = hold
2871        from matplotlib.cbook import mplDeprecation
2872        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2873                      mplDeprecation)
2874    try:
2875        ret = ax.cohere(x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend,
2876                        window=window, noverlap=noverlap, pad_to=pad_to,
2877                        sides=sides, scale_by_freq=scale_by_freq, data=data,
2878                        **kwargs)
2879    finally:
2880        ax._hold = washold
2881
2882    return ret
2883
2884# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2885@_autogen_docstring(Axes.clabel)
2886def clabel(CS, *args, **kwargs):
2887    ax = gca()
2888    # Deprecated: allow callers to override the hold state
2889    # by passing hold=True|False
2890    washold = ax._hold
2891    hold = kwargs.pop('hold', None)
2892    if hold is not None:
2893        ax._hold = hold
2894        from matplotlib.cbook import mplDeprecation
2895        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2896                      mplDeprecation)
2897    try:
2898        ret = ax.clabel(CS, *args, **kwargs)
2899    finally:
2900        ax._hold = washold
2901
2902    return ret
2903
2904# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2905@_autogen_docstring(Axes.contour)
2906def contour(*args, **kwargs):
2907    ax = gca()
2908    # Deprecated: allow callers to override the hold state
2909    # by passing hold=True|False
2910    washold = ax._hold
2911    hold = kwargs.pop('hold', None)
2912    if hold is not None:
2913        ax._hold = hold
2914        from matplotlib.cbook import mplDeprecation
2915        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2916                      mplDeprecation)
2917    try:
2918        ret = ax.contour(*args, **kwargs)
2919    finally:
2920        ax._hold = washold
2921    if ret._A is not None: sci(ret)
2922    return ret
2923
2924# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2925@_autogen_docstring(Axes.contourf)
2926def contourf(*args, **kwargs):
2927    ax = gca()
2928    # Deprecated: allow callers to override the hold state
2929    # by passing hold=True|False
2930    washold = ax._hold
2931    hold = kwargs.pop('hold', None)
2932    if hold is not None:
2933        ax._hold = hold
2934        from matplotlib.cbook import mplDeprecation
2935        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2936                      mplDeprecation)
2937    try:
2938        ret = ax.contourf(*args, **kwargs)
2939    finally:
2940        ax._hold = washold
2941    if ret._A is not None: sci(ret)
2942    return ret
2943
2944# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2945@_autogen_docstring(Axes.csd)
2946def csd(x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
2947        noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
2948        return_line=None, hold=None, data=None, **kwargs):
2949    ax = gca()
2950    # Deprecated: allow callers to override the hold state
2951    # by passing hold=True|False
2952    washold = ax._hold
2953
2954    if hold is not None:
2955        ax._hold = hold
2956        from matplotlib.cbook import mplDeprecation
2957        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2958                      mplDeprecation)
2959    try:
2960        ret = ax.csd(x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend,
2961                     window=window, noverlap=noverlap, pad_to=pad_to,
2962                     sides=sides, scale_by_freq=scale_by_freq,
2963                     return_line=return_line, data=data, **kwargs)
2964    finally:
2965        ax._hold = washold
2966
2967    return ret
2968
2969# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2970@_autogen_docstring(Axes.errorbar)
2971def errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None,
2972             capsize=None, barsabove=False, lolims=False, uplims=False,
2973             xlolims=False, xuplims=False, errorevery=1, capthick=None,
2974             hold=None, data=None, **kwargs):
2975    ax = gca()
2976    # Deprecated: allow callers to override the hold state
2977    # by passing hold=True|False
2978    washold = ax._hold
2979
2980    if hold is not None:
2981        ax._hold = hold
2982        from matplotlib.cbook import mplDeprecation
2983        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
2984                      mplDeprecation)
2985    try:
2986        ret = ax.errorbar(x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor,
2987                          elinewidth=elinewidth, capsize=capsize,
2988                          barsabove=barsabove, lolims=lolims, uplims=uplims,
2989                          xlolims=xlolims, xuplims=xuplims,
2990                          errorevery=errorevery, capthick=capthick, data=data,
2991                          **kwargs)
2992    finally:
2993        ax._hold = washold
2994
2995    return ret
2996
2997# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
2998@_autogen_docstring(Axes.eventplot)
2999def eventplot(positions, orientation='horizontal', lineoffsets=1, linelengths=1,
3000              linewidths=None, colors=None, linestyles='solid', hold=None,
3001              data=None, **kwargs):
3002    ax = gca()
3003    # Deprecated: allow callers to override the hold state
3004    # by passing hold=True|False
3005    washold = ax._hold
3006
3007    if hold is not None:
3008        ax._hold = hold
3009        from matplotlib.cbook import mplDeprecation
3010        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3011                      mplDeprecation)
3012    try:
3013        ret = ax.eventplot(positions, orientation=orientation,
3014                           lineoffsets=lineoffsets, linelengths=linelengths,
3015                           linewidths=linewidths, colors=colors,
3016                           linestyles=linestyles, data=data, **kwargs)
3017    finally:
3018        ax._hold = washold
3019
3020    return ret
3021
3022# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3023@_autogen_docstring(Axes.fill)
3024def fill(*args, **kwargs):
3025    ax = gca()
3026    # Deprecated: allow callers to override the hold state
3027    # by passing hold=True|False
3028    washold = ax._hold
3029    hold = kwargs.pop('hold', None)
3030    if hold is not None:
3031        ax._hold = hold
3032        from matplotlib.cbook import mplDeprecation
3033        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3034                      mplDeprecation)
3035    try:
3036        ret = ax.fill(*args, **kwargs)
3037    finally:
3038        ax._hold = washold
3039
3040    return ret
3041
3042# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3043@_autogen_docstring(Axes.fill_between)
3044def fill_between(x, y1, y2=0, where=None, interpolate=False, step=None,
3045                 hold=None, data=None, **kwargs):
3046    ax = gca()
3047    # Deprecated: allow callers to override the hold state
3048    # by passing hold=True|False
3049    washold = ax._hold
3050
3051    if hold is not None:
3052        ax._hold = hold
3053        from matplotlib.cbook import mplDeprecation
3054        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3055                      mplDeprecation)
3056    try:
3057        ret = ax.fill_between(x, y1, y2=y2, where=where,
3058                              interpolate=interpolate, step=step, data=data,
3059                              **kwargs)
3060    finally:
3061        ax._hold = washold
3062
3063    return ret
3064
3065# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3066@_autogen_docstring(Axes.fill_betweenx)
3067def fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False,
3068                  hold=None, data=None, **kwargs):
3069    ax = gca()
3070    # Deprecated: allow callers to override the hold state
3071    # by passing hold=True|False
3072    washold = ax._hold
3073
3074    if hold is not None:
3075        ax._hold = hold
3076        from matplotlib.cbook import mplDeprecation
3077        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3078                      mplDeprecation)
3079    try:
3080        ret = ax.fill_betweenx(y, x1, x2=x2, where=where, step=step,
3081                               interpolate=interpolate, data=data, **kwargs)
3082    finally:
3083        ax._hold = washold
3084
3085    return ret
3086
3087# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3088@_autogen_docstring(Axes.hexbin)
3089def hexbin(x, y, C=None, gridsize=100, bins=None, xscale='linear',
3090           yscale='linear', extent=None, cmap=None, norm=None, vmin=None,
3091           vmax=None, alpha=None, linewidths=None, edgecolors='face',
3092           reduce_C_function=np.mean, mincnt=None, marginals=False, hold=None,
3093           data=None, **kwargs):
3094    ax = gca()
3095    # Deprecated: allow callers to override the hold state
3096    # by passing hold=True|False
3097    washold = ax._hold
3098
3099    if hold is not None:
3100        ax._hold = hold
3101        from matplotlib.cbook import mplDeprecation
3102        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3103                      mplDeprecation)
3104    try:
3105        ret = ax.hexbin(x, y, C=C, gridsize=gridsize, bins=bins, xscale=xscale,
3106                        yscale=yscale, extent=extent, cmap=cmap, norm=norm,
3107                        vmin=vmin, vmax=vmax, alpha=alpha,
3108                        linewidths=linewidths, edgecolors=edgecolors,
3109                        reduce_C_function=reduce_C_function, mincnt=mincnt,
3110                        marginals=marginals, data=data, **kwargs)
3111    finally:
3112        ax._hold = washold
3113    sci(ret)
3114    return ret
3115
3116# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3117@_autogen_docstring(Axes.hist)
3118def hist(x, bins=None, range=None, density=None, weights=None, cumulative=False,
3119         bottom=None, histtype='bar', align='mid', orientation='vertical',
3120         rwidth=None, log=False, color=None, label=None, stacked=False,
3121         normed=None, hold=None, data=None, **kwargs):
3122    ax = gca()
3123    # Deprecated: allow callers to override the hold state
3124    # by passing hold=True|False
3125    washold = ax._hold
3126
3127    if hold is not None:
3128        ax._hold = hold
3129        from matplotlib.cbook import mplDeprecation
3130        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3131                      mplDeprecation)
3132    try:
3133        ret = ax.hist(x, bins=bins, range=range, density=density,
3134                      weights=weights, cumulative=cumulative, bottom=bottom,
3135                      histtype=histtype, align=align, orientation=orientation,
3136                      rwidth=rwidth, log=log, color=color, label=label,
3137                      stacked=stacked, normed=normed, data=data, **kwargs)
3138    finally:
3139        ax._hold = washold
3140
3141    return ret
3142
3143# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3144@_autogen_docstring(Axes.hist2d)
3145def hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None,
3146           cmax=None, hold=None, data=None, **kwargs):
3147    ax = gca()
3148    # Deprecated: allow callers to override the hold state
3149    # by passing hold=True|False
3150    washold = ax._hold
3151
3152    if hold is not None:
3153        ax._hold = hold
3154        from matplotlib.cbook import mplDeprecation
3155        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3156                      mplDeprecation)
3157    try:
3158        ret = ax.hist2d(x, y, bins=bins, range=range, normed=normed,
3159                        weights=weights, cmin=cmin, cmax=cmax, data=data,
3160                        **kwargs)
3161    finally:
3162        ax._hold = washold
3163    sci(ret[-1])
3164    return ret
3165
3166# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3167@_autogen_docstring(Axes.hlines)
3168def hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', hold=None,
3169           data=None, **kwargs):
3170    ax = gca()
3171    # Deprecated: allow callers to override the hold state
3172    # by passing hold=True|False
3173    washold = ax._hold
3174
3175    if hold is not None:
3176        ax._hold = hold
3177        from matplotlib.cbook import mplDeprecation
3178        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3179                      mplDeprecation)
3180    try:
3181        ret = ax.hlines(y, xmin, xmax, colors=colors, linestyles=linestyles,
3182                        label=label, data=data, **kwargs)
3183    finally:
3184        ax._hold = washold
3185
3186    return ret
3187
3188# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3189@_autogen_docstring(Axes.imshow)
3190def imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None,
3191           vmin=None, vmax=None, origin=None, extent=None, shape=None,
3192           filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None,
3193           hold=None, data=None, **kwargs):
3194    ax = gca()
3195    # Deprecated: allow callers to override the hold state
3196    # by passing hold=True|False
3197    washold = ax._hold
3198
3199    if hold is not None:
3200        ax._hold = hold
3201        from matplotlib.cbook import mplDeprecation
3202        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3203                      mplDeprecation)
3204    try:
3205        ret = ax.imshow(X, cmap=cmap, norm=norm, aspect=aspect,
3206                        interpolation=interpolation, alpha=alpha, vmin=vmin,
3207                        vmax=vmax, origin=origin, extent=extent, shape=shape,
3208                        filternorm=filternorm, filterrad=filterrad,
3209                        imlim=imlim, resample=resample, url=url, data=data,
3210                        **kwargs)
3211    finally:
3212        ax._hold = washold
3213    sci(ret)
3214    return ret
3215
3216# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3217@_autogen_docstring(Axes.loglog)
3218def loglog(*args, **kwargs):
3219    ax = gca()
3220    # Deprecated: allow callers to override the hold state
3221    # by passing hold=True|False
3222    washold = ax._hold
3223    hold = kwargs.pop('hold', None)
3224    if hold is not None:
3225        ax._hold = hold
3226        from matplotlib.cbook import mplDeprecation
3227        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3228                      mplDeprecation)
3229    try:
3230        ret = ax.loglog(*args, **kwargs)
3231    finally:
3232        ax._hold = washold
3233
3234    return ret
3235
3236# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3237@_autogen_docstring(Axes.magnitude_spectrum)
3238def magnitude_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None,
3239                       sides=None, scale=None, hold=None, data=None, **kwargs):
3240    ax = gca()
3241    # Deprecated: allow callers to override the hold state
3242    # by passing hold=True|False
3243    washold = ax._hold
3244
3245    if hold is not None:
3246        ax._hold = hold
3247        from matplotlib.cbook import mplDeprecation
3248        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3249                      mplDeprecation)
3250    try:
3251        ret = ax.magnitude_spectrum(x, Fs=Fs, Fc=Fc, window=window,
3252                                    pad_to=pad_to, sides=sides, scale=scale,
3253                                    data=data, **kwargs)
3254    finally:
3255        ax._hold = washold
3256
3257    return ret
3258
3259# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3260@_autogen_docstring(Axes.pcolor)
3261def pcolor(*args, **kwargs):
3262    ax = gca()
3263    # Deprecated: allow callers to override the hold state
3264    # by passing hold=True|False
3265    washold = ax._hold
3266    hold = kwargs.pop('hold', None)
3267    if hold is not None:
3268        ax._hold = hold
3269        from matplotlib.cbook import mplDeprecation
3270        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3271                      mplDeprecation)
3272    try:
3273        ret = ax.pcolor(*args, **kwargs)
3274    finally:
3275        ax._hold = washold
3276    sci(ret)
3277    return ret
3278
3279# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3280@_autogen_docstring(Axes.pcolormesh)
3281def pcolormesh(*args, **kwargs):
3282    ax = gca()
3283    # Deprecated: allow callers to override the hold state
3284    # by passing hold=True|False
3285    washold = ax._hold
3286    hold = kwargs.pop('hold', None)
3287    if hold is not None:
3288        ax._hold = hold
3289        from matplotlib.cbook import mplDeprecation
3290        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3291                      mplDeprecation)
3292    try:
3293        ret = ax.pcolormesh(*args, **kwargs)
3294    finally:
3295        ax._hold = washold
3296    sci(ret)
3297    return ret
3298
3299# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3300@_autogen_docstring(Axes.phase_spectrum)
3301def phase_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None,
3302                   hold=None, data=None, **kwargs):
3303    ax = gca()
3304    # Deprecated: allow callers to override the hold state
3305    # by passing hold=True|False
3306    washold = ax._hold
3307
3308    if hold is not None:
3309        ax._hold = hold
3310        from matplotlib.cbook import mplDeprecation
3311        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3312                      mplDeprecation)
3313    try:
3314        ret = ax.phase_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to,
3315                                sides=sides, data=data, **kwargs)
3316    finally:
3317        ax._hold = washold
3318
3319    return ret
3320
3321# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3322@_autogen_docstring(Axes.pie)
3323def pie(x, explode=None, labels=None, colors=None, autopct=None,
3324        pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
3325        radius=None, counterclock=True, wedgeprops=None, textprops=None,
3326        center=(0, 0), frame=False, rotatelabels=False, hold=None, data=None):
3327    ax = gca()
3328    # Deprecated: allow callers to override the hold state
3329    # by passing hold=True|False
3330    washold = ax._hold
3331
3332    if hold is not None:
3333        ax._hold = hold
3334        from matplotlib.cbook import mplDeprecation
3335        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3336                      mplDeprecation)
3337    try:
3338        ret = ax.pie(x, explode=explode, labels=labels, colors=colors,
3339                     autopct=autopct, pctdistance=pctdistance, shadow=shadow,
3340                     labeldistance=labeldistance, startangle=startangle,
3341                     radius=radius, counterclock=counterclock,
3342                     wedgeprops=wedgeprops, textprops=textprops, center=center,
3343                     frame=frame, rotatelabels=rotatelabels, data=data)
3344    finally:
3345        ax._hold = washold
3346
3347    return ret
3348
3349# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3350@_autogen_docstring(Axes.plot)
3351def plot(*args, **kwargs):
3352    ax = gca()
3353    # Deprecated: allow callers to override the hold state
3354    # by passing hold=True|False
3355    washold = ax._hold
3356    hold = kwargs.pop('hold', None)
3357    if hold is not None:
3358        ax._hold = hold
3359        from matplotlib.cbook import mplDeprecation
3360        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3361                      mplDeprecation)
3362    try:
3363        ret = ax.plot(*args, **kwargs)
3364    finally:
3365        ax._hold = washold
3366
3367    return ret
3368
3369# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3370@_autogen_docstring(Axes.plot_date)
3371def plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, hold=None,
3372              data=None, **kwargs):
3373    ax = gca()
3374    # Deprecated: allow callers to override the hold state
3375    # by passing hold=True|False
3376    washold = ax._hold
3377
3378    if hold is not None:
3379        ax._hold = hold
3380        from matplotlib.cbook import mplDeprecation
3381        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3382                      mplDeprecation)
3383    try:
3384        ret = ax.plot_date(x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate,
3385                           data=data, **kwargs)
3386    finally:
3387        ax._hold = washold
3388
3389    return ret
3390
3391# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3392@_autogen_docstring(Axes.psd)
3393def psd(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
3394        noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
3395        return_line=None, hold=None, data=None, **kwargs):
3396    ax = gca()
3397    # Deprecated: allow callers to override the hold state
3398    # by passing hold=True|False
3399    washold = ax._hold
3400
3401    if hold is not None:
3402        ax._hold = hold
3403        from matplotlib.cbook import mplDeprecation
3404        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3405                      mplDeprecation)
3406    try:
3407        ret = ax.psd(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend,
3408                     window=window, noverlap=noverlap, pad_to=pad_to,
3409                     sides=sides, scale_by_freq=scale_by_freq,
3410                     return_line=return_line, data=data, **kwargs)
3411    finally:
3412        ax._hold = washold
3413
3414    return ret
3415
3416# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3417@_autogen_docstring(Axes.quiver)
3418def quiver(*args, **kw):
3419    ax = gca()
3420    # Deprecated: allow callers to override the hold state
3421    # by passing hold=True|False
3422    washold = ax._hold
3423    hold = kw.pop('hold', None)
3424    if hold is not None:
3425        ax._hold = hold
3426        from matplotlib.cbook import mplDeprecation
3427        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3428                      mplDeprecation)
3429    try:
3430        ret = ax.quiver(*args, **kw)
3431    finally:
3432        ax._hold = washold
3433    sci(ret)
3434    return ret
3435
3436# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3437@_autogen_docstring(Axes.quiverkey)
3438def quiverkey(*args, **kw):
3439    ax = gca()
3440    # Deprecated: allow callers to override the hold state
3441    # by passing hold=True|False
3442    washold = ax._hold
3443    hold = kw.pop('hold', None)
3444    if hold is not None:
3445        ax._hold = hold
3446        from matplotlib.cbook import mplDeprecation
3447        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3448                      mplDeprecation)
3449    try:
3450        ret = ax.quiverkey(*args, **kw)
3451    finally:
3452        ax._hold = washold
3453
3454    return ret
3455
3456# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3457@_autogen_docstring(Axes.scatter)
3458def scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None,
3459            vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None,
3460            hold=None, data=None, **kwargs):
3461    ax = gca()
3462    # Deprecated: allow callers to override the hold state
3463    # by passing hold=True|False
3464    washold = ax._hold
3465
3466    if hold is not None:
3467        ax._hold = hold
3468        from matplotlib.cbook import mplDeprecation
3469        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3470                      mplDeprecation)
3471    try:
3472        ret = ax.scatter(x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
3473                         vmin=vmin, vmax=vmax, alpha=alpha,
3474                         linewidths=linewidths, verts=verts,
3475                         edgecolors=edgecolors, data=data, **kwargs)
3476    finally:
3477        ax._hold = washold
3478    sci(ret)
3479    return ret
3480
3481# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3482@_autogen_docstring(Axes.semilogx)
3483def semilogx(*args, **kwargs):
3484    ax = gca()
3485    # Deprecated: allow callers to override the hold state
3486    # by passing hold=True|False
3487    washold = ax._hold
3488    hold = kwargs.pop('hold', None)
3489    if hold is not None:
3490        ax._hold = hold
3491        from matplotlib.cbook import mplDeprecation
3492        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3493                      mplDeprecation)
3494    try:
3495        ret = ax.semilogx(*args, **kwargs)
3496    finally:
3497        ax._hold = washold
3498
3499    return ret
3500
3501# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3502@_autogen_docstring(Axes.semilogy)
3503def semilogy(*args, **kwargs):
3504    ax = gca()
3505    # Deprecated: allow callers to override the hold state
3506    # by passing hold=True|False
3507    washold = ax._hold
3508    hold = kwargs.pop('hold', None)
3509    if hold is not None:
3510        ax._hold = hold
3511        from matplotlib.cbook import mplDeprecation
3512        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3513                      mplDeprecation)
3514    try:
3515        ret = ax.semilogy(*args, **kwargs)
3516    finally:
3517        ax._hold = washold
3518
3519    return ret
3520
3521# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3522@_autogen_docstring(Axes.specgram)
3523def specgram(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
3524             noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None,
3525             scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None,
3526             hold=None, data=None, **kwargs):
3527    ax = gca()
3528    # Deprecated: allow callers to override the hold state
3529    # by passing hold=True|False
3530    washold = ax._hold
3531
3532    if hold is not None:
3533        ax._hold = hold
3534        from matplotlib.cbook import mplDeprecation
3535        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3536                      mplDeprecation)
3537    try:
3538        ret = ax.specgram(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend,
3539                          window=window, noverlap=noverlap, cmap=cmap,
3540                          xextent=xextent, pad_to=pad_to, sides=sides,
3541                          scale_by_freq=scale_by_freq, mode=mode, scale=scale,
3542                          vmin=vmin, vmax=vmax, data=data, **kwargs)
3543    finally:
3544        ax._hold = washold
3545    sci(ret[-1])
3546    return ret
3547
3548# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3549@_autogen_docstring(Axes.stackplot)
3550def stackplot(x, *args, **kwargs):
3551    ax = gca()
3552    # Deprecated: allow callers to override the hold state
3553    # by passing hold=True|False
3554    washold = ax._hold
3555    hold = kwargs.pop('hold', None)
3556    if hold is not None:
3557        ax._hold = hold
3558        from matplotlib.cbook import mplDeprecation
3559        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3560                      mplDeprecation)
3561    try:
3562        ret = ax.stackplot(x, *args, **kwargs)
3563    finally:
3564        ax._hold = washold
3565
3566    return ret
3567
3568# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3569@_autogen_docstring(Axes.stem)
3570def stem(*args, **kwargs):
3571    ax = gca()
3572    # Deprecated: allow callers to override the hold state
3573    # by passing hold=True|False
3574    washold = ax._hold
3575    hold = kwargs.pop('hold', None)
3576    if hold is not None:
3577        ax._hold = hold
3578        from matplotlib.cbook import mplDeprecation
3579        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3580                      mplDeprecation)
3581    try:
3582        ret = ax.stem(*args, **kwargs)
3583    finally:
3584        ax._hold = washold
3585
3586    return ret
3587
3588# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3589@_autogen_docstring(Axes.step)
3590def step(x, y, *args, **kwargs):
3591    ax = gca()
3592    # Deprecated: allow callers to override the hold state
3593    # by passing hold=True|False
3594    washold = ax._hold
3595    hold = kwargs.pop('hold', None)
3596    if hold is not None:
3597        ax._hold = hold
3598        from matplotlib.cbook import mplDeprecation
3599        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3600                      mplDeprecation)
3601    try:
3602        ret = ax.step(x, y, *args, **kwargs)
3603    finally:
3604        ax._hold = washold
3605
3606    return ret
3607
3608# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3609@_autogen_docstring(Axes.streamplot)
3610def streamplot(x, y, u, v, density=1, linewidth=None, color=None, cmap=None,
3611               norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1,
3612               transform=None, zorder=None, start_points=None, maxlength=4.0,
3613               integration_direction='both', hold=None, data=None):
3614    ax = gca()
3615    # Deprecated: allow callers to override the hold state
3616    # by passing hold=True|False
3617    washold = ax._hold
3618
3619    if hold is not None:
3620        ax._hold = hold
3621        from matplotlib.cbook import mplDeprecation
3622        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3623                      mplDeprecation)
3624    try:
3625        ret = ax.streamplot(x, y, u, v, density=density, linewidth=linewidth,
3626                            color=color, cmap=cmap, norm=norm,
3627                            arrowsize=arrowsize, arrowstyle=arrowstyle,
3628                            minlength=minlength, transform=transform,
3629                            zorder=zorder, start_points=start_points,
3630                            maxlength=maxlength,
3631                            integration_direction=integration_direction,
3632                            data=data)
3633    finally:
3634        ax._hold = washold
3635    sci(ret.lines)
3636    return ret
3637
3638# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3639@_autogen_docstring(Axes.tricontour)
3640def tricontour(*args, **kwargs):
3641    ax = gca()
3642    # Deprecated: allow callers to override the hold state
3643    # by passing hold=True|False
3644    washold = ax._hold
3645    hold = kwargs.pop('hold', None)
3646    if hold is not None:
3647        ax._hold = hold
3648        from matplotlib.cbook import mplDeprecation
3649        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3650                      mplDeprecation)
3651    try:
3652        ret = ax.tricontour(*args, **kwargs)
3653    finally:
3654        ax._hold = washold
3655    if ret._A is not None: sci(ret)
3656    return ret
3657
3658# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3659@_autogen_docstring(Axes.tricontourf)
3660def tricontourf(*args, **kwargs):
3661    ax = gca()
3662    # Deprecated: allow callers to override the hold state
3663    # by passing hold=True|False
3664    washold = ax._hold
3665    hold = kwargs.pop('hold', None)
3666    if hold is not None:
3667        ax._hold = hold
3668        from matplotlib.cbook import mplDeprecation
3669        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3670                      mplDeprecation)
3671    try:
3672        ret = ax.tricontourf(*args, **kwargs)
3673    finally:
3674        ax._hold = washold
3675    if ret._A is not None: sci(ret)
3676    return ret
3677
3678# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3679@_autogen_docstring(Axes.tripcolor)
3680def tripcolor(*args, **kwargs):
3681    ax = gca()
3682    # Deprecated: allow callers to override the hold state
3683    # by passing hold=True|False
3684    washold = ax._hold
3685    hold = kwargs.pop('hold', None)
3686    if hold is not None:
3687        ax._hold = hold
3688        from matplotlib.cbook import mplDeprecation
3689        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3690                      mplDeprecation)
3691    try:
3692        ret = ax.tripcolor(*args, **kwargs)
3693    finally:
3694        ax._hold = washold
3695    sci(ret)
3696    return ret
3697
3698# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3699@_autogen_docstring(Axes.triplot)
3700def triplot(*args, **kwargs):
3701    ax = gca()
3702    # Deprecated: allow callers to override the hold state
3703    # by passing hold=True|False
3704    washold = ax._hold
3705    hold = kwargs.pop('hold', None)
3706    if hold is not None:
3707        ax._hold = hold
3708        from matplotlib.cbook import mplDeprecation
3709        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3710                      mplDeprecation)
3711    try:
3712        ret = ax.triplot(*args, **kwargs)
3713    finally:
3714        ax._hold = washold
3715
3716    return ret
3717
3718# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3719@_autogen_docstring(Axes.violinplot)
3720def violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False,
3721               showextrema=True, showmedians=False, points=100, bw_method=None,
3722               hold=None, data=None):
3723    ax = gca()
3724    # Deprecated: allow callers to override the hold state
3725    # by passing hold=True|False
3726    washold = ax._hold
3727
3728    if hold is not None:
3729        ax._hold = hold
3730        from matplotlib.cbook import mplDeprecation
3731        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3732                      mplDeprecation)
3733    try:
3734        ret = ax.violinplot(dataset, positions=positions, vert=vert,
3735                            widths=widths, showmeans=showmeans,
3736                            showextrema=showextrema, showmedians=showmedians,
3737                            points=points, bw_method=bw_method, data=data)
3738    finally:
3739        ax._hold = washold
3740
3741    return ret
3742
3743# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3744@_autogen_docstring(Axes.vlines)
3745def vlines(x, ymin, ymax, colors='k', linestyles='solid', label='', hold=None,
3746           data=None, **kwargs):
3747    ax = gca()
3748    # Deprecated: allow callers to override the hold state
3749    # by passing hold=True|False
3750    washold = ax._hold
3751
3752    if hold is not None:
3753        ax._hold = hold
3754        from matplotlib.cbook import mplDeprecation
3755        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3756                      mplDeprecation)
3757    try:
3758        ret = ax.vlines(x, ymin, ymax, colors=colors, linestyles=linestyles,
3759                        label=label, data=data, **kwargs)
3760    finally:
3761        ax._hold = washold
3762
3763    return ret
3764
3765# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3766@_autogen_docstring(Axes.xcorr)
3767def xcorr(x, y, normed=True, detrend=mlab.detrend_none, usevlines=True,
3768          maxlags=10, hold=None, data=None, **kwargs):
3769    ax = gca()
3770    # Deprecated: allow callers to override the hold state
3771    # by passing hold=True|False
3772    washold = ax._hold
3773
3774    if hold is not None:
3775        ax._hold = hold
3776        from matplotlib.cbook import mplDeprecation
3777        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3778                      mplDeprecation)
3779    try:
3780        ret = ax.xcorr(x, y, normed=normed, detrend=detrend,
3781                       usevlines=usevlines, maxlags=maxlags, data=data,
3782                       **kwargs)
3783    finally:
3784        ax._hold = washold
3785
3786    return ret
3787
3788# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3789@_autogen_docstring(Axes.barbs)
3790def barbs(*args, **kw):
3791    ax = gca()
3792    # Deprecated: allow callers to override the hold state
3793    # by passing hold=True|False
3794    washold = ax._hold
3795    hold = kw.pop('hold', None)
3796    if hold is not None:
3797        ax._hold = hold
3798        from matplotlib.cbook import mplDeprecation
3799        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
3800                      mplDeprecation)
3801    try:
3802        ret = ax.barbs(*args, **kw)
3803    finally:
3804        ax._hold = washold
3805
3806    return ret
3807
3808# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3809@docstring.copy_dedent(Axes.cla)
3810def cla():
3811    ret = gca().cla()
3812    return ret
3813
3814# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3815@docstring.copy_dedent(Axes.grid)
3816def grid(b=None, which='major', axis='both', **kwargs):
3817    ret = gca().grid(b=b, which=which, axis=axis, **kwargs)
3818    return ret
3819
3820# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3821@docstring.copy_dedent(Axes.legend)
3822def legend(*args, **kwargs):
3823    ret = gca().legend(*args, **kwargs)
3824    return ret
3825
3826# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3827@docstring.copy_dedent(Axes.table)
3828def table(**kwargs):
3829    ret = gca().table(**kwargs)
3830    return ret
3831
3832# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3833@docstring.copy_dedent(Axes.text)
3834def text(x, y, s, fontdict=None, withdash=False, **kwargs):
3835    ret = gca().text(x, y, s, fontdict=fontdict, withdash=withdash, **kwargs)
3836    return ret
3837
3838# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3839@docstring.copy_dedent(Axes.annotate)
3840def annotate(*args, **kwargs):
3841    ret = gca().annotate(*args, **kwargs)
3842    return ret
3843
3844# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3845@docstring.copy_dedent(Axes.ticklabel_format)
3846def ticklabel_format(**kwargs):
3847    ret = gca().ticklabel_format(**kwargs)
3848    return ret
3849
3850# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3851@docstring.copy_dedent(Axes.locator_params)
3852def locator_params(axis='both', tight=None, **kwargs):
3853    ret = gca().locator_params(axis=axis, tight=tight, **kwargs)
3854    return ret
3855
3856# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3857@docstring.copy_dedent(Axes.tick_params)
3858def tick_params(axis='both', **kwargs):
3859    ret = gca().tick_params(axis=axis, **kwargs)
3860    return ret
3861
3862# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3863@docstring.copy_dedent(Axes.margins)
3864def margins(*args, **kw):
3865    ret = gca().margins(*args, **kw)
3866    return ret
3867
3868# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3869@docstring.copy_dedent(Axes.autoscale)
3870def autoscale(enable=True, axis='both', tight=None):
3871    ret = gca().autoscale(enable=enable, axis=axis, tight=tight)
3872    return ret
3873
3874# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3875def autumn():
3876    """
3877    Set the colormap to "autumn".
3878
3879    This changes the default colormap as well as the colormap of the current
3880    image if there is one. See ``help(colormaps)`` for more information.
3881    """
3882    set_cmap("autumn")
3883
3884
3885# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3886def bone():
3887    """
3888    Set the colormap to "bone".
3889
3890    This changes the default colormap as well as the colormap of the current
3891    image if there is one. See ``help(colormaps)`` for more information.
3892    """
3893    set_cmap("bone")
3894
3895
3896# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3897def cool():
3898    """
3899    Set the colormap to "cool".
3900
3901    This changes the default colormap as well as the colormap of the current
3902    image if there is one. See ``help(colormaps)`` for more information.
3903    """
3904    set_cmap("cool")
3905
3906
3907# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3908def copper():
3909    """
3910    Set the colormap to "copper".
3911
3912    This changes the default colormap as well as the colormap of the current
3913    image if there is one. See ``help(colormaps)`` for more information.
3914    """
3915    set_cmap("copper")
3916
3917
3918# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3919def flag():
3920    """
3921    Set the colormap to "flag".
3922
3923    This changes the default colormap as well as the colormap of the current
3924    image if there is one. See ``help(colormaps)`` for more information.
3925    """
3926    set_cmap("flag")
3927
3928
3929# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3930def gray():
3931    """
3932    Set the colormap to "gray".
3933
3934    This changes the default colormap as well as the colormap of the current
3935    image if there is one. See ``help(colormaps)`` for more information.
3936    """
3937    set_cmap("gray")
3938
3939
3940# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3941def hot():
3942    """
3943    Set the colormap to "hot".
3944
3945    This changes the default colormap as well as the colormap of the current
3946    image if there is one. See ``help(colormaps)`` for more information.
3947    """
3948    set_cmap("hot")
3949
3950
3951# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3952def hsv():
3953    """
3954    Set the colormap to "hsv".
3955
3956    This changes the default colormap as well as the colormap of the current
3957    image if there is one. See ``help(colormaps)`` for more information.
3958    """
3959    set_cmap("hsv")
3960
3961
3962# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3963def jet():
3964    """
3965    Set the colormap to "jet".
3966
3967    This changes the default colormap as well as the colormap of the current
3968    image if there is one. See ``help(colormaps)`` for more information.
3969    """
3970    set_cmap("jet")
3971
3972
3973# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3974def pink():
3975    """
3976    Set the colormap to "pink".
3977
3978    This changes the default colormap as well as the colormap of the current
3979    image if there is one. See ``help(colormaps)`` for more information.
3980    """
3981    set_cmap("pink")
3982
3983
3984# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3985def prism():
3986    """
3987    Set the colormap to "prism".
3988
3989    This changes the default colormap as well as the colormap of the current
3990    image if there is one. See ``help(colormaps)`` for more information.
3991    """
3992    set_cmap("prism")
3993
3994
3995# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
3996def spring():
3997    """
3998    Set the colormap to "spring".
3999
4000    This changes the default colormap as well as the colormap of the current
4001    image if there is one. See ``help(colormaps)`` for more information.
4002    """
4003    set_cmap("spring")
4004
4005
4006# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
4007def summer():
4008    """
4009    Set the colormap to "summer".
4010
4011    This changes the default colormap as well as the colormap of the current
4012    image if there is one. See ``help(colormaps)`` for more information.
4013    """
4014    set_cmap("summer")
4015
4016
4017# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
4018def winter():
4019    """
4020    Set the colormap to "winter".
4021
4022    This changes the default colormap as well as the colormap of the current
4023    image if there is one. See ``help(colormaps)`` for more information.
4024    """
4025    set_cmap("winter")
4026
4027
4028# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
4029def magma():
4030    """
4031    Set the colormap to "magma".
4032
4033    This changes the default colormap as well as the colormap of the current
4034    image if there is one. See ``help(colormaps)`` for more information.
4035    """
4036    set_cmap("magma")
4037
4038
4039# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
4040def inferno():
4041    """
4042    Set the colormap to "inferno".
4043
4044    This changes the default colormap as well as the colormap of the current
4045    image if there is one. See ``help(colormaps)`` for more information.
4046    """
4047    set_cmap("inferno")
4048
4049
4050# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
4051def plasma():
4052    """
4053    Set the colormap to "plasma".
4054
4055    This changes the default colormap as well as the colormap of the current
4056    image if there is one. See ``help(colormaps)`` for more information.
4057    """
4058    set_cmap("plasma")
4059
4060
4061# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
4062def viridis():
4063    """
4064    Set the colormap to "viridis".
4065
4066    This changes the default colormap as well as the colormap of the current
4067    image if there is one. See ``help(colormaps)`` for more information.
4068    """
4069    set_cmap("viridis")
4070
4071
4072# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
4073def nipy_spectral():
4074    """
4075    Set the colormap to "nipy_spectral".
4076
4077    This changes the default colormap as well as the colormap of the current
4078    image if there is one. See ``help(colormaps)`` for more information.
4079    """
4080    set_cmap("nipy_spectral")
4081
4082
4083# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
4084def spectral():
4085    """
4086    Set the colormap to "spectral".
4087
4088    This changes the default colormap as well as the colormap of the current
4089    image if there is one. See ``help(colormaps)`` for more information.
4090    """
4091    from matplotlib.cbook import warn_deprecated
4092    warn_deprecated(
4093                    "2.0",
4094                    name="spectral",
4095                    obj_type="colormap"
4096                    )
4097    set_cmap("spectral")
4098
4099_setup_pyplot_info_docstrings()
4100