Skip to content

Simplify (quite a bit...) _preprocess_data #10928

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Dec 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
1 change: 1 addition & 0 deletions doc/api/next_api_changes/2018-08-17-AL-deprecations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ The following API elements are deprecated:
- ``get_py2exe_datafiles``, ``tk_window_focus``,
- ``backend_ps.PsBackendHelper``, ``backend_ps.ps_backend_helper``,
- ``cbook.iterable``,
- ``cbook.get_label``, ``cbook.iterable``,
- ``font_manager.OSXInstalledFonts``,
- ``mlab.demean``,
371 changes: 136 additions & 235 deletions lib/matplotlib/__init__.py

Large diffs are not rendered by default.

150 changes: 48 additions & 102 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,46 +42,6 @@
rcParams = matplotlib.rcParams


def _has_item(data, name):
"""Return whether *data* can be item-accessed with *name*.

This supports data with a dict-like interface (`in` checks item
availability) and with numpy.arrays.
"""
try:
return data.dtype.names is not None and name in data.dtype.names
except AttributeError: # not a numpy array
return name in data


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 _has_item(data, args[1]):
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.")


def _make_inset_locator(bounds, trans, parent):
"""
Helper function to locate inset axes, used in
Expand Down Expand Up @@ -1153,8 +1113,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 @@ -1368,13 +1327,12 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1,

return colls

# ### 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)
#### Basic plotting

# 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):
def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs):
"""
Plot y versus x as lines and/or markers.

Expand Down Expand Up @@ -1485,7 +1443,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 @@ -1512,13 +1469,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 varying size and/or color (
sometimes also called bubble chart).


Notes
-----
**Format Strings**
Expand Down Expand Up @@ -1601,14 +1556,10 @@ def plot(self, *args, scalex=True, scaley=True, **kwargs):
'k^:' # black triangle_up markers connected by a dotted line

"""
lines = []

kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)

for line in self._get_lines(*args, **kwargs):
lines = [*self._get_lines(*args, data=data, **kwargs)]
for line in lines:
self.add_line(line)
lines.append(line)

self.autoscale_view(scalex=scalex, scaley=scaley)
return lines

Expand Down Expand Up @@ -1991,8 +1942,8 @@ def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,

#### Specialized plotting

@_preprocess_data(replace_names=["x", "y"], label_namer="y")
def step(self, x, y, *args, where='pre', **kwargs):
# @_preprocess_data() # let 'plot' do the unpacking..
def step(self, x, y, *args, where='pre', data=None, **kwargs):
"""
Make a step plot.

Expand Down Expand Up @@ -2057,17 +2008,9 @@ def step(self, x, y, *args, where='pre', **kwargs):
raise ValueError("'where' argument to step must be "
"'pre', 'post' or 'mid'")
kwargs['drawstyle'] = 'steps-' + where
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
)
return self.plot(x, y, *args, data=data, **kwargs)

@_preprocess_data()
@docstring.dedent_interpd
def bar(self, x, height, width=0.8, bottom=None, *, align="center",
**kwargs):
Expand Down Expand Up @@ -2459,7 +2402,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 @@ -2530,9 +2473,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 @@ -2690,8 +2633,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 @@ -3306,7 +3248,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 @@ -4835,7 +4777,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 @@ -4848,13 +4790,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 @@ -4879,7 +4820,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 @@ -4893,9 +4834,9 @@ 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"])
def fill(self, *args, **kwargs):
# Uses a custom implementation of data-kwarg handling in
# _process_plot_var_args.
def fill(self, *args, data=None, **kwargs):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data should be added to the Parameters section in the docstring

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

"""
Plot filled polygons.

Expand All @@ -4918,6 +4859,13 @@ def fill(self, *args, **kwargs):
ax.fill(x, y, x2, y2) # two polygons
ax.fill(x, y, "b", x2, y2, "r") # a blue and a red polygon

data : indexable object, optional
An object with labelled data. If given, provide the label names to
plot in *x* and *y*, e.g.::

ax.fill("time", "signal",
data={"time": [0, 1, 2], "signal": [0, 1, 0]})

Returns
-------
a list of :class:`~matplotlib.patches.Polygon`
Expand All @@ -4935,14 +4883,13 @@ def fill(self, *args, **kwargs):
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)

patches = []
for poly in self._get_patches_for_fill(*args, **kwargs):
for poly in self._get_patches_for_fill(*args, data=data, **kwargs):
self.add_patch(poly)
patches.append(poly)
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 @@ -5124,8 +5071,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 @@ -5307,7 +5253,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 @@ -5574,7 +5520,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 @@ -5811,7 +5757,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 @@ -6024,7 +5970,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 @@ -6788,7 +6734,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 @@ -6896,7 +6842,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 @@ -7131,7 +7077,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 @@ -7234,7 +7180,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 @@ -7316,7 +7262,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 @@ -7397,7 +7343,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 @@ -7462,7 +7408,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 @@ -7814,7 +7760,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
Loading