Skip to content

Commit

Permalink
Simplify _preprocess_data using Signature.bind.
Browse files Browse the repository at this point in the history
Public API change: `step` no longer defaults to using `y` as
label_namer.  This is consistent with other functions that wrap `plot`
(`plot` itself, `loglog`, etc.).  (Alternatively, we could make all
these functions use `y` as label_namer; I don't really care either way.)

The plot-specific data kwarg logic was moved to
`_process_plot_var_args`, dropping the need for
general callable `positional_parameter_names`,
`_plot_args_replacer`, and `positional_parameter_names`.
`test_positional_parameter_names_as_function` and tests using
`plot_func_varargs` were removed as a consequence.

`replace_all_args` can be replaced by making `replace_names=None`
trigger replacement of all args, even the "unknown" ones.  There was
no real use of "replace all known args but not unknown ones" (even if
there was, this can easily be handled by explicitly listing the args in
replace_names). `test_function_call_with_replace_all_args` was removed
as a consequence.

`replace_names` no longer complains if some argument names it is given
are not present in the "explicit" signature, as long as the function
accepts `**kwargs` -- because it may find the arguments in kwargs
instead.

label_namer no longer triggers if `data` is not passed (if the
argument specified by label_namer was a string, then it is
likely a categorical and shouldn't be considered as a label
anyways). `test_label_problems_at_runtime` was renamed to
`test_label_namer_only_if_data` and modified accordingly.

Calling data-replaced functions used to trigger RuntimeError in some
cases of mismatched arguments; they now trigger TypeError similarly to
how normal functions do (`test_more_args_than_pos_parameters`).
  • Loading branch information
anntzer committed Jun 7, 2018
1 parent b5e8c05 commit f88f6e8
Show file tree
Hide file tree
Showing 7 changed files with 225 additions and 427 deletions.
5 changes: 3 additions & 2 deletions doc/api/next_api_changes/2018-02-15-AL-deprecations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ The following classes, methods, functions, and attributes are deprecated:
- ``backend_qt5.error_msg_qt``, ``backend_qt5.exception_handler``,
- ``backend_wx.FigureCanvasWx.macros``,
- ``cbook.GetRealpathAndStat``, ``cbook.Locked``,
- ``cbook.is_numlike`` (use ``isinstance(..., numbers.Number)`` instead),
``cbook.listFiles``, ``cbook.unicode_safe``,
- ``cbook.get_label``, ``cbook.is_numlike`` (use
``isinstance(..., numbers.Number)`` instead), ``cbook.listFiles``,
``cbook.unicode_safe``,
- ``container.Container.set_remove_method``,
- ``contour.ContourLabeler.cl``, ``.cl_xy``, and ``.cl_cvalues``,
- ``dates.DateFormatter.strftime_pre_1900``, ``dates.DateFormatter.strftime``,
Expand Down
6 changes: 6 additions & 0 deletions doc/api/next_api_changes/2018-03-31-AL.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Axes methods now raise TypeError instead of RuntimeError on mismatched calls
````````````````````````````````````````````````````````````````````````````

In certain cases, Axes methods (and pyplot functions) used to raise a
RuntimeError if they were called with a ``data`` kwarg and otherwise mismatched
arguments. They now raise a ``TypeError`` instead.
340 changes: 116 additions & 224 deletions lib/matplotlib/__init__.py

Large diffs are not rendered by default.

114 changes: 31 additions & 83 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,40 +44,6 @@
rcParams = matplotlib.rcParams


def _plot_args_replacer(args, data):
if len(args) == 1:
return ["y"]
elif len(args) == 2:
# this can be two cases: x,y or y,c
if (not args[1] in data and
not (hasattr(data, 'dtype') and
hasattr(data.dtype, 'names') and
data.dtype.names is not None and
args[1] in data.dtype.names)):
# this is not in data, so just assume that it is something which
# will not get replaced (color spec or array like).
return ["y", "c"]
# it's data, but could be a color code like 'ro' or 'b--'
# -> warn the user in that case...
try:
_process_plot_format(args[1])
except ValueError:
pass
else:
cbook._warn_external(
"Second argument {!r} is ambiguous: could be a color spec but "
"is in data; using as data. Either rename the entry in data "
"or use three arguments to plot.".format(args[1]),
RuntimeWarning)
return ["x", "y"]
elif len(args) == 3:
return ["x", "y", "c"]
else:
raise ValueError("Using arbitrary long args with data is not "
"supported due to ambiguity of arguments.\nUse "
"multiple plotting calls instead.")


# The axes module contains all the wrappers to plotting functions.
# All the other methods should go in the _AxesBase class.

Expand Down Expand Up @@ -894,8 +860,7 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid',

@_preprocess_data(replace_names=["positions", "lineoffsets",
"linelengths", "linewidths",
"colors", "linestyles"],
label_namer=None)
"colors", "linestyles"])
@docstring.dedent_interpd
def eventplot(self, positions, orientation='horizontal', lineoffsets=1,
linelengths=1, linewidths=None, colors=None,
Expand Down Expand Up @@ -1111,10 +1076,8 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1,

#### Basic plotting

# The label_naming happens in `matplotlib.axes._base._plot_args`
@_preprocess_data(replace_names=["x", "y"],
positional_parameter_names=_plot_args_replacer,
label_namer=None)
# Uses a custom implementation of data-kwarg handling in
# _process_plot_var_args.
@docstring.dedent_interpd
def plot(self, *args, scalex=True, scaley=True, **kwargs):
"""
Expand Down Expand Up @@ -1227,7 +1190,6 @@ def plot(self, *args, scalex=True, scaley=True, **kwargs):
You may suppress the warning by adding an empty format string
`plot('n', 'o', '', data=obj)`.
Other Parameters
----------------
scalex, scaley : bool, optional, default: True
Expand All @@ -1254,13 +1216,11 @@ def plot(self, *args, scalex=True, scaley=True, **kwargs):
lines
A list of `.Line2D` objects representing the plotted data.
See Also
--------
scatter : XY scatter plot with markers of variing size and/or color (
sometimes also called bubble chart).
Notes
-----
**Format Strings**
Expand Down Expand Up @@ -1729,7 +1689,7 @@ def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,

#### Specialized plotting

@_preprocess_data(replace_names=["x", "y"], label_namer="y")
# @_preprocess_data() # let 'plot' do the unpacking..
def step(self, x, y, *args, where='pre', **kwargs):
"""
Make a step plot.
Expand Down Expand Up @@ -1798,15 +1758,7 @@ def step(self, x, y, *args, where='pre', **kwargs):

return self.plot(x, y, *args, **kwargs)

@_preprocess_data(replace_names=["x", "left",
"height", "width",
"y", "bottom",
"color", "edgecolor", "linewidth",
"tick_label", "xerr", "yerr",
"ecolor"],
label_namer=None,
replace_all_args=True
)
@_preprocess_data()
@docstring.dedent_interpd
def bar(self, x, height, width=0.8, bottom=None, *, align="center",
**kwargs):
Expand Down Expand Up @@ -2198,7 +2150,7 @@ def barh(self, y, width, height=0.8, left=None, *, align="center",
align=align, **kwargs)
return patches

@_preprocess_data(label_namer=None)
@_preprocess_data()
@docstring.dedent_interpd
def broken_barh(self, xranges, yrange, **kwargs):
"""
Expand Down Expand Up @@ -2269,9 +2221,9 @@ def broken_barh(self, xranges, yrange, **kwargs):

return col

@_preprocess_data(replace_all_args=True, label_namer=None)
def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None,
bottom=0, label=None):
@_preprocess_data()
def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
label=None):
"""
Create a stem plot.
Expand Down Expand Up @@ -2429,8 +2381,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None,

return stem_container

@_preprocess_data(replace_names=["x", "explode", "labels", "colors"],
label_namer=None)
@_preprocess_data(replace_names=["x", "explode", "labels", "colors"])
def pie(self, x, explode=None, labels=None, colors=None,
autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,
startangle=None, radius=None, counterclock=True,
Expand Down Expand Up @@ -3045,7 +2996,7 @@ def extract_err(err, data):

return errorbar_container # (l0, caplines, barcols)

@_preprocess_data(label_namer=None)
@_preprocess_data()
def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,
positions=None, widths=None, patch_artist=None,
bootstrap=None, usermedians=None, conf_intervals=None,
Expand Down Expand Up @@ -4523,7 +4474,7 @@ def _quiver_units(self, args, kw):
return args

# args can by a combination if X, Y, U, V, C and all should be replaced
@_preprocess_data(replace_all_args=True, label_namer=None)
@_preprocess_data()
def quiver(self, *args, **kw):
# Make sure units are handled for x and y values
args = self._quiver_units(args, kw)
Expand All @@ -4536,13 +4487,12 @@ def quiver(self, *args, **kw):
quiver.__doc__ = mquiver.Quiver.quiver_doc

# args can by either Y or y1,y2,... and all should be replaced
@_preprocess_data(replace_all_args=True, label_namer=None)
@_preprocess_data()
def stackplot(self, x, *args, **kwargs):
return mstack.stackplot(self, x, *args, **kwargs)
stackplot.__doc__ = mstack.stackplot.__doc__

@_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"],
label_namer=None)
@_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"])
def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
minlength=0.1, transform=None, zorder=None,
Expand All @@ -4567,7 +4517,7 @@ def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
streamplot.__doc__ = mstream.streamplot.__doc__

# args can be some combination of X, Y, U, V, C and all should be replaced
@_preprocess_data(replace_all_args=True, label_namer=None)
@_preprocess_data()
@docstring.dedent_interpd
def barbs(self, *args, **kw):
"""
Expand All @@ -4581,8 +4531,8 @@ def barbs(self, *args, **kw):
self.autoscale_view()
return b

@_preprocess_data(replace_names=["x", "y"], label_namer=None,
positional_parameter_names=["x", "y", "c"])
# Uses a custom implementation of data-kwarg handling in
# _process_plot_var_args.
def fill(self, *args, **kwargs):
"""
Plot filled polygons.
Expand Down Expand Up @@ -4629,8 +4579,7 @@ def fill(self, *args, **kwargs):
self.autoscale_view()
return patches

@_preprocess_data(replace_names=["x", "y1", "y2", "where"],
label_namer=None)
@_preprocess_data(replace_names=["x", "y1", "y2", "where"])
@docstring.dedent_interpd
def fill_between(self, x, y1, y2=0, where=None, interpolate=False,
step=None, **kwargs):
Expand Down Expand Up @@ -4812,8 +4761,7 @@ def get_interp_point(ind):
self.autoscale_view()
return collection

@_preprocess_data(replace_names=["y", "x1", "x2", "where"],
label_namer=None)
@_preprocess_data(replace_names=["y", "x1", "x2", "where"])
@docstring.dedent_interpd
def fill_betweenx(self, y, x1, x2=0, where=None,
step=None, interpolate=False, **kwargs):
Expand Down Expand Up @@ -4995,7 +4943,7 @@ def get_interp_point(ind):
return collection

#### plotting z(x,y): imshow, pcolor and relatives, contour
@_preprocess_data(label_namer=None)
@_preprocess_data()
def imshow(self, X, cmap=None, norm=None, aspect=None,
interpolation=None, alpha=None, vmin=None, vmax=None,
origin=None, extent=None, shape=None, filternorm=1,
Expand Down Expand Up @@ -5260,7 +5208,7 @@ def _pcolorargs(funcname, *args, allmatch=False):
C = cbook.safe_masked_invalid(C)
return X, Y, C

@_preprocess_data(label_namer=None)
@_preprocess_data()
@docstring.dedent_interpd
def pcolor(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
vmax=None, **kwargs):
Expand Down Expand Up @@ -5497,7 +5445,7 @@ def pcolor(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
self.autoscale_view()
return collection

@_preprocess_data(label_namer=None)
@_preprocess_data()
@docstring.dedent_interpd
def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
vmax=None, shading='flat', antialiased=False, **kwargs):
Expand Down Expand Up @@ -5710,7 +5658,7 @@ def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
self.autoscale_view()
return collection

@_preprocess_data(label_namer=None)
@_preprocess_data()
@docstring.dedent_interpd
def pcolorfast(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
vmax=None, **kwargs):
Expand Down Expand Up @@ -6469,7 +6417,7 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
else:
return tops, bins, cbook.silent_list('Lists of Patches', patches)

@_preprocess_data(replace_names=["x", "y", "weights"], label_namer=None)
@_preprocess_data(replace_names=["x", "y", "weights"])
def hist2d(self, x, y, bins=10, range=None, normed=False, weights=None,
cmin=None, cmax=None, **kwargs):
"""
Expand Down Expand Up @@ -6577,7 +6525,7 @@ def hist2d(self, x, y, bins=10, range=None, normed=False, weights=None,

return h, xedges, yedges, pc

@_preprocess_data(replace_names=["x"], label_namer=None)
@_preprocess_data(replace_names=["x"])
@docstring.dedent_interpd
def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
window=None, noverlap=None, pad_to=None,
Expand Down Expand Up @@ -6812,7 +6760,7 @@ def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None,
else:
return pxy, freqs, line

@_preprocess_data(replace_names=["x"], label_namer=None)
@_preprocess_data(replace_names=["x"])
@docstring.dedent_interpd
def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,
pad_to=None, sides=None, scale=None,
Expand Down Expand Up @@ -6915,7 +6863,7 @@ def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,

return spec, freqs, lines[0]

@_preprocess_data(replace_names=["x"], label_namer=None)
@_preprocess_data(replace_names=["x"])
@docstring.dedent_interpd
def angle_spectrum(self, x, Fs=None, Fc=None, window=None,
pad_to=None, sides=None, **kwargs):
Expand Down Expand Up @@ -6997,7 +6945,7 @@ def angle_spectrum(self, x, Fs=None, Fc=None, window=None,

return spec, freqs, lines[0]

@_preprocess_data(replace_names=["x"], label_namer=None)
@_preprocess_data(replace_names=["x"])
@docstring.dedent_interpd
def phase_spectrum(self, x, Fs=None, Fc=None, window=None,
pad_to=None, sides=None, **kwargs):
Expand Down Expand Up @@ -7078,7 +7026,7 @@ def phase_spectrum(self, x, Fs=None, Fc=None, window=None,

return spec, freqs, lines[0]

@_preprocess_data(replace_names=["x", "y"], label_namer=None)
@_preprocess_data(replace_names=["x", "y"])
@docstring.dedent_interpd
def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
Expand Down Expand Up @@ -7143,7 +7091,7 @@ def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,

return cxy, freqs

@_preprocess_data(replace_names=["x"], label_namer=None)
@_preprocess_data(replace_names=["x"])
@docstring.dedent_interpd
def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
window=None, noverlap=None,
Expand Down Expand Up @@ -7492,7 +7440,7 @@ def matshow(self, Z, **kwargs):
integer=True))
return im

@_preprocess_data(replace_names=["dataset"], label_namer=None)
@_preprocess_data(replace_names=["dataset"])
def violinplot(self, dataset, positions=None, vert=True, widths=0.5,
showmeans=False, showextrema=True, showmedians=False,
points=100, bw_method=None):
Expand Down

0 comments on commit f88f6e8

Please sign in to comment.