From 788203b974cb462548c1c430a13095b2fb897386 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 18:56:14 -0700 Subject: [PATCH 1/6] Dynamically generate pyplot functions. --- .appveyor.yml | 2 +- INSTALL.rst | 3 +- build_alllocal.cmd | 2 +- ci/conda_recipe/meta.yaml | 2 + lib/matplotlib/pyplot.py | 2243 ++----------------------------------- lib/matplotlib/rcsetup.py | 12 +- setup.py | 1 + setupext.py | 32 +- 8 files changed, 154 insertions(+), 2143 deletions(-) diff --git a/.appveyor.yml b/.appveyor.yml index 8676e8064e54..671f84d34dbe 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -86,7 +86,7 @@ install: mock sphinx pandas - activate test-environment - echo %PYTHON_VERSION% %TARGET_ARCH% - - if %PYTHON_VERSION% == 2.7 conda install -q backports.functools_lru_cache + - if %PYTHON_VERSION% == 2.7 conda install -q backports.functools_lru_cache funcsigs # pytest-cov>=2.3.1 due to https://github.com/pytest-dev/pytest-cov/issues/124 - pip install -q pytest "pytest-cov>=2.3.1" pytest-rerunfailures pytest-timeout diff --git a/INSTALL.rst b/INSTALL.rst index 3e5d1dde0dc8..19ab1eb340f0 100644 --- a/INSTALL.rst +++ b/INSTALL.rst @@ -187,6 +187,7 @@ Matplotlib requires a large number of dependencies: * `six `_ * `backports.functools_lru_cache `_ (for Python 2.7 only) + * `funcsigs `_ (for Python 2.7 only) * `subprocess32 `_ (for Python 2.7 only, on Linux and macOS only) @@ -332,7 +333,7 @@ without fiddling with environment variables:: # this package is only available in the conda-forge channel conda install -c conda-forge msinttypes # for Python 2.7 - conda install -c conda-forge backports.functools_lru_cache + conda install -c conda-forge backports.functools_lru_cache funcsigs # copy the libs which have "wrong" names set LIBRARY_LIB=%CONDA_DEFAULT_ENV%\Library\lib diff --git a/build_alllocal.cmd b/build_alllocal.cmd index 7a357302c4ae..4912e870bfa2 100644 --- a/build_alllocal.cmd +++ b/build_alllocal.cmd @@ -7,7 +7,7 @@ :: # this package is only available in the conda-forge channel :: conda install -c conda-forge msinttypes :: if you build on py2.7: -:: conda install -c conda-forge backports.functools_lru_cache +:: conda install -c conda-forge backports.functools_lru_cache funcsigs set TARGET=bdist_wheel IF [%1]==[] ( diff --git a/ci/conda_recipe/meta.yaml b/ci/conda_recipe/meta.yaml index ad3c80da231f..9985a490a56a 100644 --- a/ci/conda_recipe/meta.yaml +++ b/ci/conda_recipe/meta.yaml @@ -40,6 +40,7 @@ requirements: - pyqt # [not osx] - tk 8.5* # [linux] - backports.functools_lru_cache # [py2k] + - funcsigs # [py2k] run: - python @@ -55,6 +56,7 @@ requirements: - pyqt # [not osx] - tk 8.5* # [linux and win] - backports.functools_lru_cache # [py2k] + - funcsigs # [py2k] test: imports: diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 7b46dc3179d4..ed17dce7ed96 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -20,9 +20,9 @@ import six +import inspect import sys import warnings -import types from cycler import cycler import matplotlib @@ -622,16 +622,6 @@ def get_current_fig_manager(): return figManager -@docstring.copy_dedent(FigureCanvasBase.mpl_connect) -def connect(s, func): - return get_current_fig_manager().canvas.mpl_connect(s, func) - - -@docstring.copy_dedent(FigureCanvasBase.mpl_disconnect) -def disconnect(cid): - return get_current_fig_manager().canvas.mpl_disconnect(cid) - - def close(*args): """ Close a figure window. @@ -671,194 +661,12 @@ def close(*args): elif isinstance(arg, Figure): _pylab_helpers.Gcf.destroy_fig(arg) else: - raise TypeError('Unrecognized argument type %s to close' % type(arg)) + raise TypeError( + 'Unrecognized argument type %s to close' % type(arg)) else: raise TypeError('close takes 0 or 1 arguments') -def clf(): - """ - Clear the current figure. - """ - gcf().clf() - - -def draw(): - """Redraw the current figure. - - This is used to update a figure that has been altered, but not - automatically re-drawn. If interactive mode is on (:func:`.ion()`), this - should be only rarely needed, but there may be ways to modify the state of - a figure without marking it as `stale`. Please report these cases as - bugs. - - A more object-oriented alternative, given any - :class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that - was created using a :mod:`~matplotlib.pyplot` function, is:: - - fig.canvas.draw_idle() - """ - get_current_fig_manager().canvas.draw_idle() - - -@docstring.copy_dedent(Figure.savefig) -def savefig(*args, **kwargs): - fig = gcf() - res = fig.savefig(*args, **kwargs) - fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors - return res - - -@docstring.copy_dedent(Figure.ginput) -def ginput(*args, **kwargs): - """ - Blocking call to interact with the figure. - - This will wait for *n* clicks from the user and return a list of the - coordinates of each click. - - If *timeout* is negative, does not timeout. - """ - return gcf().ginput(*args, **kwargs) - - -@docstring.copy_dedent(Figure.waitforbuttonpress) -def waitforbuttonpress(*args, **kwargs): - """ - Blocking call to interact with the figure. - - This will wait for *n* key or mouse clicks from the user and - return a list containing True's for keyboard clicks and False's - for mouse clicks. - - If *timeout* is negative, does not timeout. - """ - return gcf().waitforbuttonpress(*args, **kwargs) - - -# Putting things in figures - -@docstring.copy_dedent(Figure.text) -def figtext(*args, **kwargs): - return gcf().text(*args, **kwargs) - - -@docstring.copy_dedent(Figure.suptitle) -def suptitle(*args, **kwargs): - return gcf().suptitle(*args, **kwargs) - - -@docstring.copy_dedent(Figure.figimage) -def figimage(*args, **kwargs): - return gcf().figimage(*args, **kwargs) - - -def figlegend(*args, **kwargs): - """ - Place a legend in the figure. - - *labels* - a sequence of strings - - *handles* - a sequence of :class:`~matplotlib.lines.Line2D` or - :class:`~matplotlib.patches.Patch` instances - - *loc* - can be a string or an integer specifying the legend - location - - A :class:`matplotlib.legend.Legend` instance is returned. - - Examples - -------- - - To make a legend from existing artists on every axes:: - - figlegend() - - To make a legend for a list of lines and labels:: - - figlegend( (line1, line2, line3), - ('label1', 'label2', 'label3'), - 'upper right' ) - - .. seealso:: - - :func:`~matplotlib.pyplot.legend` - - """ - return gcf().legend(*args, **kwargs) - - -## Figure and Axes hybrid ## - -_hold_msg = """pyplot.hold is deprecated. - Future behavior will be consistent with the long-time default: - plot commands add elements without first clearing the - Axes and/or Figure.""" - -@deprecated("2.0", message=_hold_msg) -def hold(b=None): - """ - Set the hold state. If *b* is None (default), toggle the - hold state, else set the hold state to boolean value *b*:: - - hold() # toggle hold - hold(True) # hold is on - hold(False) # hold is off - - When *hold* is *True*, subsequent plot commands will add elements to - the current axes. When *hold* is *False*, the current axes and - figure will be cleared on the next plot command. - - """ - - fig = gcf() - ax = fig.gca() - - if b is not None: - b = bool(b) - fig._hold = b - ax._hold = b - - # b=None toggles the hold state, so let's get get the current hold - # state; but should pyplot hold toggle the rc setting - me thinks - # not - b = ax._hold - - # The comment above looks ancient; and probably the line below, - # contrary to the comment, is equally ancient. It will trigger - # a second warning, but "Oh, well...". - rc('axes', hold=b) - -@deprecated("2.0", message=_hold_msg) -def ishold(): - """ - Return the hold status of the current axes. - - """ - return gca()._hold - - -@deprecated("2.0", message=_hold_msg) -def over(func, *args, **kwargs): - """ - Call a function with hold(True). - - Calls:: - - func(*args, **kwargs) - - with ``hold(True)`` and then restores the hold state. - - """ - ax = gca() - h = ax._hold - ax._hold = True - func(*args, **kwargs) - ax._hold = h - ## Axes ## @@ -948,26 +756,6 @@ def sca(ax): raise ValueError("Axes instance argument was not found in a figure.") -def gca(**kwargs): - """ - Get the current :class:`~matplotlib.axes.Axes` instance on the - current figure matching the given keyword args, or create one. - - Examples - -------- - To get the current polar axes on the current figure:: - - plt.gca(projection='polar') - - If the current axes doesn't exist, or isn't a polar one, the appropriate - axes will be created and then returned. - - See Also - -------- - matplotlib.figure.Figure.gca : The figure's gca method. - """ - return gcf().gca(**kwargs) - # More ways of creating axes: @@ -1243,7 +1031,7 @@ def twinx(ax=None): For an example """ if ax is None: - ax=gca() + ax = gca() ax1 = ax.twinx() return ax1 @@ -1256,37 +1044,11 @@ def twiny(ax=None): returned. """ if ax is None: - ax=gca() + ax = gca() ax1 = ax.twiny() return ax1 -def subplots_adjust(*args, **kwargs): - """ - Tune the subplot layout. - - call signature:: - - subplots_adjust(left=None, bottom=None, right=None, top=None, - wspace=None, hspace=None) - - The parameter meanings (and suggested defaults) are:: - - left = 0.125 # the left side of the subplots of the figure - right = 0.9 # the right side of the subplots of the figure - bottom = 0.1 # the bottom of the subplots of the figure - top = 0.9 # the top of the subplots of the figure - wspace = 0.2 # the amount of width reserved for blank space between subplots, - # expressed as a fraction of the average axis width - hspace = 0.2 # the amount of height reserved for white space between subplots, - # expressed as a fraction of the average axis height - - The actual defaults are controlled by the rc file - """ - fig = gcf() - fig.subplots_adjust(*args, **kwargs) - - def subplot_tool(targetfig=None): """ Launch a subplot tool window for a figure. @@ -1312,27 +1074,6 @@ def subplot_tool(targetfig=None): return ret -def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None): - """ - Automatically adjust subplot parameters to give specified padding. - - Parameters: - - pad : float - padding between the figure edge and the edges of subplots, as a fraction of the font-size. - h_pad, w_pad : float - padding (height/width) between edges of adjacent subplots. - Defaults to `pad_inches`. - rect : if rect is given, it is interpreted as a rectangle - (left, bottom, right, top) in the normalized figure - coordinate that the whole subplots area (including - labels) will fit into. Default is (0, 0, 1, 1). - """ - - fig = gcf() - fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) - - def box(on=None): """ Turn the axes box on or off. *on* may be a boolean or a string, @@ -1347,163 +1088,9 @@ def box(on=None): ax.set_frame_on(on) -def title(s, *args, **kwargs): - """ - Set a title of the current axes. - - Set one of the three available axes titles. The available titles are - positioned above the axes in the center, flush with the left edge, - and flush with the right edge. - - .. seealso:: - See :func:`~matplotlib.pyplot.text` for adding text - to the current axes - - Parameters - ---------- - label : str - Text to use for the title - - fontdict : dict - A dictionary controlling the appearance of the title text, - the default `fontdict` is: - - {'fontsize': rcParams['axes.titlesize'], - 'fontweight' : rcParams['axes.titleweight'], - 'verticalalignment': 'baseline', - 'horizontalalignment': loc} - - loc : {'center', 'left', 'right'}, str, optional - Which title to set, defaults to 'center' - - Returns - ------- - text : :class:`~matplotlib.text.Text` - The matplotlib text instance representing the title - - Other parameters - ---------------- - kwargs : text properties - Other keyword arguments are text properties, see - :class:`~matplotlib.text.Text` for a list of valid text - properties. - - """ - return gca().set_title(s, *args, **kwargs) - ## Axis ## -def axis(*v, **kwargs): - """ - Convenience method to get or set axis properties. - - Calling with no arguments:: - - >>> axis() - - returns the current axes limits ``[xmin, xmax, ymin, ymax]``.:: - - >>> axis(v) - - sets the min and max of the x and y axes, with - ``v = [xmin, xmax, ymin, ymax]``.:: - - >>> axis('off') - - turns off the axis lines and labels.:: - - >>> axis('equal') - - changes limits of *x* or *y* axis so that equal increments of *x* - and *y* have the same length; a circle is circular.:: - - >>> axis('scaled') - - achieves the same result by changing the dimensions of the plot box instead - of the axis data limits.:: - - >>> axis('tight') - - changes *x* and *y* axis limits such that all data is shown. If - all data is already shown, it will move it to the center of the - figure without modifying (*xmax* - *xmin*) or (*ymax* - - *ymin*). Note this is slightly different than in MATLAB.:: - - >>> axis('image') - - is 'scaled' with the axis limits equal to the data limits.:: - - >>> axis('auto') - - and:: - - >>> axis('normal') - - are deprecated. They restore default behavior; axis limits are automatically - scaled to make the data fit comfortably within the plot box. - - if ``len(*v)==0``, you can pass in *xmin*, *xmax*, *ymin*, *ymax* - as kwargs selectively to alter just those limits without changing - the others. - - >>> axis('square') - - changes the limit ranges (*xmax*-*xmin*) and (*ymax*-*ymin*) of - the *x* and *y* axes to be the same, and have the same scaling, - resulting in a square plot. - - The xmin, xmax, ymin, ymax tuple is returned - - .. seealso:: - - :func:`xlim`, :func:`ylim` - For setting the x- and y-limits individually. - """ - return gca().axis(*v, **kwargs) - - -def xlabel(s, *args, **kwargs): - """ - Set the *x* axis label of the current axis. - - Default override is:: - - override = { - 'fontsize' : 'small', - 'verticalalignment' : 'top', - 'horizontalalignment' : 'center' - } - - .. seealso:: - - :func:`~matplotlib.pyplot.text` - For information on how override and the optional args work - """ - return gca().set_xlabel(s, *args, **kwargs) - - -def ylabel(s, *args, **kwargs): - """ - Set the *y* axis label of the current axis. - - Defaults override is:: - - override = { - 'fontsize' : 'small', - 'verticalalignment' : 'center', - 'horizontalalignment' : 'right', - 'rotation'='vertical' : } - - .. seealso:: - - :func:`~matplotlib.pyplot.text` - For information on how override and the optional args - work. - """ - return gca().set_ylabel(s, *args, **kwargs) - - def xlim(*args, **kwargs): """ Get or set the *x* limits of the current axes. @@ -1559,42 +1146,6 @@ def ylim(*args, **kwargs): return ret -@docstring.dedent_interpd -def xscale(*args, **kwargs): - """ - Set the scaling of the *x*-axis. - - call signature:: - - xscale(scale, **kwargs) - - The available scales are: %(scale)s - - Different keywords may be accepted, depending on the scale: - - %(scale_docs)s - """ - gca().set_xscale(*args, **kwargs) - - -@docstring.dedent_interpd -def yscale(*args, **kwargs): - """ - Set the scaling of the *y*-axis. - - call signature:: - - yscale(scale, **kwargs) - - The available scales are: %(scale)s - - Different keywords may be accepted, depending on the scale: - - %(scale_docs)s - """ - gca().set_yscale(*args, **kwargs) - - def xticks(*args, **kwargs): """ Get or set the *x*-limits of the current tick locations and labels. @@ -1617,21 +1168,19 @@ def xticks(*args, **kwargs): xticks( arange(12), calendar.month_name[1:13], rotation=17 ) """ ax = gca() - - if len(args)==0: + if len(args) == 0: locs = ax.get_xticks() labels = ax.get_xticklabels() - elif len(args)==1: + elif len(args) == 1: locs = ax.set_xticks(args[0]) labels = ax.get_xticklabels() - elif len(args)==2: + elif len(args) == 2: locs = ax.set_xticks(args[0]) labels = ax.set_xticklabels(args[1], **kwargs) - else: raise TypeError('Illegal number of arguments to xticks') - if len(kwargs): - for l in labels: - l.update(kwargs) - + else: + raise TypeError('Illegal number of arguments to xticks') + for l in labels: + l.update(kwargs) return locs, silent_list('Text xticklabel', labels) @@ -1657,42 +1206,20 @@ def yticks(*args, **kwargs): yticks( arange(12), calendar.month_name[1:13], rotation=45 ) """ ax = gca() - - if len(args)==0: + if len(args) == 0: locs = ax.get_yticks() labels = ax.get_yticklabels() - elif len(args)==1: + elif len(args) == 1: locs = ax.set_yticks(args[0]) labels = ax.get_yticklabels() - elif len(args)==2: + elif len(args) == 2: locs = ax.set_yticks(args[0]) labels = ax.set_yticklabels(args[1], **kwargs) - else: raise TypeError('Illegal number of arguments to yticks') - if len(kwargs): - for l in labels: - l.update(kwargs) - - - return ( locs, - silent_list('Text yticklabel', labels) - ) - - -def minorticks_on(): - """ - Display minor ticks on the current plot. - - Displaying minor ticks reduces performance; turn them off using - minorticks_off() if drawing speed is a problem. - """ - gca().minorticks_on() - - -def minorticks_off(): - """ - Remove minor ticks from the current plot. - """ - gca().minorticks_off() + else: + raise TypeError('Illegal number of arguments to yticks') + for l in labels: + l.update(kwargs) + return locs, silent_list('Text yticklabel', labels) def rgrids(*args, **kwargs): @@ -1815,8 +1342,6 @@ def get_plot_commands(): # colormap-setting functions, and anything marked as private with # a preceding underscore. - import inspect - exclude = {'colormaps', 'colors', 'connect', 'disconnect', 'get_plot_commands', 'get_current_fig_manager', 'ginput', 'plotting', 'waitforbuttonpress'} @@ -2237,7 +1762,6 @@ def set_cmap(cmap): im.set_cmap(cmap) - @docstring.copy_dedent(_imread) def imread(*args, **kwargs): return _imread(*args, **kwargs) @@ -2371,11 +1895,11 @@ def plotfile(fname, cols=(0,), plotfuncs=None, else: fig = gcf() - if len(cols)<1: + if len(cols) < 1: raise ValueError('must have at least one column of data') if plotfuncs is None: - plotfuncs = dict() + plotfuncs = {} r = mlab.csv2rec(fname, comments=comments, skiprows=skiprows, checkrows=checkrows, delimiter=delimiter, names=names) @@ -2392,22 +1916,22 @@ def getname_val(identifier): xname, x = getname_val(cols[0]) ynamelist = [] - if len(cols)==1: - ax1 = fig.add_subplot(1,1,1) + if len(cols) == 1: + ax1 = fig.add_subplot(1, 1, 1) funcname = plotfuncs.get(cols[0], 'plot') func = getattr(ax1, funcname) func(x, **kwargs) ax1.set_ylabel(xname) else: N = len(cols) - for i in range(1,N): + for i in range(1, N): if subplots: - if i==1: - ax = ax1 = fig.add_subplot(N-1,1,i) + if i == 1: + ax = ax1 = fig.add_subplot(N - 1, 1, i) else: - ax = fig.add_subplot(N-1,1,i, sharex=ax1) - elif i==1: - ax = fig.add_subplot(1,1,1) + ax = fig.add_subplot(N - 1, 1, i, sharex=ax1) + elif i == 1: + ax = fig.add_subplot(1, 1, 1) yname, y = getname_val(cols[i]) ynamelist.append(yname) @@ -2426,36 +1950,23 @@ def getname_val(identifier): if not subplots: ax.legend(ynamelist, loc='best') - if xname=='date': + if xname == 'date': fig.autofmt_xdate() def _autogen_docstring(base): """Autogenerated wrappers will get their docstring from a base function with an addendum.""" - #msg = "\n\nAdditional kwargs: hold = [True|False] overrides default hold state" msg = '' addendum = docstring.Appender(msg, '\n\n') return lambda func: addendum(docstring.copy_dedent(base)(func)) + # This function cannot be generated by boilerplate.py because it may # return an image or a line. @_autogen_docstring(Axes.spy) def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', **kwargs): - ax = gca() - hold = kwargs.pop('hold', None) - # allow callers to override the hold state by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs) - finally: - ax._hold = washold + ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs) if isinstance(ret, cm.ScalarMappable): sci(ret) return ret @@ -2467,1612 +1978,90 @@ def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', **kwargs): # to determine if they should trigger a draw. install_repl_displayhook() -################# REMAINING CONTENT GENERATED BY boilerplate.py ############## - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.acorr) -def acorr(x, hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.acorr(x, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.angle_spectrum) -def angle_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, - hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.angle_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, - sides=sides, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.arrow) -def arrow(x, y, dx, dy, hold=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.arrow(x, y, dx, dy, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.axhline) -def axhline(y=0, xmin=0, xmax=1, hold=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.axhline(y=y, xmin=xmin, xmax=xmax, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.axhspan) -def axhspan(ymin, ymax, xmin=0, xmax=1, hold=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs) - finally: - ax._hold = washold - - return ret -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.axvline) -def axvline(x=0, ymin=0, ymax=1, hold=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.axvline(x=x, ymin=ymin, ymax=ymax, **kwargs) - finally: - ax._hold = washold +def _make_wrapper(obj_getter, cls, command): + if ":" in command: + method_name, func_name = command.split(":") + else: + method_name = func_name = command + method = getattr(cls, method_name) + + def func(*args, **kwargs): + # We actually need to refetch the method here in case it has been + # monkey-patched. + return getattr(obj_getter(), method_name)(*args, **kwargs) + + if six.PY2: + func.__name__ = func_name.encode("ascii") + import funcsigs + sig = funcsigs.signature(method) + else: + func.__name__ = func_name + sig = inspect.signature(method) + + func.__doc__ = method.__doc__ + func.__signature__ = sig.replace( + parameters=list(sig.parameters.values())[1:]) + globals()[func.__name__] = func + + +_canvas_commands = ["draw", "mpl_connect:connect", "mpl_disconnect:disconnect"] +_fig_commands = [ + "clf", "figimage", "gca", "ginput", "savefig", "subplots_adjust", + "suptitle", "tight_layout", "waitforbuttonpress", + # Renamed commands. + "legend:figlegend", "text:figtext"] +_axes_commands = [ + "acorr", "angle_spectrum", "annotate", "arrow", "autoscale", "axhline", + "axhspan", "axis", "axvline", "axvspan", "bar", "barbs", "barh", "boxplot", + "broken_barh", "cla", "clabel", "cohere", "contour", "contourf", "csd", + "errorbar", "eventplot", "fill", "fill_between", "fill_betweenx", "grid", + "hexbin", "hist", "hist2d", "hlines", "imshow", "legend", "locator_params", + "loglog", "magnitude_spectrum", "margins", "minorticks_off", + "minorticks_on", "pcolor", "pcolormesh", "phase_spectrum", "pie", "plot", + "plot_date", "psd", "quiver", "quiverkey", "scatter", "semilogx", + "semilogy", "specgram", "stackplot", "stem", "step", "streamplot", "table", + "text", "tick_params", "ticklabel_format", "tricontour", "tricontourf", + "tripcolor", "triplot", "violinplot", "vlines", "xcorr", + # Renamed commands. + "set_title:title", "set_xlabel:xlabel", "set_xscale:xscale", + "set_ylabel:ylabel", "set_yscale:yscale"] + + +for _command in _canvas_commands: + _make_wrapper( + lambda: get_current_fig_manager().canvas, FigureCanvasBase, _command) +for _command in _fig_commands: + _make_wrapper(gcf, Figure, _command) +for _command in _axes_commands: + _make_wrapper(gca, Axes, _command) + + +def _make_cmap_wrapper(name): + + def func(): + rc("image", cmap=name) + im = gci() + if im is not None: + im.set_cmap(name) + + func.__name__ = name.encode("ascii") if six.PY2 else name + func.__doc__ = """ + Set the default colormap to "{}" and apply it to the current image, if any. + + See ``help(colormaps)`` for more information. + """.format(name) + globals()[func.__name__] = func + + +_cmaps = [ + "autumn", "bone", "cool", "copper", "flag", "gray", "hot", "hsv", + "inferno", "jet", "magma", "nipy_spectral", "pink", "plasma", "prism", + "spectral", "spring", "summer", "viridis", "winter"] + + +for _cmap in _cmaps: + _make_cmap_wrapper(_cmap) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.axvspan) -def axvspan(xmin, xmax, ymin=0, ymax=1, hold=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.bar) -def bar(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.bar(*args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.barh) -def barh(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.barh(*args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.broken_barh) -def broken_barh(xranges, yrange, hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.broken_barh(xranges, yrange, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.boxplot) -def boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, - widths=None, patch_artist=None, bootstrap=None, usermedians=None, - conf_intervals=None, meanline=None, showmeans=None, showcaps=None, - showbox=None, showfliers=None, boxprops=None, labels=None, - flierprops=None, medianprops=None, meanprops=None, capprops=None, - whiskerprops=None, manage_xticks=True, autorange=False, zorder=None, - hold=None, data=None): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.boxplot(x, notch=notch, sym=sym, vert=vert, whis=whis, - positions=positions, widths=widths, - patch_artist=patch_artist, bootstrap=bootstrap, - usermedians=usermedians, - conf_intervals=conf_intervals, meanline=meanline, - showmeans=showmeans, showcaps=showcaps, - showbox=showbox, showfliers=showfliers, - boxprops=boxprops, labels=labels, - flierprops=flierprops, medianprops=medianprops, - meanprops=meanprops, capprops=capprops, - whiskerprops=whiskerprops, - manage_xticks=manage_xticks, autorange=autorange, - zorder=zorder, data=data) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.cohere) -def cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, - window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', - scale_by_freq=None, hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.cohere(x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, - window=window, noverlap=noverlap, pad_to=pad_to, - sides=sides, scale_by_freq=scale_by_freq, data=data, - **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.clabel) -def clabel(CS, *args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.clabel(CS, *args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.contour) -def contour(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.contour(*args, **kwargs) - finally: - ax._hold = washold - if ret._A is not None: sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.contourf) -def contourf(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.contourf(*args, **kwargs) - finally: - ax._hold = washold - if ret._A is not None: sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.csd) -def csd(x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, - noverlap=None, pad_to=None, sides=None, scale_by_freq=None, - return_line=None, hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.csd(x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, - window=window, noverlap=noverlap, pad_to=pad_to, - sides=sides, scale_by_freq=scale_by_freq, - return_line=return_line, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.errorbar) -def errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, - capsize=None, barsabove=False, lolims=False, uplims=False, - xlolims=False, xuplims=False, errorevery=1, capthick=None, - hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.errorbar(x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor, - elinewidth=elinewidth, capsize=capsize, - barsabove=barsabove, lolims=lolims, uplims=uplims, - xlolims=xlolims, xuplims=xuplims, - errorevery=errorevery, capthick=capthick, data=data, - **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.eventplot) -def eventplot(positions, orientation='horizontal', lineoffsets=1, linelengths=1, - linewidths=None, colors=None, linestyles='solid', hold=None, - data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.eventplot(positions, orientation=orientation, - lineoffsets=lineoffsets, linelengths=linelengths, - linewidths=linewidths, colors=colors, - linestyles=linestyles, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.fill) -def fill(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.fill(*args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.fill_between) -def fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, - hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.fill_between(x, y1, y2=y2, where=where, - interpolate=interpolate, step=step, data=data, - **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.fill_betweenx) -def fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False, - hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.fill_betweenx(y, x1, x2=x2, where=where, step=step, - interpolate=interpolate, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.hexbin) -def hexbin(x, y, C=None, gridsize=100, bins=None, xscale='linear', - yscale='linear', extent=None, cmap=None, norm=None, vmin=None, - vmax=None, alpha=None, linewidths=None, edgecolors='face', - reduce_C_function=np.mean, mincnt=None, marginals=False, hold=None, - data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.hexbin(x, y, C=C, gridsize=gridsize, bins=bins, xscale=xscale, - yscale=yscale, extent=extent, cmap=cmap, norm=norm, - vmin=vmin, vmax=vmax, alpha=alpha, - linewidths=linewidths, edgecolors=edgecolors, - reduce_C_function=reduce_C_function, mincnt=mincnt, - marginals=marginals, data=data, **kwargs) - finally: - ax._hold = washold - sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.hist) -def hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, - bottom=None, histtype='bar', align='mid', orientation='vertical', - rwidth=None, log=False, color=None, label=None, stacked=False, - normed=None, hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.hist(x, bins=bins, range=range, density=density, - weights=weights, cumulative=cumulative, bottom=bottom, - histtype=histtype, align=align, orientation=orientation, - rwidth=rwidth, log=log, color=color, label=label, - stacked=stacked, normed=normed, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.hist2d) -def hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None, - cmax=None, hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.hist2d(x, y, bins=bins, range=range, normed=normed, - weights=weights, cmin=cmin, cmax=cmax, data=data, - **kwargs) - finally: - ax._hold = washold - sci(ret[-1]) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.hlines) -def hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', hold=None, - data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.hlines(y, xmin, xmax, colors=colors, linestyles=linestyles, - label=label, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.imshow) -def imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, - vmin=None, vmax=None, origin=None, extent=None, shape=None, - filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, - hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.imshow(X, cmap=cmap, norm=norm, aspect=aspect, - interpolation=interpolation, alpha=alpha, vmin=vmin, - vmax=vmax, origin=origin, extent=extent, shape=shape, - filternorm=filternorm, filterrad=filterrad, - imlim=imlim, resample=resample, url=url, data=data, - **kwargs) - finally: - ax._hold = washold - sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.loglog) -def loglog(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.loglog(*args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.magnitude_spectrum) -def magnitude_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, - sides=None, scale=None, hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.magnitude_spectrum(x, Fs=Fs, Fc=Fc, window=window, - pad_to=pad_to, sides=sides, scale=scale, - data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.pcolor) -def pcolor(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.pcolor(*args, **kwargs) - finally: - ax._hold = washold - sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.pcolormesh) -def pcolormesh(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.pcolormesh(*args, **kwargs) - finally: - ax._hold = washold - sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.phase_spectrum) -def phase_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, - hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.phase_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, - sides=sides, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.pie) -def pie(x, explode=None, labels=None, colors=None, autopct=None, - pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, - radius=None, counterclock=True, wedgeprops=None, textprops=None, - center=(0, 0), frame=False, rotatelabels=False, hold=None, data=None): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.pie(x, explode=explode, labels=labels, colors=colors, - autopct=autopct, pctdistance=pctdistance, shadow=shadow, - labeldistance=labeldistance, startangle=startangle, - radius=radius, counterclock=counterclock, - wedgeprops=wedgeprops, textprops=textprops, center=center, - frame=frame, rotatelabels=rotatelabels, data=data) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.plot) -def plot(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.plot(*args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.plot_date) -def plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, hold=None, - data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.plot_date(x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate, - data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.psd) -def psd(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, - noverlap=None, pad_to=None, sides=None, scale_by_freq=None, - return_line=None, hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.psd(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, - window=window, noverlap=noverlap, pad_to=pad_to, - sides=sides, scale_by_freq=scale_by_freq, - return_line=return_line, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.quiver) -def quiver(*args, **kw): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kw.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.quiver(*args, **kw) - finally: - ax._hold = washold - sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.quiverkey) -def quiverkey(*args, **kw): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kw.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.quiverkey(*args, **kw) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.scatter) -def scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, - vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, - hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.scatter(x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm, - vmin=vmin, vmax=vmax, alpha=alpha, - linewidths=linewidths, verts=verts, - edgecolors=edgecolors, data=data, **kwargs) - finally: - ax._hold = washold - sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.semilogx) -def semilogx(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.semilogx(*args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.semilogy) -def semilogy(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.semilogy(*args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.specgram) -def specgram(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, - noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None, - scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None, - hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.specgram(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, - window=window, noverlap=noverlap, cmap=cmap, - xextent=xextent, pad_to=pad_to, sides=sides, - scale_by_freq=scale_by_freq, mode=mode, scale=scale, - vmin=vmin, vmax=vmax, data=data, **kwargs) - finally: - ax._hold = washold - sci(ret[-1]) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.stackplot) -def stackplot(x, *args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.stackplot(x, *args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.stem) -def stem(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.stem(*args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.step) -def step(x, y, *args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.step(x, y, *args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.streamplot) -def streamplot(x, y, u, v, density=1, linewidth=None, color=None, cmap=None, - norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, - transform=None, zorder=None, start_points=None, maxlength=4.0, - integration_direction='both', hold=None, data=None): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.streamplot(x, y, u, v, density=density, linewidth=linewidth, - color=color, cmap=cmap, norm=norm, - arrowsize=arrowsize, arrowstyle=arrowstyle, - minlength=minlength, transform=transform, - zorder=zorder, start_points=start_points, - maxlength=maxlength, - integration_direction=integration_direction, - data=data) - finally: - ax._hold = washold - sci(ret.lines) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.tricontour) -def tricontour(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.tricontour(*args, **kwargs) - finally: - ax._hold = washold - if ret._A is not None: sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.tricontourf) -def tricontourf(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.tricontourf(*args, **kwargs) - finally: - ax._hold = washold - if ret._A is not None: sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.tripcolor) -def tripcolor(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.tripcolor(*args, **kwargs) - finally: - ax._hold = washold - sci(ret) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.triplot) -def triplot(*args, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kwargs.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.triplot(*args, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.violinplot) -def violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False, - showextrema=True, showmedians=False, points=100, bw_method=None, - hold=None, data=None): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.violinplot(dataset, positions=positions, vert=vert, - widths=widths, showmeans=showmeans, - showextrema=showextrema, showmedians=showmedians, - points=points, bw_method=bw_method, data=data) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.vlines) -def vlines(x, ymin, ymax, colors='k', linestyles='solid', label='', hold=None, - data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.vlines(x, ymin, ymax, colors=colors, linestyles=linestyles, - label=label, data=data, **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.xcorr) -def xcorr(x, y, normed=True, detrend=mlab.detrend_none, usevlines=True, - maxlags=10, hold=None, data=None, **kwargs): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.xcorr(x, y, normed=normed, detrend=detrend, - usevlines=usevlines, maxlags=maxlags, data=data, - **kwargs) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@_autogen_docstring(Axes.barbs) -def barbs(*args, **kw): - ax = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - washold = ax._hold - hold = kw.pop('hold', None) - if hold is not None: - ax._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - ret = ax.barbs(*args, **kw) - finally: - ax._hold = washold - - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.cla) -def cla(): - ret = gca().cla() - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.grid) -def grid(b=None, which='major', axis='both', **kwargs): - ret = gca().grid(b=b, which=which, axis=axis, **kwargs) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.legend) -def legend(*args, **kwargs): - ret = gca().legend(*args, **kwargs) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.table) -def table(**kwargs): - ret = gca().table(**kwargs) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.text) -def text(x, y, s, fontdict=None, withdash=False, **kwargs): - ret = gca().text(x, y, s, fontdict=fontdict, withdash=withdash, **kwargs) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.annotate) -def annotate(*args, **kwargs): - ret = gca().annotate(*args, **kwargs) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.ticklabel_format) -def ticklabel_format(**kwargs): - ret = gca().ticklabel_format(**kwargs) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.locator_params) -def locator_params(axis='both', tight=None, **kwargs): - ret = gca().locator_params(axis=axis, tight=tight, **kwargs) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.tick_params) -def tick_params(axis='both', **kwargs): - ret = gca().tick_params(axis=axis, **kwargs) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.margins) -def margins(*args, **kw): - ret = gca().margins(*args, **kw) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -@docstring.copy_dedent(Axes.autoscale) -def autoscale(enable=True, axis='both', tight=None): - ret = gca().autoscale(enable=enable, axis=axis, tight=tight) - return ret - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def autumn(): - ''' - set the default colormap to autumn and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='autumn') - im = gci() - - if im is not None: - im.set_cmap(cm.autumn) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def bone(): - ''' - set the default colormap to bone and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='bone') - im = gci() - - if im is not None: - im.set_cmap(cm.bone) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def cool(): - ''' - set the default colormap to cool and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='cool') - im = gci() - - if im is not None: - im.set_cmap(cm.cool) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def copper(): - ''' - set the default colormap to copper and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='copper') - im = gci() - - if im is not None: - im.set_cmap(cm.copper) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def flag(): - ''' - set the default colormap to flag and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='flag') - im = gci() - - if im is not None: - im.set_cmap(cm.flag) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def gray(): - ''' - set the default colormap to gray and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='gray') - im = gci() - - if im is not None: - im.set_cmap(cm.gray) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def hot(): - ''' - set the default colormap to hot and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='hot') - im = gci() - - if im is not None: - im.set_cmap(cm.hot) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def hsv(): - ''' - set the default colormap to hsv and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='hsv') - im = gci() - - if im is not None: - im.set_cmap(cm.hsv) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def jet(): - ''' - set the default colormap to jet and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='jet') - im = gci() - - if im is not None: - im.set_cmap(cm.jet) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def pink(): - ''' - set the default colormap to pink and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='pink') - im = gci() - - if im is not None: - im.set_cmap(cm.pink) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def prism(): - ''' - set the default colormap to prism and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='prism') - im = gci() - - if im is not None: - im.set_cmap(cm.prism) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def spring(): - ''' - set the default colormap to spring and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='spring') - im = gci() - - if im is not None: - im.set_cmap(cm.spring) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def summer(): - ''' - set the default colormap to summer and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='summer') - im = gci() - - if im is not None: - im.set_cmap(cm.summer) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def winter(): - ''' - set the default colormap to winter and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='winter') - im = gci() - - if im is not None: - im.set_cmap(cm.winter) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def magma(): - ''' - set the default colormap to magma and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='magma') - im = gci() - - if im is not None: - im.set_cmap(cm.magma) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def inferno(): - ''' - set the default colormap to inferno and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='inferno') - im = gci() - - if im is not None: - im.set_cmap(cm.inferno) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def plasma(): - ''' - set the default colormap to plasma and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='plasma') - im = gci() - - if im is not None: - im.set_cmap(cm.plasma) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def viridis(): - ''' - set the default colormap to viridis and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='viridis') - im = gci() - - if im is not None: - im.set_cmap(cm.viridis) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def nipy_spectral(): - ''' - set the default colormap to nipy_spectral and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='nipy_spectral') - im = gci() - - if im is not None: - im.set_cmap(cm.nipy_spectral) - - -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost -def spectral(): - ''' - set the default colormap to spectral and apply to current image if any. - See help(colormaps) for more information - ''' - from matplotlib.cbook import warn_deprecated - warn_deprecated( - "2.0", - name="spectral", - obj_type="colormap" - ) - - rc('image', cmap='spectral') - im = gci() - - if im is not None: - im.set_cmap(cm.spectral) _setup_pyplot_info_docstrings() diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py index e17f93874704..b3a6f78add00 100644 --- a/lib/matplotlib/rcsetup.py +++ b/lib/matplotlib/rcsetup.py @@ -531,16 +531,16 @@ def validate_ps_distiller(s): @deprecated('2.1', - addendum=(" See 'validate_negative_linestyle_legacy' " + - "deprecation warning for more information.")) + addendum=(" See 'validate_negative_linestyle_legacy' deprecation " + "warning for more information.")) def validate_negative_linestyle(s): return _validate_negative_linestyle(s) @deprecated('2.1', - addendum=(" The 'contour.negative_linestyle' rcParam now " + - "follows the same validation as the other rcParams " + - "that are related to line style.")) + addendum=(" The 'contour.negative_linestyle' rcParam now follows " + "the same validation as the other rcParams that are " + "related to line style.")) def validate_negative_linestyle_legacy(s): try: res = validate_negative_linestyle(s) @@ -1090,7 +1090,7 @@ def _validate_linestyle(ls): 'image.aspect': ['equal', validate_aspect], # equal, auto, a number 'image.interpolation': ['nearest', six.text_type], - 'image.cmap': ['viridis', six.text_type], # one of gray, jet, etc + 'image.cmap': ['viridis', six.text_type], # one of gray, jet, etc 'image.lut': [256, validate_int], # lookup table 'image.origin': ['upper', six.text_type], # lookup table 'image.resample': [True, validate_bool], diff --git a/setup.py b/setup.py index 95e05a67d258..bb6f12f01c26 100644 --- a/setup.py +++ b/setup.py @@ -69,6 +69,7 @@ setupext.Numpy(), setupext.Six(), setupext.Dateutil(), + setupext.Funcsigs(), setupext.BackportsFuncToolsLRUCache(), setupext.Subprocess32(), setupext.Pytz(), diff --git a/setupext.py b/setupext.py index 1b03b4d93bf2..5f12e6f7ce15 100644 --- a/setupext.py +++ b/setupext.py @@ -1536,9 +1536,8 @@ def check(self): try: import backports.functools_lru_cache except ImportError: - return ( - "backports.functools_lru_cache was not found. It is required for" - "Python versions prior to 3.2") + return ("backports.functools_lru_cache was not found. It is " + "required for Python 2.") return "using backports.functools_lru_cache" else: @@ -1551,6 +1550,27 @@ def get_install_requires(self): return [] +class Funcsigs(SetupPackage): + name = "funcsigs" + + def check(self): + if not PY3min: + try: + import funcsigs + except ImportError: + return "funcsigs was not found. It is required for Python 2." + + return "using funcsigs" + else: + return "Not required" + + def get_install_requires(self): + if not PY3min: + return ['funcsigs'] + else: + return [] + + class Subprocess32(SetupPackage): name = "subprocess32" @@ -1559,10 +1579,8 @@ def check(self): try: import subprocess32 except ImportError: - return ( - "subprocess32 was not found. It used " - " for Python versions prior to 3.2 to improves" - " functionality on Linux and OSX") + return ("subprocess32 was not found. It used for Python 2 to " + "improves functionality on Linux and OSX.") return "using subprocess32" else: From 45fbdae50ef162e9152431a420f14d8d5cfe25c0 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 19:35:25 -0700 Subject: [PATCH 2/6] Also dynamically generate scalarmappable functions. --- lib/matplotlib/pyplot.py | 67 ++++++++++++++++------------------------ 1 file changed, 27 insertions(+), 40 deletions(-) diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index ed17dce7ed96..fc5f46a96955 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -321,26 +321,8 @@ def rcdefaults(): draw_all() -# The current "image" (ScalarMappable) is retrieved or set -# only via the pyplot interface using the following two -# functions: -def gci(): - """ - Get the current colorable artist. Specifically, returns the - current :class:`~matplotlib.cm.ScalarMappable` instance (image or - patch collection), or *None* if no images or patch collections - have been defined. The commands :func:`~matplotlib.pyplot.imshow` - and :func:`~matplotlib.pyplot.figimage` create - :class:`~matplotlib.image.Image` instances, and the commands - :func:`~matplotlib.pyplot.pcolor` and - :func:`~matplotlib.pyplot.scatter` create - :class:`~matplotlib.collections.Collection` instances. The - current image is an attribute of the current axes, or the nearest - earlier axes in the current figure that contains an image. - """ - return gcf()._gci() - - +# This function is not autogenerated because it is needed in when +# autogenerating other functions, see `_post_processors`. def sci(im): """ Set the current image. This image will be the target of colormap @@ -1954,23 +1936,6 @@ def getname_val(identifier): fig.autofmt_xdate() -def _autogen_docstring(base): - """Autogenerated wrappers will get their docstring from a base function - with an addendum.""" - msg = '' - addendum = docstring.Appender(msg, '\n\n') - return lambda func: addendum(docstring.copy_dedent(base)(func)) - - -# This function cannot be generated by boilerplate.py because it may -# return an image or a line. -@_autogen_docstring(Axes.spy) -def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', **kwargs): - ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs) - if isinstance(ret, cm.ScalarMappable): - sci(ret) - return ret - # just to be safe. Interactive mode can be turned on without # calling `plt.ion()` so register it again here. # This is safe because multiple calls to `install_repl_displayhook` @@ -1985,11 +1950,14 @@ def _make_wrapper(obj_getter, cls, command): else: method_name = func_name = command method = getattr(cls, method_name) + post_processor = _post_processors.get(func_name, lambda obj: None) def func(*args, **kwargs): # We actually need to refetch the method here in case it has been # monkey-patched. - return getattr(obj_getter(), method_name)(*args, **kwargs) + ret = getattr(obj_getter(), method_name)(*args, **kwargs) + post_processor(ret) + return ret if six.PY2: func.__name__ = func_name.encode("ascii") @@ -2010,7 +1978,7 @@ def func(*args, **kwargs): "clf", "figimage", "gca", "ginput", "savefig", "subplots_adjust", "suptitle", "tight_layout", "waitforbuttonpress", # Renamed commands. - "legend:figlegend", "text:figtext"] + "_gci:gci", "legend:figlegend", "text:figtext"] _axes_commands = [ "acorr", "angle_spectrum", "annotate", "arrow", "autoscale", "axhline", "axhspan", "axis", "axvline", "axvspan", "bar", "barbs", "barh", "boxplot", @@ -2026,7 +1994,26 @@ def func(*args, **kwargs): # Renamed commands. "set_title:title", "set_xlabel:xlabel", "set_xscale:xscale", "set_ylabel:ylabel", "set_yscale:yscale"] - +_post_processors = { + # For the following functions, an additional callable will be called with + # the return value as argument. + "hexbin": sci, + "imshow": sci, + "pcolor": sci, + "pcolormesh": sci, + "quiver": sci, + "scatter": sci, + "tripcolor": sci, + "contour": lambda ret: sci(ret) if ret._A is not None else None, + "contourf": lambda ret: sci(ret) if ret._A is not None else None, + "tricontour": lambda ret: sci(ret) if ret._A is not None else None, + "tricontourf": lambda ret: sci(ret) if ret._A is not None else None, + "hist2d": lambda ret: sci(ret[-1]), + "specgram": lambda ret: sci(ret[-1]), + "streamplot": lambda ret: sci(ret.lines), + "spy": ( + lambda ret: sci(ret) if isinstance(ret, cm.ScalarMappable) else None) +} for _command in _canvas_commands: _make_wrapper( From 2c5b2fa8b34096e2fbf9a3cd0b961febdcfc87e0 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 19:38:15 -0700 Subject: [PATCH 3/6] Get rid of boilerplate.py. --- lib/matplotlib/pyplot.py | 9 +- pytest.ini | 1 - tools/boilerplate.py | 388 --------------------------------------- 3 files changed, 3 insertions(+), 395 deletions(-) delete mode 100644 tools/boilerplate.py diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index fc5f46a96955..575d7ce6aea1 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -1,5 +1,3 @@ -# Note: The first part of this file can be modified in place, but the latter -# part is autogenerated by the boilerplate.py script. """ Provides a MATLAB-like plotting framework. @@ -21,6 +19,7 @@ import six import inspect +import re import sys import warnings @@ -1634,12 +1633,10 @@ def _setup_pyplot_info_docstrings(): """ Generates the plotting and docstring. - These must be done after the entire module is imported, so it is - called from the end of this module, which is generated by - boilerplate.py. + These must be done after the entire module is imported, so it is called + from the end of this module. """ # Generate the plotting docstring - import re def pad(s, l): """Pad string *s* to length *l*.""" diff --git a/pytest.ini b/pytest.ini index 5ca19fee86a7..a1c55588ec5a 100644 --- a/pytest.ini +++ b/pytest.ini @@ -10,7 +10,6 @@ markers = pep8ignore = * E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E226 E240 E241 E242 E243 E244 E245 E246 E247 E248 E249 E265 E266 E704 W503 - tools/boilerplate.py E501 setup.py E402 E501 setupext.py E301 E302 E501 setup_external_compile.py E302 E501 E711 diff --git a/tools/boilerplate.py b/tools/boilerplate.py deleted file mode 100644 index 5c34b4f869f2..000000000000 --- a/tools/boilerplate.py +++ /dev/null @@ -1,388 +0,0 @@ -""" -Script to autogenerate pyplot wrappers. - -When this script is run, the current contents of pyplot are -split into generatable and non-generatable content (via the magic header -:attr:`PYPLOT_MAGIC_HEADER`) and the generatable content is overwritten. -Hence, the non-generatable content should be edited in the pyplot.py file -itself, whereas the generatable content must be edited via templates in -this file. - -This file is python 3 only due to the use of `inspect` -""" -# We did try to do the wrapping the smart way, -# with callable functions and new.function, but could never get the -# docstrings right for python2.2. See -# http://groups.google.com/group/comp.lang.python/browse_frm/thread/dcd63ec13096a0f6/1b14640f3a4ad3dc?#1b14640f3a4ad3dc -# For some later history, see -# http://thread.gmane.org/gmane.comp.python.matplotlib.devel/7068 - -from __future__ import (absolute_import, division, print_function, - unicode_literals) - -import six - -import os -import inspect -import random -import types - -import textwrap - -# this line imports the installed copy of matplotlib, and not the local copy -from matplotlib.axes import Axes - - -# this is the magic line that must exist in pyplot, after which the boilerplate content will be -# appended -PYPLOT_MAGIC_HEADER = '################# REMAINING CONTENT GENERATED BY boilerplate.py ##############\n' - -PYPLOT_PATH = os.path.join(os.path.dirname(__file__), 'lib', 'matplotlib', - 'pyplot.py') - - -AUTOGEN_MSG = """ -# This function was autogenerated by boilerplate.py. Do not edit as -# changes will be lost""" - - -PLOT_TEMPLATE = AUTOGEN_MSG + """ -@_autogen_docstring(Axes.%(func)s) -def %(func)s(%(argspec)s): - %(ax)s = gca() - # Deprecated: allow callers to override the hold state - # by passing hold=True|False - %(washold)s = %(ax)s._hold -%(sethold)s - if hold is not None: - %(ax)s._hold = hold - from matplotlib.cbook import mplDeprecation - warnings.warn("The 'hold' keyword argument is deprecated since 2.0.", - mplDeprecation) - try: - %(ret)s = %(ax)s.%(func)s(%(call)s) - finally: - %(ax)s._hold = %(washold)s -%(mappable)s - return %(ret)s -""" - - -# Used for misc functions such as cla/legend etc. -MISC_FN_TEMPLATE = AUTOGEN_MSG + """ -@docstring.copy_dedent(Axes.%(func)s) -def %(func)s(%(argspec)s): - %(ret)s = gca().%(func)s(%(call)s) - return %(ret)s -""" - -# Used for colormap functions -CMAP_TEMPLATE = AUTOGEN_MSG + """ -def {name}(): - ''' - set the default colormap to {name} and apply to current image if any. - See help(colormaps) for more information - ''' - rc('image', cmap='{name}') - im = gci() - - if im is not None: - im.set_cmap(cm.{name}) - -""" - -CMAP_TEMPLATE_DEPRECATED = AUTOGEN_MSG + """ -def {name}(): - ''' - set the default colormap to {name} and apply to current image if any. - See help(colormaps) for more information - ''' - from matplotlib.cbook import warn_deprecated - warn_deprecated( - "2.0", - name="{name}", - obj_type="colormap" - ) - - rc('image', cmap='{name}') - im = gci() - - if im is not None: - im.set_cmap(cm.{name}) - -""" - - -def boilerplate_gen(): - """Generator of lines for the automated part of pyplot.""" - - # these methods are all simple wrappers of Axes methods by the same - # name. - _plotcommands = ( - 'acorr', - 'angle_spectrum', - 'arrow', - 'axhline', - 'axhspan', - 'axvline', - 'axvspan', - 'bar', - 'barh', - 'broken_barh', - 'boxplot', - 'cohere', - 'clabel', - 'contour', - 'contourf', - 'csd', - 'errorbar', - 'eventplot', - 'fill', - 'fill_between', - 'fill_betweenx', - 'hexbin', - 'hist', - 'hist2d', - 'hlines', - 'imshow', - 'loglog', - 'magnitude_spectrum', - 'pcolor', - 'pcolormesh', - 'phase_spectrum', - 'pie', - 'plot', - 'plot_date', - 'psd', - 'quiver', - 'quiverkey', - 'scatter', - 'semilogx', - 'semilogy', - 'specgram', - #'spy', - 'stackplot', - 'stem', - 'step', - 'streamplot', - 'tricontour', - 'tricontourf', - 'tripcolor', - 'triplot', - 'violinplot', - 'vlines', - 'xcorr', - 'barbs', - ) - - _misccommands = ( - 'cla', - 'grid', - 'legend', - 'table', - 'text', - 'annotate', - 'ticklabel_format', - 'locator_params', - 'tick_params', - 'margins', - 'autoscale', - ) - - cmappable = { - 'contour': 'if %(ret)s._A is not None: sci(%(ret)s)', - 'contourf': 'if %(ret)s._A is not None: sci(%(ret)s)', - 'hexbin': 'sci(%(ret)s)', - 'scatter': 'sci(%(ret)s)', - 'pcolor': 'sci(%(ret)s)', - 'pcolormesh': 'sci(%(ret)s)', - 'hist2d': 'sci(%(ret)s[-1])', - 'imshow': 'sci(%(ret)s)', - #'spy' : 'sci(%(ret)s)', ### may return image or Line2D - 'quiver': 'sci(%(ret)s)', - 'specgram': 'sci(%(ret)s[-1])', - 'streamplot': 'sci(%(ret)s.lines)', - 'tricontour': 'if %(ret)s._A is not None: sci(%(ret)s)', - 'tricontourf': 'if %(ret)s._A is not None: sci(%(ret)s)', - 'tripcolor': 'sci(%(ret)s)', - } - - def format_value(value): - """ - Format function default values as needed for inspect.formatargspec. - The interesting part is a hard-coded list of functions used - as defaults in pyplot methods. - """ - if isinstance(value, types.FunctionType): - if value.__name__ in ('detrend_none', 'window_hanning'): - return '=mlab.' + value.__name__ - if value.__name__ == 'mean': - return '=np.' + value.__name__ - raise ValueError(('default value %s unknown to boilerplate.' + - 'formatvalue') % value) - return '=' + repr(value) - - text_wrapper = textwrap.TextWrapper(break_long_words=False) - - for fmt, cmdlist in [(PLOT_TEMPLATE, _plotcommands), - (MISC_FN_TEMPLATE, _misccommands)]: - for func in cmdlist: - # For some commands, an additional line is needed to set the - # color map - if func in cmappable: - mappable = ' ' + cmappable[func] % locals() - else: - mappable = '' - - # Get argspec of wrapped function - base_func = getattr(Axes, func) - has_data = 'data' in inspect.signature(base_func).parameters - work_func = inspect.unwrap(base_func) - - if six.PY2: - args, varargs, varkw, defaults = inspect.getargspec(work_func) - else: - (args, varargs, varkw, defaults, kwonlyargs, kwonlydefs, - annotations) = inspect.getfullargspec(work_func) - args.pop(0) # remove 'self' argument - if defaults is None: - defaults = () - else: - def_edited = [] - for val in defaults: - if six.PY2: - if isinstance(val, unicode): - val = val.encode('ascii', 'ignore') - def_edited.append(val) - defaults = tuple(def_edited) - - # Add a data keyword argument if needed (fmt is PLOT_TEMPLATE) and - # possible (if *args is used, we can't just add a data - # argument in front of it since it would gobble one of the - # arguments the user means to pass via *args) - # This needs to be done here so that it goes into call - if not varargs and fmt is PLOT_TEMPLATE and has_data: - args.append('data') - defaults = defaults + (None,) - - # How to call the wrapped function - call = [] - for i, arg in enumerate(args): - if len(defaults) < len(args) - i: - call.append('%s' % arg) - else: - call.append('%s=%s' % (arg, arg)) - - # remove the data keyword as it was needed above to go into the - # call but should go after `hold` in the signature. - # This is janky as all get out, but hopefully boilerplate will - # be retired soon. - if not varargs and fmt is PLOT_TEMPLATE and has_data: - args.pop() - defaults = defaults[:-1] - - if varargs is not None: - call.append('*' + varargs) - if varkw is not None: - call.append('**' + varkw) - call = ', '.join(call) - - text_wrapper.width = 80 - 19 - len(func) - join_with = '\n' + ' ' * (18 + len(func)) - call = join_with.join(text_wrapper.wrap(call)) - - # Add a hold keyword argument if needed (fmt is PLOT_TEMPLATE) and - # possible (if *args is used, we can't just add a hold - # argument in front of it since it would gobble one of the - # arguments the user means to pass via *args) - if varargs: - sethold = " hold = %(varkw)s.pop('hold', None)" % locals() - elif fmt is PLOT_TEMPLATE: - args.append('hold') - defaults = defaults + (None,) - if has_data: - args.append('data') - defaults = defaults + (None,) - sethold = '' - - # Now we can build the argspec for defining the wrapper - argspec = inspect.formatargspec(args, varargs, varkw, defaults, - formatvalue=format_value) - argspec = argspec[1:-1] # remove parens - - text_wrapper.width = 80 - 5 - len(func) - join_with = '\n' + ' ' * (5 + len(func)) - argspec = join_with.join(text_wrapper.wrap(argspec)) - - # A gensym-like facility in case some function takes an - # argument named washold, ax, or ret - washold, ret, ax = 'washold', 'ret', 'ax' - bad = set(args) | {varargs, varkw} - while washold in bad or ret in bad or ax in bad: - washold = 'washold' + str(random.randrange(10 ** 12)) - ret = 'ret' + str(random.randrange(10 ** 12)) - ax = 'ax' + str(random.randrange(10 ** 12)) - - # Since we can't avoid using some function names, - # bail out if they are used as argument names - for reserved in ('gca', 'gci'): - if reserved in bad: - msg = 'Axes method %s has kwarg named %s' % (func, reserved) - raise ValueError(msg) - - yield fmt % locals() - - cmaps = ( - 'autumn', - 'bone', - 'cool', - 'copper', - 'flag', - 'gray', - 'hot', - 'hsv', - 'jet', - 'pink', - 'prism', - 'spring', - 'summer', - 'winter', - 'magma', - 'inferno', - 'plasma', - 'viridis', - "nipy_spectral" - ) - deprecated_cmaps = ("spectral", ) - # add all the colormaps (autumn, hsv, ....) - for name in cmaps: - yield CMAP_TEMPLATE.format(name=name) - for name in deprecated_cmaps: - yield CMAP_TEMPLATE_DEPRECATED.format(name=name) - - yield '' - yield '_setup_pyplot_info_docstrings()' - - -def build_pyplot(): - pyplot_path = os.path.join(os.path.dirname(__file__), "..", 'lib', - 'matplotlib', 'pyplot.py') - - pyplot_orig = open(pyplot_path, 'r').readlines() - - try: - pyplot_orig = pyplot_orig[:pyplot_orig.index(PYPLOT_MAGIC_HEADER) + 1] - except IndexError: - raise ValueError('The pyplot.py file *must* have the exact line: %s' % PYPLOT_MAGIC_HEADER) - - pyplot = open(pyplot_path, 'w') - pyplot.writelines(pyplot_orig) - pyplot.write('\n') - - pyplot.writelines(boilerplate_gen()) - pyplot.write('\n') - - -if __name__ == '__main__': - # Write the matplotlib.pyplot file - build_pyplot() From fc25521b453a601ad38d8bfb8ce0434f0def1aa5 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 20:12:01 -0700 Subject: [PATCH 4/6] Define pyplot.__all__. --- lib/matplotlib/pyplot.py | 96 ++++++++++++++-------------------------- 1 file changed, 33 insertions(+), 63 deletions(-) diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 575d7ce6aea1..104b55484ae1 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -25,31 +25,26 @@ from cycler import cycler import matplotlib -import matplotlib.colorbar -from matplotlib import style -from matplotlib import _pylab_helpers, interactive -from matplotlib.cbook import dedent, silent_list, is_numlike -from matplotlib.cbook import _string_to_bool -from matplotlib.cbook import deprecated -from matplotlib import docstring +from matplotlib import ( + # submodules + _pylab_helpers, cm, docstring, mlab, style, + # functions + get_backend, interactive, rc, rc_context, + # objects + rcParams, rcParamsDefault) +from matplotlib.artist import getp, get, setp, Artist +from matplotlib.axes import Axes, Subplot from matplotlib.backend_bases import FigureCanvasBase +from matplotlib.cbook import ( + _string_to_bool, dedent, deprecated, is_numlike, silent_list) +from matplotlib.cm import get_cmap, register_cmap from matplotlib.figure import Figure, figaspect from matplotlib.gridspec import GridSpec -from matplotlib.image import imread as _imread -from matplotlib.image import imsave as _imsave -from matplotlib import rcParams, rcParamsDefault, get_backend -from matplotlib import rc_context -from matplotlib.rcsetup import interactive_bk as _interactive_bk -from matplotlib.artist import getp, get, Artist -from matplotlib.artist import setp as _setp -from matplotlib.axes import Axes, Subplot +from matplotlib.image import imread, imsave from matplotlib.projections import PolarAxes -from matplotlib import mlab # for csv2rec, detrend_none, window_hanning +from matplotlib.rcsetup import interactive_bk as _interactive_bk from matplotlib.scale import get_scale_docs, get_scale_names -from matplotlib import cm -from matplotlib.cm import get_cmap, register_cmap - import numpy as np # We may not need the following imports here: @@ -252,20 +247,18 @@ def show(*args, **kw): def isinteractive(): - """ - Return status of interactive mode. - """ + """Return status of interactive mode.""" return matplotlib.is_interactive() def ioff(): - 'Turn interactive mode off.' + """Turn interactive mode off.""" matplotlib.interactive(False) uninstall_repl_displayhook() def ion(): - 'Turn interactive mode on.' + """Turn interactive mode on.""" matplotlib.interactive(True) install_repl_displayhook() @@ -303,16 +296,6 @@ def pause(interval): time.sleep(interval) -@docstring.copy_dedent(matplotlib.rc) -def rc(*args, **kwargs): - matplotlib.rc(*args, **kwargs) - - -@docstring.copy_dedent(matplotlib.rc_context) -def rc_context(rc=None, fname=None): - return matplotlib.rc_context(rc, fname) - - @docstring.copy_dedent(matplotlib.rcdefaults) def rcdefaults(): matplotlib.rcdefaults() @@ -334,10 +317,6 @@ def sci(im): ## Any Artist ## -# (getp is simply imported) -@docstring.copy(_setp) -def setp(*args, **kwargs): - return _setp(*args, **kwargs) def xkcd(scale=1, length=100, randomness=2): @@ -1314,10 +1293,9 @@ def plotting(): pass +@deprecated('2.2') def get_plot_commands(): - """ - Get a sorted list of all of the plotting commands. - """ + """Get a sorted list of all of the plotting commands.""" # This works by searching for all functions in this module and # removing a few hard-coded exclusions, as well as all of the # colormap-setting functions, and anything marked as private with @@ -1326,17 +1304,7 @@ def get_plot_commands(): exclude = {'colormaps', 'colors', 'connect', 'disconnect', 'get_plot_commands', 'get_current_fig_manager', 'ginput', 'plotting', 'waitforbuttonpress'} - exclude |= set(colormaps()) - this_module = inspect.getmodule(get_plot_commands) - - commands = set() - for name, obj in list(six.iteritems(globals())): - if name.startswith('_') or name in exclude: - continue - if inspect.isfunction(obj) and inspect.getmodule(obj) is this_module: - commands.add(name) - - return sorted(commands) + return sorted(set(__all__) - exclude - set(colormaps())) @deprecated('2.1') @@ -1644,7 +1612,13 @@ def pad(s, l): return s[:l] return s + ' ' * (l - len(s)) - commands = get_plot_commands() + # Searching for all public functions in this module (this is done when + # defining __all__) and remove a few hard-coded exclusions, as well as all + # of the colormap-setting functions + exclude = {"colormaps", "colors", "connect", "disconnect", + "get_current_fig_manager", "ginput", "plotting", + "waitforbuttonpress"} + commands = sorted(set(__all__) - exclude - set(colormaps())) first_sentence = re.compile(r"(?:\s*).+?\.(?:\s+|$)", flags=re.DOTALL) @@ -1741,16 +1715,6 @@ def set_cmap(cmap): im.set_cmap(cmap) -@docstring.copy_dedent(_imread) -def imread(*args, **kwargs): - return _imread(*args, **kwargs) - - -@docstring.copy_dedent(_imsave) -def imsave(*args, **kwargs): - return _imsave(*args, **kwargs) - - def matshow(A, fignum=None, **kw): """ Display an array as a matrix in a new figure window. @@ -2048,4 +2012,10 @@ def func(): _make_cmap_wrapper(_cmap) +__all__ = sorted([name for name, obj in globals().items() + if getattr(obj, "__module__", None) == __name__ + and not name.startswith("_")] + + ["getp", "imread", "imsave", "rc", "rc_context", "setp"]) + + _setup_pyplot_info_docstrings() From f88bd65f70405286617b60d02876ab5ff150201f Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 22:13:54 -0700 Subject: [PATCH 5/6] Fix docstrings affected by move to dynamic pyplot. --- lib/matplotlib/axes/_axes.py | 2 +- lib/matplotlib/axes/_base.py | 63 ++++++++++++++++------------------ lib/matplotlib/figure.py | 65 ++++++++++++++++++++---------------- lib/matplotlib/pyplot.py | 18 +++++----- 4 files changed, 76 insertions(+), 72 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 402382587ccf..17d614e5f5bf 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -230,7 +230,7 @@ def get_ylabel(self): def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs): """ - Set the label for the yaxis + Set the label for the yaxis. Parameters ---------- diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index eeadfc87a1e0..48757cba4f59 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -1488,45 +1488,40 @@ def apply_aspect(self, position=None): self.set_xbound((x0, x1)) def axis(self, *v, **kwargs): - """Set axis properties. + """Convenience method to get or set axis properties. Valid signatures:: - xmin, xmax, ymin, ymax = axis() - xmin, xmax, ymin, ymax = axis(list_arg) - xmin, xmax, ymin, ymax = axis(string_arg) - xmin, xmax, ymin, ymax = axis(**kwargs) + xmin, xmax, ymin, ymax = axis(*, emit=True) + xmin, xmax, ymin, ymax = axis(_string_arg_, *, emit=True) + xmin, xmax, ymin, ymax = axis([xmin, ymin, xmax, ymax], *, emit=True) Parameters ---------- - v : list of float or {'on', 'off', 'equal', 'tight', 'scaled',\ - 'normal', 'auto', 'image', 'square'} - Optional positional argument - - Axis data limits set from a list; or a command relating to axes: - - ========== ================================================ - Value Description - ========== ================================================ - 'on' Toggle axis lines and labels on - 'off' Toggle axis lines and labels off - 'equal' Equal scaling by changing limits - 'scaled' Equal scaling by changing box dimensions - 'tight' Limits set such that all data is shown - 'auto' Automatic scaling, fill rectangle with data - 'normal' Same as 'auto'; deprecated - 'image' 'scaled' with axis limits equal to data limits - 'square' Square plot; similar to 'scaled', but initially\ - forcing xmax-xmin = ymax-ymin - ========== ================================================ - - emit : bool, optional - Passed to set_{x,y}lim functions, if observers - are notified of axis limit change + _string_arg_ : str, optional + + The following values are allowed: + + ========== ======================================================= + Value Description + ========== ======================================================= + 'on' Toggle axis lines and labels on + 'off' Toggle axis lines and labels off + 'equal' Equal scaling by changing limits + 'scaled' Equal scaling by changing box dimensions + 'tight' Limits set such that all data is shown + 'auto' Automatic scaling, fill rectangle with data + 'image' 'scaled' with axis limits equal to data limits + 'square' Square plot; similar to 'scaled', but initially forcing + ``xmax-xmin = ymax-ymin`` + ========== ======================================================= xmin, ymin, xmax, ymax : float, optional The axis limits to be set + emit : bool, optional + Whether observers are notified of axes limit changes. + Returns ------- xmin, xmax, ymin, ymax : float @@ -1547,17 +1542,15 @@ def axis(self, *v, **kwargs): self.set_axis_on() elif s == 'off': self.set_axis_off() - elif s in ('equal', 'tight', 'scaled', 'normal', - 'auto', 'image', 'square'): + elif s in ['equal', 'tight', 'scaled', 'auto', 'image', 'square']: self.set_autoscale_on(True) self.set_aspect('auto') self.autoscale_view(tight=False) - # self.apply_aspect() if s == 'equal': self.set_aspect('equal', adjustable='datalim') elif s == 'scaled': self.set_aspect('equal', adjustable='box', anchor='C') - self.set_autoscale_on(False) # Req. by Mark Bakker + self.set_autoscale_on(False) elif s == 'tight': self.autoscale_view(tight=True) self.set_autoscale_on(False) @@ -2950,7 +2943,7 @@ def get_xscale(self): def set_xscale(self, value, **kwargs): """ - Set the x-axis scale + Set the x-axis scale. Parameters ---------- @@ -3257,7 +3250,7 @@ def get_yscale(self): def set_yscale(self, value, **kwargs): """ - Set the y-axis scale + Set the y-axis scale. Parameters ---------- diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index d47fa4d2d935..c3f00100e467 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -1564,7 +1564,7 @@ def _set_artist_props(self, a): @docstring.dedent_interpd def gca(self, **kwargs): """ - Get the current axes, creating one if necessary + Get the current axes, creating one if necessary. The following kwargs are supported for ensuring the returned axes adheres to the given projection etc., and for axes creation if @@ -1610,17 +1610,14 @@ def gca(self, **kwargs): return self.add_subplot(1, 1, 1, **kwargs) def sca(self, a): - 'Set the current axes to be a and return a' + """Set the current axes to be a and return a.""" self._axstack.bubble(a) for func in self._axobservers: func(self) return a def _gci(self): - """ - helper for :func:`~matplotlib.pyplot.gci`; - do not use elsewhere. - """ + """Get the current colorable artist.""" # Look first for an image in the current Axes: cax = self._axstack.current_key_axes()[1] if cax is None: @@ -1846,18 +1843,30 @@ def colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kw): self.stale = True return cb - def subplots_adjust(self, *args, **kwargs): + def subplots_adjust(self, left=None, bottom=None, right=None, top=None, + wspace=None, hspace=None): """ - Call signature:: + Update the figure's `SubplotParams` and the subplot locations. - subplots_adjust(left=None, bottom=None, right=None, top=None, - wspace=None, hspace=None) + All parameters default to their respective rcParams. - Update the :class:`SubplotParams` with *kwargs* (defaulting to rc when - *None*) and update the subplot locations - - """ - self.subplotpars.update(*args, **kwargs) + Parameters + ---------- + left : float + Left edge of the subplots of the figure. + right : float + Right edge of the subplots of the figure. + bottom : float + Bottom edge of the subplots of the figure. + top : float + Top edge of the subplots of the figure. + wspace : float + Amount of width reserved as blank space between subplots. + hspace : float + Amount of height reserved as blank space between subplots. + """ + self.subplotpars.update(left=left, bottom=bottom, right=right, top=top, + wspace=wspace, hspace=hspace) for ax in self.axes: if not isinstance(ax, SubplotBase): # Check if sharing a subplots axis @@ -1974,20 +1983,20 @@ def get_tightbbox(self, renderer): def tight_layout(self, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None): """ - Adjust subplot parameters to give specified padding. - - Parameters: + Automatically adjust subplot parameters to give specified padding. - pad : float - padding between the figure edge and the edges of subplots, - as a fraction of the font-size. - h_pad, w_pad : float - padding (height/width) between edges of adjacent subplots. - Defaults to `pad_inches`. - rect : if rect is given, it is interpreted as a rectangle - (left, bottom, right, top) in the normalized figure - coordinate that the whole subplots area (including - labels) will fit into. Default is (0, 0, 1, 1). + Parameters + ---------- + pad : float, optional + Padding between the figure edge and the edges of subplots, as a + fraction of the font-size. + h_pad, w_pad : float, optional + Padding (height/width) between edges of adjacent subplots. + Defaults to *pad_inches*. + rect : Tuple[float, float, float, float], optional + (left, bottom, right, top) rectangle in normalized figure + coordinates that the whole subplots area (including labels) will + fit into. Defaults to using the entire figure. """ from .tight_layout import ( diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 104b55484ae1..6a68b56f14af 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -113,11 +113,11 @@ def _backend_selection(): def install_repl_displayhook(): """ - Install a repl display hook so that any stale figure are automatically - redrawn when control is returned to the repl. + Install a REPL display hook so that any stale figure are automatically + redrawn when control is returned to the REPL. - This works with IPython terminals and kernels, - as well as vanilla python shells. + This works with IPython terminals and kernels, as well as vanilla Python + shells. """ global _IP_REGISTERED global _INSTALL_FIG_OBSERVER @@ -167,7 +167,7 @@ def post_execute(): def uninstall_repl_displayhook(): """ - Uninstalls the matplotlib display hook. + Uninstall the matplotlib display hook. .. warning @@ -823,7 +823,7 @@ def subplot(*args, **kwargs): def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw): """ - Create a figure and a set of subplots + Create a figure and a set of subplots. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call. @@ -1628,13 +1628,15 @@ def pad(s, l): max_name = 0 max_summary = 0 for name in commands: - doc = globals()[name].__doc__ + func = globals()[name] + doc = inspect.getdoc(func) summary = '' if doc is not None: match = first_sentence.match(doc) if match is not None: summary = match.group(0).strip().replace('\n', ' ') - name = '`%s`' % name + name = ("`{0.__name__}`" if func.__module__ == __name__ + else "`~{0.__module__}.{0.__name__}`").format(func) rows.append([name, summary]) max_name = max(max_name, len(name)) max_summary = max(max_summary, len(summary)) From a9a59019573949e21ab2d3f81d2b328115c581f9 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 22:37:15 -0700 Subject: [PATCH 6/6] Simplify docstring.py. Unless the docstring is going to be interpolated, we do not need to bother dedenting it. Deprecated unused functionality in docstring.py. --- lib/matplotlib/docstring.py | 101 ++++++++++-------- lib/matplotlib/lines.py | 3 - lib/matplotlib/pyplot.py | 5 +- .../axes_grid1/anchored_artists.py | 5 - 4 files changed, 59 insertions(+), 55 deletions(-) diff --git a/lib/matplotlib/docstring.py b/lib/matplotlib/docstring.py index cf9537f0c6fe..a828ecbddc44 100644 --- a/lib/matplotlib/docstring.py +++ b/lib/matplotlib/docstring.py @@ -4,52 +4,53 @@ import six from matplotlib import cbook -import sys -import types class Substitution(object): - """ - A decorator to take a function's docstring and perform string - substitution on it. + """A decorator that performs %-substitution on an object's docstring. - This decorator should be robust even if func.__doc__ is None - (for example, if -OO was passed to the interpreter) + This decorator should be robust even if obj.__doc__ is None (for example, + if -OO was passed to the interpreter) - Usage: construct a docstring.Substitution with a sequence or - dictionary suitable for performing substitution; then - decorate a suitable function with the constructed object. e.g. + Usage: construct a docstring.Substitution with a sequence or dictionary + suitable for performing substitution; then decorate a suitable function + with the constructed object, e.g.:: - sub_author_name = Substitution(author='Jason') + sub_author_name = Substitution(author='Jason') - @sub_author_name - def some_function(x): - "%(author)s wrote this function" + @sub_author_name + def some_function(x): + "%(author)s wrote this function" - # note that some_function.__doc__ is now "Jason wrote this function" + # note that some_function.__doc__ is now "Jason wrote this function" - One can also use positional arguments. + One can also use positional arguments:: - sub_first_last_names = Substitution('Edgar Allen', 'Poe') + sub_first_last_names = Substitution('Edgar Allen', 'Poe') - @sub_first_last_names - def some_function(x): - "%s %s wrote the Raven" + @sub_first_last_names + def some_function(x): + "%s %s wrote the Raven" """ def __init__(self, *args, **kwargs): - assert not (len(args) and len(kwargs)), \ - "Only positional or keyword args are allowed" + if args and kwargs: + raise ValueError("Only positional or keyword args are allowed") self.params = args or kwargs def __call__(self, func): - func.__doc__ = func.__doc__ and func.__doc__ % self.params + if func.__doc__: + if six.PY2: + getattr(func, "im_func", func).__doc__ %= self.params + else: + func.__doc__ %= self.params return func def update(self, *args, **kwargs): - "Assume self.params is a dict and update it with supplied args" + """Assume self.params is a dict and update it with supplied args.""" self.params.update(*args, **kwargs) @classmethod + @cbook.deprecated("2.2") def from_params(cls, params): """ In the case where the params is a mutable sequence (list or @@ -62,6 +63,7 @@ def from_params(cls, params): return result +@cbook.deprecated("2.2") class Appender(object): """ A function decorator that will append an addendum to the docstring @@ -86,43 +88,52 @@ def __init__(self, addendum, join=''): self.join = join def __call__(self, func): - docitems = [func.__doc__, self.addendum] - func.__doc__ = func.__doc__ and self.join.join(docitems) + if func.__doc__: + func.__doc__ = self.join.join([func.__doc__, self.addendum]) return func +@cbook.deprecated("2.2") def dedent(func): - "Dedent a docstring (if present)" - func.__doc__ = func.__doc__ and cbook.dedent(func.__doc__) + """Dedent a docstring (if present).""" + if func.__doc__: + if six.PY2: + getattr(func, "im_func", func).__doc__ = cbook.dedent(func.__doc__) + else: + func.__doc__ = cbook.dedent(func.__doc__) return func +@cbook.deprecated("2.2") def copy(source): - "Copy a docstring from another source function (if present)" - def do_copy(target): + """A decorator that copies the docstring from the source (if present).""" + def decorator(target): if source.__doc__: target.__doc__ = source.__doc__ return target - return do_copy + return decorator -# create a decorator that will house the various documentation that -# is reused throughout matplotlib +# Create a decorator that will house the various documentation that is reused +# throughout Matplotlib. interpd = Substitution() def dedent_interpd(func): - """A special case of the interpd that first performs a dedent on - the incoming docstring""" - if isinstance(func, types.MethodType) and not six.PY3: - func = func.im_func - return interpd(dedent(func)) + """Decorator that dedents and interpolates an object's docstring. + """ + if func.__doc__: + if six.PY2: + getattr(func, "im_func", func).__doc__ = cbook.dedent(func.__doc__) + else: + func.__doc__ = cbook.dedent(func.__doc__) + return interpd(func) +@cbook.deprecated("2.2") def copy_dedent(source): - """A decorator that will copy the docstring from the source and - then dedent it""" - # note the following is ugly because "Python is not a functional - # language" - GVR. Perhaps one day, functools.compose will exist. - # or perhaps not. - # http://mail.python.org/pipermail/patches/2007-February/021687.html - return lambda target: dedent(copy(source)(target)) + """A decorator that copies the dedented docstring from the source.""" + def decorator(func): + if source.__doc__: + dedent(source) + return func + return decorator diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index 057a03291a25..91f588761f37 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -1498,7 +1498,4 @@ def onpick(self, event): fillStyles = MarkerStyle.fillstyles docstring.interpd.update(Line2D=artist.kwdoc(Line2D)) - -# You can not set the docstring of an instancemethod, -# but you can on the underlying function. Go figure. docstring.dedent_interpd(Line2D.__init__) diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 6a68b56f14af..ec05b537855e 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -18,6 +18,7 @@ import six +import functools import inspect import re import sys @@ -200,11 +201,11 @@ def uninstall_repl_displayhook(): draw_all = _pylab_helpers.Gcf.draw_all -@docstring.copy_dedent(Artist.findobj) def findobj(o=None, match=None, include_self=True): if o is None: o = gcf() return o.findobj(match, include_self=include_self) +findobj.__doc__ = Artist.findobj.__doc__ def switch_backend(newbackend): @@ -296,7 +297,7 @@ def pause(interval): time.sleep(interval) -@docstring.copy_dedent(matplotlib.rcdefaults) +@functools.wraps(matplotlib.rcdefaults, ["__doc__"]) def rcdefaults(): matplotlib.rcdefaults() if matplotlib.is_interactive(): diff --git a/lib/mpl_toolkits/axes_grid1/anchored_artists.py b/lib/mpl_toolkits/axes_grid1/anchored_artists.py index 3cda87108377..e3f7f06fb021 100644 --- a/lib/mpl_toolkits/axes_grid1/anchored_artists.py +++ b/lib/mpl_toolkits/axes_grid1/anchored_artists.py @@ -2,7 +2,6 @@ unicode_literals) import six -from matplotlib import docstring from matplotlib.offsetbox import (AnchoredOffsetbox, AuxTransformBox, DrawingArea, TextArea, VPacker) from matplotlib.patches import Rectangle, Ellipse @@ -13,7 +12,6 @@ class AnchoredDrawingArea(AnchoredOffsetbox): - @docstring.dedent def __init__(self, width, height, xdescent, ydescent, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs): @@ -89,7 +87,6 @@ def __init__(self, width, height, xdescent, ydescent, class AnchoredAuxTransformBox(AnchoredOffsetbox): - @docstring.dedent def __init__(self, transform, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs): """ @@ -162,7 +159,6 @@ def __init__(self, transform, loc, class AnchoredEllipse(AnchoredOffsetbox): - @docstring.dedent def __init__(self, transform, width, height, angle, loc, pad=0.1, borderpad=0.1, prop=None, frameon=True, **kwargs): """ @@ -228,7 +224,6 @@ def __init__(self, transform, width, height, angle, loc, class AnchoredSizeBar(AnchoredOffsetbox): - @docstring.dedent def __init__(self, transform, size, label, loc, pad=0.1, borderpad=0.1, sep=2, frameon=True, size_vertical=0, color='black',