8000 Simplify _preprocess_data using Signature.bind. · matplotlib/matplotlib@df26a24 · GitHub
[go: up one dir, main page]

Skip to content

Commit df26a24

Browse files
committed
Simplify _preprocess_data using Signature.bind.
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`).
1 parent b83f96c commit df26a24

File tree

7 files changed

+227
-435
lines changed

7 files changed

+227
-435
lines changed

doc/api/next_api_changes/2018-02-15-AL-deprecations.rst

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,9 @@ The following classes, methods, functions, and attributes are deprecated:
1313
- ``afm.parse_afm``,
1414
- ``backend_wx.FigureCanvasWx.macros``,
1515
- ``cbook.GetRealpathAndStat``, ``cbook.Locked``,
16-
- ``cbook.is_numlike`` (use ``isinstance(..., numbers.Number)`` instead),
17-
``cbook.listFiles``, ``cbook.unicode_safe``
16+
- ``cbook.get_label``, ``cbook.is_numlike`` (use
17+
``isinstance(..., numbers.Number)`` instead), ``cbook.listFiles``,
18+
``cbook.unicode_safe``
1819
- ``container.Container.set_remove_method``,
1920
- ``dates.DateFormatter.strftime_pre_1900``, ``dates.DateFormatter.strftime``,
2021
- ``font_manager.TempCache``,
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Axes methods now raise TypeError instead of RuntimeError on mismatched calls
2+
````````````````````````````````````````````````````````````````````````````
3+
4+
In certain cases, Axes methods (and pyplot functions) used to raise a
5+
RuntimeError if they were called with a ``data`` kwarg and otherwise mismatched
6+
arguments. They now raise a ``TypeError`` instead.

lib/matplotlib/__init__.py

Lines changed: 117 additions & 227 deletions
Large diffs are not rendered by default.

lib/matplotlib/axes/_axes.py

Lines changed: 29 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -44,40 +44,6 @@
4444
rcParams = matplotlib.rcParams
4545

4646

47-
def _plot_args_replacer(args, data):
48-
if len(args) == 1:
49-
return ["y"]
50-
elif len(args) == 2:
51-
# this can be two cases: x,y or y,c
52-
if (not args[1] in data and
53-
not (hasattr(data, 'dtype') and
54-
hasattr(data.dtype, 'names') and
55-
data.dtype.names is not None and
56-
args[1] in data.dtype.names)):
57-
# this is not in data, so just assume that it is something which
58-
# will not get replaced (color spec or array like).
59-
return ["y", "c"]
60-
# it's data, but could be a color code like 'ro' or 'b--'
61-
# -> warn the user in that case...
62-
try:
63-
_process_plot_format(args[1])
64-
except ValueError:
65-
pass
66-
else:
67-
warnings.warn(
68-
"Second argument {!r} is ambiguous: could be a color spec but "
69-
"is in data; using as data. Either rename the entry in data "
70-
"or use three arguments to plot.".format(args[1]),
71-
RuntimeWarning, stacklevel=3)
72-
return ["x", "y"]
73-
elif len(args) == 3:
74-
return ["x", "y", "c"]
75-
else:
76-
raise ValueError("Using arbitrary long args with data is not "
77-
"supported due to ambiguity of arguments.\nUse "
78-
"multiple plotting calls instead.")
79-
80-
8147
# The axes module contains all the wrappers to plotting functions.
8248
# All the other methods should go in the _AxesBase class.
8349

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

895861
@_preprocess_data(replace_names=["positions", "lineoffsets",
896862
"linelengths", "linewidths",
897-
"colors", "linestyles"],
898-
label_namer=None)
863+
"colors", "linestyles"])
899864
@docstring.dedent_interpd
900865
def eventplot(self, positions, orientation='horizontal', lineoffsets=1,
901866
linelengths=1, linewidths=None, colors=None,
@@ -1110,10 +1075,8 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1,
11101075

11111076
#### Basic plotting
11121077

1113-
# The label_naming happens in `matplotlib.axes._base._plot_args`
1114-
@_preprocess_data(replace_names=["x", "y"],
1115-
positional_parameter_names=_plot_args_replacer,
1116-
label_namer=None)
1078+
# Uses a custom implementation of data-kwarg handling in
1079+
# _process_plot_var_args.
11171080
@docstring.dedent_interpd
11181081
def plot(self, *args, **kwargs):
11191082
"""
@@ -1226,7 +1189,6 @@ def plot(self, *args, **kwargs):
12261189
You may suppress the warning by adding an empty format string
12271190
`plot('n', 'o', '', data=obj)`.
12281191
1229-
12301192
Other Parameters
12311193
----------------
12321194
scalex, scaley : bool, optional, default: True
@@ -1253,13 +1215,11 @@ def plot(self, *args, **kwargs):
12531215
lines
12541216
A list of `.Line2D` objects representing the plotted data.
12551217
1256-
12571218
See Also
12581219
--------
12591220
scatter : XY scatter plot with markers of variing size and/or color (
12601221
sometimes also called bubble chart).
12611222
1262-
12631223
Notes
12641224
-----
12651225
**Format Strings**
@@ -1732,7 +1692,7 @@ def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,
17321692

17331693
#### Specialized plotting
17341694

1735-
@_preprocess_data(replace_names=["x", "y"], label_namer="y")
1695+
# @_preprocess_data() # let 'plot' do the unpacking..
17361696
def step(self, x, y, *args, **kwargs):
17371697
"""
17381698
Make a step plot.
@@ -1803,15 +1763,7 @@ def step(self, x, y, *args, **kwargs):
18031763

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

1806-
@_preprocess_data(replace_names=["x", "left",
1807-
"height", "width",
1808-
"y", "bottom",
1809-
"color", "edgecolor", "linewidth",
1810-
"tick_label", "xerr", "yerr",
1811-
"ecolor"],
1812-
label_namer=None,
1813-
replace_all_args=True
1814-
)
1766+
@_preprocess_data()
18151767
@docstring.dedent_interpd
18161768
def bar(self, *args, **kwargs):
18171769
r"""
@@ -2265,7 +2217,7 @@ def barh(self, *args, **kwargs):
22652217
bottom=y, **kwargs)
22662218
return patches
22672219

2268-
@_preprocess_data(label_namer=None)
2220+
@_preprocess_data()
22692221
@docstring.dedent_interpd
22702222
def broken_barh(self, xranges, yrange, **kwargs):
22712223
"""
@@ -2336,7 +2288,7 @@ def broken_barh(self, xranges, yrange, **kwargs):
23362288

23372289
return col
23382290

2339-
@_preprocess_data(replace_all_args=True, label_namer=None)
2291+
@_preprocess_data()
23402292
def stem(self, *args, **kwargs):
23412293
"""
23422294
Create a stem plot.
@@ -2525,8 +2477,7 @@ def stem(self, *args, **kwargs):
25252477

25262478
return stem_container
25272479

2528-
@_preprocess_data(replace_names=["x", "explode", "labels", "colors"],
2529-
label_namer=None)
2480+
@_preprocess_data(replace_names=["x", "explode", "labels", "colors"])
25302481
def pie(self, x, explode=None, labels=None, colors=None,
25312482
autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,
25322483
startangle=None, radius=None, counterclock=True,
@@ -3136,7 +3087,7 @@ def extract_err(err, data):
31363087

31373088
return errorbar_container # (l0, caplines, barcols)
31383089

3139-
@_preprocess_data(label_namer=None)
3090+
@_preprocess_data()
31403091
def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,
31413092
positions=None, widths=None, patch_artist=None,
31423093
bootstrap=None, usermedians=None, conf_intervals=None,
@@ -4614,7 +4565,7 @@ def _quiver_units(self, args, kw):
46144565
return args
46154566

46164567
# args can by a combination if X, Y, U, V, C and all should be replaced
4617-
@_preprocess_data(replace_all_args=True, label_namer=None)
4568+
@_preprocess_data()
46184569
def quiver(self, *args, **kw):
46194570
# Make sure units are handled for x and y values
46204571
args = self._quiver_units(args, kw)
@@ -4627,13 +4578,12 @@ def quiver(self, *args, **kw):
46274578
quiver.__doc__ = mquiver.Quiver.quiver_doc
46284579

46294580
# args can by either Y or y1,y2,... and all should be replaced
4630-
@_preprocess_dat 2851 a(replace_all_args=True, label_namer=None)
4581+
@_preprocess_data()
46314582
def stackplot(self, x, *args, **kwargs):
46324583
return mstack.stackplot(self, x, *args, **kwargs)
46334584
stackplot.__doc__ = mstack.stackplot.__doc__
46344585

4635-
@_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"],
4636-
label_namer=None)
4586+
@_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"])
46374587
def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
46384588
cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
46394589
minlength=0.1, transform=None, zorder=None,
@@ -4658,7 +4608,7 @@ def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
46584608
streamplot.__doc__ = mstream.streamplot.__doc__
46594609

46604610
# args can be some combination of X, Y, U, V, C and all should be replaced
4661-
@_preprocess_data(replace_all_args=True, label_namer=None)
4611+
@_preprocess_data()
46624612
@docstring.dedent_interpd
46634613
def barbs(self, *args, **kw):
46644614
"""
@@ -4672,8 +4622,8 @@ def barbs(self, *args, **kw):
46724622
self.autoscale_view()
46734623
return b
46744624

4675-
@_preprocess_data(replace_names=["x", "y"], label_namer=None,
4676-
positional_parameter_names=["x", "y", "c"])
4625+
# Uses a custom implementation of data-kwarg handling in
4626+
# _process_plot_var_args.
46774627
def fill(self, *args, **kwargs):
46784628
"""
46794629
Plot filled polygons.
@@ -4720,8 +4670,7 @@ def fill(self, *args, **kwargs):
47204670
self.autoscale_view()
47214671
return patches
47224672

4723-
@_preprocess_data(replace_names=["x", "y1", "y2", "where"],
4724-
label_namer=None)
4673+
@_preprocess_data(replace_names=["x", "y1", "y2", "where"])
47254674
@docstring.dedent_interpd
47264675
def fill_between(self, x, y1, y2=0, where=None, interpolate=False,
47274676
step=None, **kwargs):
@@ -4903,8 +4852,7 @@ def get_interp_point(ind):
49034852
self.autoscale_view()
49044853
return collection
49054854

4906-
@_preprocess_data(replace_names=["y", "x1", "x2", "where"],
4907-
label_namer=None)
4855+
@_preprocess_data(replace_names=["y", "x1", "x2", "where"])
49084856
@docstring.dedent_interpd
49094857
def fill_betweenx(self, y, x1, x2=0, where=None,
49104858
step=None, interpolate=False, **kwargs):
@@ -5086,7 +5034,7 @@ def get_interp_point(ind):
50865034
return collection
50875035

50885036
#### plotting z(x,y): imshow, pcolor and relatives, contour
5089-
@_preprocess_data(label_namer=None)
5037+
@_preprocess_data()
50905038
def imshow(self, X, cmap=None, norm=None, aspect=None,
50915039
interpolation=None, alpha=None, vmin=None, vmax=None,
50925040
origin=None, extent=None, shape=None, filternorm=1,
@@ -5315,7 +5263,7 @@ def _pcolorargs(funcname, *args, **kw):
53155263
C = cbook.safe_masked_invalid(C)
53165264
return X, Y, C
53175265

5318-
@_preprocess_data(label_namer=None)
5266+
@_preprocess_data()
53195267
@docstring.dedent_interpd
53205268
def pcolor(self, *args, **kwargs):
53215269
"""
@@ -5561,7 +5509,7 @@ def pcolor(self, *args, **kwargs):
55615509
self.autoscale_view()
55625510
return collection
55635511

5564-
@_preprocess_data(label_namer=None)
5512+
@_preprocess_data()
55655513
@docstring.dedent_interpd
55665514
def pcolormesh(self, *args, **kwargs):
55675515
"""
@@ -5698,7 +5646,7 @@ def pcolormesh(self, *args, **kwargs):
56985646
self.autoscale_view()
56995647
return collection
57005648

5701-
@_preprocess_data(label_namer=None)
5649+
@_preprocess_data()
57025650
@docstring.dedent_interpd
57035651
def pcolorfast(self, *args, **kwargs):
57045652
"""
@@ -6443,7 +6391,7 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
64436391
else:
64446392
return tops, bins, cbook.silent_list('Lists of Patches', patches)
64456393

6446-
@_preprocess_data(replace_names=["x", "y", "weights"], label_namer=None)
6394+
@_preprocess_data(replace_names=["x", "y", "weights"])
64476395
def hist2d(self, x, y, bins=10, range=None, normed=False, weights=None,
64486396
cmin=None, cmax=None, **kwargs):
64496397
"""
@@ -6550,7 +6498,7 @@ def hist2d(self, x, y, bins=10, range=None, normed=False, weights=None,
65506498

65516499
return h, xedges, yedges, pc
65526500

6553-
@_preprocess_data(replace_names=["x"], label_namer=None)
6501+
@_preprocess_data(replace_names=["x"])
65546502
@docstring.dedent_interpd
65556503
def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
65566504
window=None, noverlap=None, pad_to=None,
@@ -6785,7 +6733,7 @@ def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None,
67856733
else:
67866734
return pxy, freqs, line
67876735

6788-
@_preprocess_data(replace_names=["x"], label_namer=None)
6736+
@_preprocess_data(replace_names=["x"])
67896737
@docstring.dedent_interpd
67906738
def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,
67916739
pad_to=None, sides=None, scale=None,
@@ -6888,7 +6836,7 @@ def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,
68886836

68896837
return spec, freqs, lines[0]
68906838

6891-
@_preprocess_data(replace_names=["x"], label_namer=None)
6839+
@_preprocess_data(replace_names=["x"])
68926840
@docstring.dedent_interpd
68936841
def angle_spectrum(self, x, Fs=None, Fc=None, window=None,
68946842
pad_to=None, sides=None, **kwargs):
@@ -6970,7 +6918,7 @@ def angle_spectrum(self, x, Fs=None, Fc=None, window=None,
69706918

69716919
return spec, freqs, lines[0]
69726920

6973-
@_preprocess_data(replace_names=["x"], label_namer=None)
6921+
@_preprocess_data(replace_names=["x"])
69746922
@docstring.dedent_interpd
69756923
def phase_spectrum(self, x, Fs=None, Fc=None, window=None,
69766924
pad_to=None, sides=None, **kwargs):
@@ -7051,7 +6999,7 @@ def phase_spectrum(self, x, Fs=None, Fc=None, window=None,
70516999

70527000
return spec, freqs, lines[0]
70537001

7054-
@_preprocess_data(replace_names=["x", "y"], label_namer=None)
7002+
@_preprocess_data(replace_names=["x", "y"])
70557003
@docstring.dedent_interpd
70567004
def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
70577005
window=mlab.window_hanning, noverlap=0, pad_to=None,
@@ -7116,7 +7064,7 @@ def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
71167064

71177065
return cxy, freqs
71187066

7119-
@_preprocess_data(replace_names=["x"], label_namer=None)
7067+
@_preprocess_data(replace_names=["x"])
71207068
@docstring.dedent_interpd
71217069
def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
71227070
window=None, noverlap=None,
@@ -7441,7 +7389,7 @@ def matshow(self, Z, **kwargs):
74417389
integer=True))
74427390
return im
74437391

7444-
@_preprocess_data(replace_names=["dataset"], label_namer=None)
7392+
@_preprocess_data(replace_names=["dataset"])
74457393
def violinplot(self, dataset, positions=None, vert=True, widths=0.5,
74467394
showmeans=False, showextrema=True, showmedians=False,
74477395
points=100, bw_method=None):

0 commit comments

Comments
 (0)
0