From 458546b8faf6a9a66477c2742ecd842dbb84caf7 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 18:56:14 -0700 Subject: [PATCH 1/7] Dynamically generate pyplot functions. --- INSTALL.rst | 3 +- build_alllocal.cmd | 2 +- lib/matplotlib/pyplot.py | 2241 ++----------------------------------- lib/matplotlib/rcsetup.py | 12 +- setupext.py | 5 +- 5 files changed, 129 insertions(+), 2134 deletions(-) diff --git a/INSTALL.rst b/INSTALL.rst index 08c8dd4e1773..f1cc650bcfba 100644 --- a/INSTALL.rst +++ b/INSTALL.rst @@ -179,6 +179,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) @@ -324,7 +325,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/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 22ed435b059e..431bdd4eaf62 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -22,6 +22,7 @@ import six +import inspect import sys import time import warnings @@ -625,16 +626,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. @@ -674,193 +665,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 ## @@ -963,26 +773,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: @@ -1276,7 +1066,7 @@ def twinx(ax=None): For an example """ if ax is None: - ax=gca() + ax = gca() ax1 = ax.twinx() return ax1 @@ -1289,37 +1079,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 space between subplots, - # expressed as a fraction of the average axis width - hspace = 0.2 # the amount of height reserved for space between subplots, - # expressed as a fraction of the average axis height - - The actual defaults are controlled by the rc file - """ - fig = gcf() - fig.subplots_adjust(*args, **kwargs) - - def subplot_tool(targetfig=None): """ Launch a subplot tool window for a figure. @@ -1345,27 +1109,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. @@ -1382,163 +1125,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. @@ -1594,42 +1183,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. @@ -1652,21 +1205,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) @@ -1692,42 +1243,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): @@ -1850,8 +1379,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'} @@ -2272,7 +1799,6 @@ def set_cmap(cmap): im.set_cmap(cmap) - @docstring.copy_dedent(_imread) def imread(*args, **kwargs): return _imread(*args, **kwargs) @@ -2406,11 +1932,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) @@ -2427,22 +1953,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) @@ -2461,36 +1987,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 @@ -2502,1612 +2015,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 +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) -# 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 - - 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 eafc8d4eecf7..c963b4c397df 100644 --- a/lib/matplotlib/rcsetup.py +++ b/lib/matplotlib/rcsetup.py @@ -530,16 +530,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) @@ -1087,7 +1087,7 @@ def _validate_linestyle(ls): 'image.aspect': ['equal', validate_aspect], # equal, auto, a number 'image.interpolation': ['nearest', validate_string], - 'image.cmap': ['viridis', validate_string], # one of gray, jet, etc + 'image.cmap': ['viridis', validate_string], # one of gray, jet, etc 'image.lut': [256, validate_int], # lookup table 'image.origin': ['upper', validate_string], # lookup table 'image.resample': [True, validate_bool], diff --git a/setupext.py b/setupext.py index acef4ba2549f..321497dc5d5c 100644 --- a/setupext.py +++ b/setupext.py @@ -1462,7 +1462,10 @@ def get_install_requires(self): "six>=1.10", ] if sys.version_info < (3,): - install_requires += ["backports.functools_lru_cache"] + install_requires += [ + "backports.functools_lru_cache", + "funcsigs", + ] if sys.version_info < (3,) and os.name == "posix": install_requires += ["subprocess32"] return install_requires From 9b8f94e025f9f449d40ae7e73c10e85d2d46683a Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 19:35:25 -0700 Subject: [PATCH 2/7] 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 431bdd4eaf62..fb011bd133d8 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -316,26 +316,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 @@ -1991,23 +1973,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` @@ -2022,11 +1987,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") @@ -2047,7 +2015,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", @@ -2063,7 +2031,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 894e4ecffccb875611bb72efc57b91ec3c57b757 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 19:38:15 -0700 Subject: [PATCH 3/7] Get rid of boilerplate.py. --- lib/matplotlib/pyplot.py | 10 +- tools/boilerplate.py | 388 --------------------------------------- 2 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 fb011bd133d8..6623a90e7ec1 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -1,6 +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. - """ `matplotlib.pyplot` is a state-based interface to matplotlib. It provides a MATLAB-like way of plotting. @@ -23,6 +20,7 @@ import six import inspect +import re import sys import time import warnings @@ -1671,12 +1669,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/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 7874128d7000b857b26bca9b61e9ed221dedebe7 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 20:12:01 -0700 Subject: [PATCH 4/7] Define pyplot.__all__. --- lib/matplotlib/pyplot.py | 99 ++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 65 deletions(-) diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 6623a90e7ec1..7e43e19d8f1c 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -27,31 +27,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, warn_deprecated -from matplotlib import docstring +from matplotlib import ( + # submodules + _pylab_helpers, cbook, 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: @@ -253,9 +248,7 @@ def show(*args, **kw): def isinteractive(): - """ - Return status of interactive mode. - """ + """Return status of interactive mode.""" return matplotlib.is_interactive() @@ -297,16 +290,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() @@ -328,10 +311,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): @@ -716,10 +695,9 @@ def axes(arg=None, **kwargs): return subplot(111, **kwargs) if isinstance(arg, Axes): - warn_deprecated("2.2", - message="Using pyplot.axes(ax) with ax an Axes " - "argument is deprecated. Please use " - "pyplot.sca(ax) instead.") + cbook.warn_deprecated( + "2.2", "Using pyplot.axes(ax) with ax an Axes argument is " + "deprecated. Please use pyplot.sca(ax) instead.") ax = arg sca(ax) return ax @@ -1350,10 +1328,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 @@ -1362,17 +1339,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') @@ -1680,7 +1647,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) @@ -1777,16 +1750,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. @@ -2084,4 +2047,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 bbbc93f0fe96c16d09d1093caff1936d6ed68bff Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 8 Sep 2017 22:13:54 -0700 Subject: [PATCH 5/7] Fix docstrings affected by move to dynamic pyplot. --- lib/matplotlib/axes/_axes.py | 2 +- lib/matplotlib/axes/_base.py | 71 ++++++++++++++++-------------------- lib/matplotlib/figure.py | 60 ++++++++++++++++-------------- lib/matplotlib/pyplot.py | 18 +++++---- 4 files changed, 76 insertions(+), 75 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 36659d76df73..eaf284b7fd76 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -240,7 +240,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 614c943d73d1..647d00e0d178 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -1606,45 +1606,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 @@ -1665,17 +1660,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) @@ -3102,14 +3095,14 @@ def set_xscale(self, value, **kwargs): """ Set the x-axis scale. - .. - ACCEPTS: [ 'linear' | 'log' | 'symlog' | 'logit' | ... ] - Parameters ---------- value : {"linear", "log", "symlog", "logit"} scaling strategy to apply + .. + ACCEPTS: [ 'linear' | 'log' | 'symlog' | 'logit' | ... ] + Notes ----- Different kwargs are accepted, depending on the scale. See @@ -3427,14 +3420,14 @@ def set_yscale(self, value, **kwargs): """ Set the y-axis scale. - .. - ACCEPTS: [ 'linear' | 'log' | 'symlog' | 'logit' | ... ] - Parameters ---------- value : {"linear", "log", "symlog", "logit"} scaling strategy to apply + .. + ACCEPTS: [ 'linear' | 'log' | 'symlog' | 'logit' | ... ] + Notes ----- Different kwargs are accepted, depending on the scale. See diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index b56c67b3c054..5cf509247145 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -1629,7 +1629,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 @@ -1675,17 +1675,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: @@ -1921,18 +1918,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 @@ -2053,19 +2062,16 @@ def tight_layout(self, renderer=None, pad=1.08, h_pad=None, w_pad=None, Parameters ---------- - - pad : float - padding between the figure edge and the edges of subplots, - as a fraction of the font-size. - + 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 (left, bottom, right, top), optional - 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). + 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 7e43e19d8f1c..fcf928428dc1 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -114,11 +114,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 @@ -168,7 +168,7 @@ def post_execute(): def uninstall_repl_displayhook(): """ - Uninstalls the matplotlib display hook. + Uninstall the matplotlib display hook. .. warning @@ -832,7 +832,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. @@ -1663,13 +1663,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 3ff63048995f4b9f00ba62e1c9f43819c6ebe40f Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sun, 10 Sep 2017 00:53:25 -0700 Subject: [PATCH 6/7] Also autogenerate isinteractive and rcdefaults. --- lib/matplotlib/__init__.py | 16 +-- lib/matplotlib/axes/_base.py | 17 +-- lib/matplotlib/pyplot.py | 241 ++++++++++++++++------------------- 3 files changed, 128 insertions(+), 146 deletions(-) diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 8a7861c06bc2..9519a84688e3 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -1394,25 +1394,25 @@ def get_backend(): def interactive(b): """ - Set interactive mode to boolean b. + Set interactive mode to boolean *b*. - If b is True, then draw after every plotting command, e.g., after xlabel + If *b* is True, then draw after every plotting command, e.g., after xlabel. """ rcParams['interactive'] = b def is_interactive(): - 'Return true if plot mode is interactive' + """Return whether interactive mode is on.""" return rcParams['interactive'] def tk_window_focus(): """Return true if focus maintenance under TkAgg on win32 is on. - This currently works only for python.exe and IPython.exe. - Both IDLE and Pythonwin.exe fail badly when tk_window_focus is on.""" - if rcParams['backend'] != 'TkAgg': - return False - return rcParams['tk.window_focus'] + + This currently works only for python.exe and IPython.exe. + Both IDLE and Pythonwin.exe fail badly when tk_window_focus is on. + """ + return rcParams['backend'] == 'TkAgg' and rcParams['tk.window_focus'] default_test_modules = [ diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 647d00e0d178..53d40b7c1edc 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -1763,18 +1763,19 @@ def get_yticklines(self): # Adding and tracking artists def _sci(self, im): - """ - helper for :func:`~matplotlib.pyplot.sci`; - do not use elsewhere. + """Set the current image. + + This image will be the target of colormap functions like + `~matplotlib.pyplot.viridis`, and other functions such as + `~matplotlib.pyplot.hot` or `~matplotlib.pyplot.clim`. The current + image is an attribute of the current axes. """ if isinstance(im, matplotlib.contour.ContourSet): if im.collections[0] not in self.collections: - raise ValueError( - "ContourSet must be in current Axes") + raise ValueError("ContourSet must be in current Axes") elif im not in self.images and im not in self.collections: - raise ValueError( - "Argument must be an image, collection, or ContourSet in " - "this Axes") + raise ValueError("Argument must be an image, collection, or " + "ContourSet in this Axes") self._current_image = im def _gci(self): diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index fcf928428dc1..b00abf7db1ca 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -247,11 +247,6 @@ def show(*args, **kw): return _show(*args, **kw) -def isinteractive(): - """Return status of interactive mode.""" - return matplotlib.is_interactive() - - def ioff(): """Turn interactive mode off.""" matplotlib.interactive(False) @@ -290,26 +285,6 @@ def pause(interval): time.sleep(interval) -@docstring.copy_dedent(matplotlib.rcdefaults) -def rcdefaults(): - matplotlib.rcdefaults() - if matplotlib.is_interactive(): - draw_all() - - -# 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 - commands like :func:`~matplotlib.pyplot.jet`, - :func:`~matplotlib.pyplot.hot` or - :func:`~matplotlib.pyplot.clim`). The current image is an - attribute of the current axes. - """ - gca()._sci(im) - - ## Any Artist ## @@ -1942,111 +1917,117 @@ def getname_val(identifier): install_repl_displayhook() -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) - 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. - ret = getattr(obj_getter(), method_name)(*args, **kwargs) - post_processor(ret) - return ret - - 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. - "_gci:gci", "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"] -_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( - 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) +def _make_wrappers(obj_getter, base, commands, post_processors): + def make_closure(func_name, wrapper_name, post_processor): + def wrapper(*args, **kwargs): + # We actually need to refetch the func here in case it has been + # monkey-patched. + ret = getattr(obj_getter(), func_name)(*args, **kwargs) + post_processor(ret) + return ret + + func = getattr(base, func_name) + if six.PY2: + wrapper.__name__ = wrapper_name.encode("ascii") + import funcsigs + sig = funcsigs.signature(func) + else: + wrapper.__name__ = wrapper_name + sig = inspect.signature(func) + wrapper.__doc__ = func.__doc__ + # If, and only if, the base object is a class, we are dealing with + # methods, and the first argument gets bound. + wrapper.__signature__ = ( + sig.replace(parameters=list(sig.parameters.values())[1:]) + if isinstance(base, type) else sig) + globals()[wrapper.__name__] = wrapper + + for command in commands: + if ":" in command: + func_name, wrapper_name = command.split(":") + else: + func_name = wrapper_name = command + post_processor = post_processors.get(wrapper_name, lambda obj: None) + make_closure(func_name, wrapper_name, post_processor) + + +_make_wrappers( + lambda: matplotlib, matplotlib, + ["is_interactive:isinteractive", "rcdefaults"], + {"rcdefaults": + lambda _: draw_all() if matplotlib.is_interactive() else None}) +_make_wrappers( + lambda: get_current_fig_manager().canvas, FigureCanvasBase, + ["draw", "mpl_connect:connect", "mpl_disconnect:disconnect"], + {}) +_make_wrappers( + gcf, Figure, + ["clf", "figimage", "gca", "ginput", "savefig", "subplots_adjust", + "suptitle", "tight_layout", "waitforbuttonpress", + # Renamed commands. + "_gci:gci", "legend:figlegend", "text:figtext"], + {}) +_make_wrappers( + gca, Axes, + ["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. + "_sci:sci", "set_title:title", "set_xlabel:xlabel", "set_xscale:xscale", + "set_ylabel:ylabel", "set_yscale:yscale"], + { # For the following functions, an additional callable will be called + # with the return value as argument. + "hexbin": lambda ret: sci(ret), + "imshow": lambda ret: sci(ret), + "pcolor": lambda ret: sci(ret), + "pcolormesh": lambda ret: sci(ret), + "quiver": lambda ret: sci(ret), + "scatter": lambda ret: sci(ret), + "tripcolor": lambda ret: sci(ret), + "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)}) + + +def _make_cmap_wrappers(names): + def make_closure(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 and current image's colormap to "{}". + + See ``help(colormaps)`` for more information. + """.format(name) + globals()[func.__name__] = func + + for name in names: + make_closure(name) + + +_make_cmap_wrappers( + ["autumn", "bone", "cool", "copper", "flag", "gray", "hot", "hsv", + "inferno", "jet", "magma", "nipy_spectral", "pink", "plasma", "prism", + "spectral", "spring", "summer", "viridis", "winter"]) __all__ = sorted([name for name, obj in globals().items() From 9ea3ce3d39ef32d57e74dc521696f03ea14d148d Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sun, 10 Sep 2017 01:21:31 -0700 Subject: [PATCH 7/7] pep8-ify pyplot. --- lib/matplotlib/pyplot.py | 124 ++++++++++++++++++--------------------- pytest.ini | 2 +- 2 files changed, 59 insertions(+), 67 deletions(-) diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index b00abf7db1ca..8a81dc54cdd6 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -2,8 +2,8 @@ `matplotlib.pyplot` is a state-based interface to matplotlib. It provides a MATLAB-like way of plotting. -pyplot is mainly intended for interactive plots and simple cases of programmatic -plot generation:: +pyplot is mainly intended for interactive plots and simple cases of +programmatic plot generation:: import numpy as np import matplotlib.pyplot as plt @@ -64,7 +64,9 @@ MaxNLocator from matplotlib.backends import pylab_setup + ## Backend detection ## + def _backend_selection(): """ If rcParams['backend_fallback'] is true, check to see if the current backend is compatible with the current running event @@ -74,7 +76,7 @@ def _backend_selection(): if not rcParams['backend_fallback'] or backend not in _interactive_bk: return is_agg_backend = rcParams['backend'].endswith('Agg') - if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'): + if 'wx' in sys.modules and backend not in ('WX', 'WXAgg'): import wx if wx.App.IsMainLoopRunning(): rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend @@ -224,7 +226,8 @@ def switch_backend(newbackend): global _backend_mod, new_figure_manager, draw_if_interactive, _show matplotlib.use(newbackend, warn=False, force=True) from matplotlib.backends import pylab_setup - _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() + _backend_mod, new_figure_manager, draw_if_interactive, _show = \ + pylab_setup() def show(*args, **kw): @@ -284,10 +287,8 @@ def pause(interval): else: time.sleep(interval) - ## Any Artist ## - def xkcd(scale=1, length=100, randomness=2): """ Turns on `xkcd `_ sketch-style drawing mode. @@ -360,7 +361,6 @@ def __enter__(self): return dummy_ctx() - ## Figures ## def figure(num=None, # autoincrement if None, else integer from 1-N @@ -604,10 +604,8 @@ def close(*args): else: raise TypeError('close takes 0 or 1 arguments') - ## Axes ## - def axes(arg=None, **kwargs): """ Add an axes to the current figure and make it the current axes. @@ -683,8 +681,10 @@ def axes(arg=None, **kwargs): def delaxes(ax=None): """ - Remove the given `Axes` *ax* from the current figure. If *ax* is *None*, - the current axes is removed. A KeyError is raised if the axes doesn't exist. + Remove the given `Axes` *ax* from the current figure. + + If *ax* is *None*, the current axes is removed. A KeyError is raised if the + axes doesn't exist. """ if ax is None: ax = gca() @@ -736,12 +736,13 @@ def subplot(*args, **kwargs): import matplotlib.pyplot as plt # plot a line, implicitly creating a subplot(111) plt.plot([1,2,3]) - # now create a subplot which represents the top plot of a grid - # with 2 rows and 1 column. Since this subplot will overlap the - # first, the plot (and its axes) previously created, will be removed + # now create a subplot which represents the top plot of a grid with + # 2 rows and 1 column. Since this subplot will overlap the first, the + # plot (and its axes) previously created, will be removed plt.subplot(211) plt.plot(range(12)) - plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background + # create a second subplot with yellow background + plt.subplot(212, facecolor='y') If you do not want this behavior, use the :meth:`~matplotlib.figure.Figure.add_subplot` method or the @@ -778,8 +779,8 @@ def subplot(*args, **kwargs): """ # if subplot called without arguments, create subplot(1,1,1) - if len(args)==0: - args=(1,1,1) + if len(args) == 0: + args = (1, 1, 1) # This check was added because it is very easy to type # subplot(1, 2, False) when subplots(1, 2, False) was intended @@ -787,19 +788,17 @@ def subplot(*args, **kwargs): # ever occur, but mysterious behavior can result because what was # intended to be the sharex argument is instead treated as a # subplot index for subplot() - if len(args) >= 3 and isinstance(args[2], bool) : - warnings.warn("The subplot index argument to subplot() appears" - " to be a boolean. Did you intend to use subplots()?") + if len(args) >= 3 and isinstance(args[2], bool): + warnings.warn("The subplot index argument to subplot() appears " + "to be a boolean. Did you intend to use subplots()?") fig = gcf() a = fig.add_subplot(*args, **kwargs) bbox = a.bbox - byebye = [] - for other in fig.axes: - if other==a: continue - if bbox.fully_overlaps(other.bbox): - byebye.append(other) - for ax in byebye: delaxes(ax) + byebye = [other for other in fig.axes + if other is not a and bbox.fully_overlaps(other.bbox)] + for ax in byebye: + delaxes(ax) return a @@ -1021,24 +1020,28 @@ def subplot_tool(targetfig=None): """ Launch a subplot tool window for a figure. - A :class:`matplotlib.widgets.SubplotTool` instance is returned. + Returns + ------- + `matplotlib.widgets.SubplotTool` """ - tbar = rcParams['toolbar'] # turn off the navigation toolbar for the toolfig - rcParams['toolbar'] = 'None' + tbar = rcParams["toolbar"] # Turn off the nav toolbar for the toolfig. + rcParams["toolbar"] = "None" if targetfig is None: manager = get_current_fig_manager() targetfig = manager.canvas.figure else: - # find the manager for this figure + # Find the manager for this figure. for manager in _pylab_helpers.Gcf._activeQue: - if manager.canvas.figure==targetfig: break - else: raise RuntimeError('Could not find manager for targetfig') + if manager.canvas.figure == targetfig: + break + else: + raise RuntimeError("Could not find manager for targetfig") - toolfig = figure(figsize=(6,3)) + toolfig = figure(figsize=(6, 3)) toolfig.subplots_adjust(top=0.9) - ret = SubplotTool(targetfig, toolfig) - rcParams['toolbar'] = tbar - _pylab_helpers.Gcf.set_active(manager) # restore the current figure + ret = SubplotTool(targetfig, toolfig) + rcParams["toolbar"] = tbar + _pylab_helpers.Gcf.set_active(manager) # Restore the current figure. return ret @@ -1057,10 +1060,8 @@ def box(on=None): on = not ax.get_frame_on() ax.set_frame_on(on) - ## Axis ## - def xlim(*args, **kwargs): """ Get or set the *x* limits of the current axes. @@ -1225,15 +1226,14 @@ def rgrids(*args, **kwargs): """ ax = gca() if not isinstance(ax, PolarAxes): - raise RuntimeError('rgrids only defined for polar axes') - if len(args)==0: + raise RuntimeError("rgrids only defined for polar axes") + if len(args) == 0: lines = ax.yaxis.get_gridlines() labels = ax.yaxis.get_ticklabels() else: lines, labels = ax.set_rgrids(*args, **kwargs) - - return ( silent_list('Line2D rgridline', lines), - silent_list('Text rgridlabel', labels) ) + return (silent_list("Line2D rgridline", lines), + silent_list("Text rgridlabel", labels)) def thetagrids(*args, **kwargs): @@ -1271,31 +1271,27 @@ def thetagrids(*args, **kwargs): - *labels* are :class:`~matplotlib.text.Text` instances. - Note that on input, the *labels* argument is a list of strings, - and on output it is a list of :class:`~matplotlib.text.Text` - instances. + Note that on input, the *labels* argument is a list of strings, and on + output it is a list of :class:`~matplotlib.text.Text` instances. Examples:: # set the locations of the radial gridlines and labels - lines, labels = thetagrids( range(45,360,90) ) + lines, labels = thetagrids(range(45, 360, 90)) # set the locations and labels of the radial gridlines and labels - lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') ) + lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE')) """ ax = gca() if not isinstance(ax, PolarAxes): - raise RuntimeError('rgrids only defined for polar axes') - if len(args)==0: + raise RuntimeError("rgrids only defined for polar axes") + if len(args) == 0: lines = ax.xaxis.get_ticklines() labels = ax.xaxis.get_ticklabels() else: lines, labels = ax.set_thetagrids(*args, **kwargs) - - return (silent_list('Line2D thetagridline', lines), - silent_list('Text thetagridlabel', labels) - ) - + return (silent_list("Line2D thetagridline", lines), + silent_list("Text thetagridlabel", labels)) ## Plotting Info ## @@ -1362,16 +1358,15 @@ def colors(): Here is an example that creates a pale turquoise title:: title('Is this the best color?', color='#afeeee') - """ - pass def colormaps(): """ Matplotlib provides a number of colormaps, and others can be added using - :func:`~matplotlib.cm.register_cmap`. This function documents the built-in - colormaps, and will also return a list of all registered colormaps if called. + `~matplotlib.cm.register_cmap`. This function documents the built-in + colormaps, and will also return a list of all registered colormaps if + called. You can set the colormap for an image, pcolor, scatter, etc, using a keyword argument:: @@ -1628,7 +1623,7 @@ def pad(s, l): exclude = {"colormaps", "colors", "connect", "disconnect", "get_current_fig_manager", "ginput", "plotting", "waitforbuttonpress"} - commands = sorted(set(__all__) - exclude - set(colormaps())) + commands = sorted(set(__all__) - exclude - set(colormaps())) first_sentence = re.compile(r"(?:\s*).+?\.(?:\s+|$)", flags=re.DOTALL) @@ -1676,9 +1671,7 @@ def colorbar(mappable=None, cax=None, ax=None, **kw): 'with contourf).') if ax is None: ax = gca() - - ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw) - return ret + return gcf().colorbar(mappable, cax=cax, ax=ax, **kw) colorbar.__doc__ = matplotlib.colorbar.colorbar_doc @@ -1743,7 +1736,6 @@ def matshow(A, fignum=None, **kw): kwarg to "lower" if you want the first row in the array to be at the bottom instead of the top. - *fignum*: [ None | integer | False ] By default, :func:`matshow` creates a new figure window with automatic numbering. If *fignum* is given as an integer, the @@ -1758,9 +1750,9 @@ def matshow(A, fignum=None, **kw): if fignum is False or fignum is 0: ax = gca() else: - # Extract actual aspect ratio of array and make appropriately sized figure + # Extract array's actual aspect ratio; make appropriately sized figure. fig = figure(fignum, figsize=figaspect(A)) - ax = fig.add_axes([0.15, 0.09, 0.775, 0.775]) + ax = fig.add_axes([0.15, 0.09, 0.775, 0.775]) im = ax.matshow(A, **kw) sci(im) diff --git a/pytest.ini b/pytest.ini index d30a885c90db..ad0bef0d5176 100644 --- a/pytest.ini +++ b/pytest.ini @@ -66,7 +66,7 @@ pep8ignore = matplotlib/mathtext.py E201 E202 E203 E211 E221 E222 E225 E228 E231 E251 E261 E301 E302 E303 E401 E402 E501 matplotlib/patheffects.py E231 matplotlib/pylab.py E401 E402 E501 - matplotlib/pyplot.py E201 E202 E203 E221 E222 E225 E231 E251 E261 E302 E303 E501 E701 E713 + matplotlib/pyplot.py E302 E305 matplotlib/rcsetup.py E203 E225 E261 E302 E501 matplotlib/stackplot.py E251 matplotlib/transforms.py E201 E202 E203 E302 E501