8000 Merge pull request #10928 from anntzer/process-plot-args · matplotlib/matplotlib@3826ee5 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3826ee5

Browse files
authored
Merge pull request #10928 from anntzer/process-plot-args
MNT: Simplify (quite a bit...) _preprocess_data
2 parents 87085bd + 434a6a5 commit 3826ee5

File tree

7 files changed

+271
-522
lines changed

7 files changed

+271
-522
lines changed
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.
6D40

doc/api/next_api_changes/2018-08-17-AL-deprecations.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@ The following API elements are deprecated:
66
- ``get_py2exe_datafiles``, ``tk_window_focus``,
77
- ``backend_ps.PsBackendHelper``, ``backend_ps.ps_backend_helper``,
88
- ``cbook.iterable``,
9+
- ``cbook.get_label``, ``cbook.iterable``,
910
- ``font_manager.OSXInstalledFonts``,
1011
- ``mlab.demean``,

lib/matplotlib/__init__.py

Lines changed: 136 additions & 235 deletions
Large diffs are not rendered by default.

lib/matplotlib/axes/_axes.py

Lines changed: 48 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -42,46 +42,6 @@
4242
rcParams = matplotlib.rcParams
4343

4444

45-
def _has_item(data, name):
46-
"""Return whether *data* can be item-accessed with *name*.
47-
48-
This supports data with a dict-like interface (`in` checks item
49-
availability) and with numpy.arrays.
50-
"""
51-
try:
52-
return data.dtype.names is not None and name in data.dtype.names
53-
except AttributeError: # not a numpy array
54-
return name in data
55-
56-
57-
def _plot_args_replacer(args, data):
58-
if len(args) == 1:
59-
return ["y"]
60-
elif len(args) == 2:
61-
# this can be two cases: x,y or y,c
62-
if not _has_item(data, args[1]):
63-
return ["y", "c"]
64-
# it's data, but could be a color code like 'ro' or 'b--'
65-
# -> warn the user in that case...
66-
try:
67-
_process_plot_format(args[1])
68-
except ValueError:
69-
pass
70-
else:
71-
cbook._warn_external(
72-
"Second argument {!r} is ambiguous: could be a color spec but "
73-
"is in data; using as data. Either rename the entry in data "
74-
"or use three arguments to plot.".format(args[1]),
75-
RuntimeWarning)
76-
return ["x", "y"]
77-
elif len(args) == 3:
78-
return ["x", "y", "c"]
79-
else:
80-
raise ValueError("Using arbitrary long args with data is not "
81-
"supported due to ambiguity of arguments.\nUse "
82-
"multiple plotting calls instead.")
83-
84-
8545
def _make_inset_locator(bounds, trans, parent):
8646
"""
8747
Helper function to locate inset axes, used in
@@ -1154,8 +1114,7 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid',
11541114

11551115
@_preprocess_data(replace_names=["positions", "lineoffsets",
11561116
"linelengths", "linewidths",
1157-
"colors", "linestyles"],
1158-
label_namer=None)
1117+
"colors", "linestyles"])
11591118
@docstring.dedent_interpd
11601119
def eventplot(self, positions, orientation='horizontal', lineoffsets=1,
11611120
linelengths=1, linewidths=None, colors=None,
@@ -1369,13 +1328,12 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1,
13691328

13701329
return colls
13711330

1372-
# ### Basic plotting
1373-
# The label_naming happens in `matplotlib.axes._base._plot_args`
1374-
@_preprocess_data(replace_names=["x", "y"],
1375-
positional_parameter_names=_plot_args_replacer,
1376-
label_namer=None)
1331+
#### Basic plotting
1332+
1333+
# Uses a custom implementation of data-kwarg handling in
1334+
# _process_plot_var_args.
13771335
@docstring.dedent_interpd
1378-
def plot(self, *args, scalex=True, scaley=True, **kwargs):
1336+
def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs):
13791337
"""
13801338
Plot y versus x as lines and/or markers.
13811339
@@ -1486,7 +1444,6 @@ def plot(self, *args, scalex=True, scaley=True, **kwargs):
14861444
You may suppress the warning by adding an empty format string
14871445
`plot('n', 'o', '', data=obj)`.
14881446
1489-
14901447
Other Parameters
14911448
----------------
14921449
scalex, scaley : bool, optional, default: True
@@ -1513,13 +1470,11 @@ def plot(self, *args, scalex=True, scaley=True, **kwargs):
15131470
lines
15141471
A list of `.Line2D` objects representing the plotted data.
15151472
1516-
15171473
See Also
15181474
--------
15191475
scatter : XY scatter plot with markers of varying size and/or color (
15201476
sometimes also called bubble chart).
15211477
1522-
15231478
Notes
15241479
-----
15251480
**Format Strings**
@@ -1606,14 +1561,10 @@ def plot(self, *args, scalex=True, scaley=True, **kwargs):
16061561
additionally use any `matplotlib.colors` spec, e.g. full names
16071562
(``'green'``) or hex strings (``'#008000'``).
16081563
"""
1609-
lines = []
1610-
16111564
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
1612-
1613-
for line in self._get_lines(*args, **kwargs):
1565+
lines = [*self._get_lines(*args, data=data, **kwargs)]
1566+
for line in lines:
16141567
self.add_line(line)
1615-
lines.append(line)
1616-
16171568
self.autoscale_view(scalex=scalex, scaley=scaley)
16181569
return lines
16191570

@@ -1996,8 +1947,8 @@ def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,
19961947

19971948
#### Specialized plotting
19981949

1999-
@_preprocess_data(replace_names=["x", "y"], label_namer="y")
2000-
def step(self, x, y, *args, where='pre', **kwargs):
1950+
# @_preprocess_data() # let 'plot' do the unpacking..
1951+
def step(self, x, y, *args, where='pre', data=None, **kwargs):
20011952
"""
20021953
Make a step plot.
20031954
@@ -2062,17 +2013,9 @@ def step(self, x, y, *args, where='pre', **kwargs):
20622013
raise ValueError("'where' argument to step must be "
20632014
"'pre', 'post' or 'mid'")
20642015
kwargs['drawstyle'] = 'steps-' + where
2065-
return self.plot(x, y, *args, **kwargs)
2066-
2067-
@_preprocess_data(replace_names=["x", "left",
2068-
"height", "width",
2069-
"y", "bottom",
2070-
"color", "edgecolor", "linewidth",
2071-
"tick_label", "xerr", "yerr",
2072-
"ecolor"],
2073-
label_namer=None,
2074-
replace_all_args=True
2075-
)
2016+
return self.plot(x, y, *args, data=data, **kwargs)
2017+
2018+
@_preprocess_data()
20762019
@docstring.dedent_interpd
20772020
def bar(self, x, height, width=0.8, bottom=None, *, align="center",
20782021
**kwargs):
@@ -2464,7 +2407,7 @@ def barh(self, y, width, height=0.8, left=None, *, align="center",
24642407
align=align, **kwargs)
24652408
return patches
24662409

2467-
@_preprocess_data(label_namer=None)
2410+
@_preprocess_data()
24682411
@docstring.dedent_interpd
24692412
def broken_barh(self, xranges, yrange, **kwargs):
24702413
"""
@@ -2535,9 +2478,9 @@ def broken_barh(self, xranges, yrange, **kwargs):
25352478

25362479
return col
25372480

2538-
@_preprocess_data(replace_all_args=True, label_namer=None)
2539-
def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None,
2540-
bottom=0, label=None):
2481+
@_preprocess_data()
2482+
def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
2483+
label=None):
25412484
"""
25422485
Create a stem plot.
25432486
@@ -2695,8 +2638,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None,
26952638

26962639
return stem_container
26972640

2698-
@_preprocess_data(replace_names=["x", "explode", "labels", "colors"],
2699-
label_namer=None)
2641+
@_preprocess_data(replace_names=["x", "explode", "labels", "colors"])
27002642
def pie(self, x, explode=None, labels=None, colors=None,
27012643
autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,
27022644
startangle=None, radius=None, counterclock=True,
@@ -3313,7 +3255,7 @@ def extract_err(err, data):
33133255

33143256
return errorbar_container # (l0, caplines, barcols)
33153257

3316-
@_preprocess_data(label_namer=None)
3258+
@_preprocess_data()
33173259
def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,
33183260
positions=None, widths=None, patch_artist=None,
33193261
bootstrap=None, usermedians=None, conf_intervals=None,
@@ -4908,7 +4850,7 @@ def _quiver_units(self, args, kw):
49084850
return args
49094851

49104852
# args can by a combination if X, Y, U, V, C and all should be replaced
4911-
@_preprocess_data(replace_all_args=True, label_namer=None)
4853+
@_preprocess_data()
49124854
def 10000 quiver(self, *args, **kw):
49134855
# Make sure units are handled for x and y values
49144856
args = self._quiver_units(args, kw)
@@ -4921,13 +4863,12 @@ def quiver(self, *args, **kw):
49214863
quiver.__doc__ = mquiver.Quiver.quiver_doc
49224864

49234865
# args can by either Y or y1,y2,... and all should be replaced
4924-
@_preprocess_data(replace_all_args=True, label_namer=None)
4866+
@_preprocess_data()
49254867
def stackplot(self, x, *args, **kwargs):
49264868
return mstack.stackplot(self, x, *args, **kwargs)
49274869
stackplot.__doc__ = mstack.stackplot.__doc__
49284870

4929-
@_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"],
4930-
label_namer=None)
4871+
@_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"])
49314872
def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
49324873
cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
49334874
minlength=0.1, transform=None, zorder=None,
@@ -4952,7 +4893,7 @@ def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
49524893
streamplot.__doc__ = mstream.streamplot.__doc__
49534894

49544895
# args can be some combination of X, Y, U, V, C and all should be replaced
4955-
@_preprocess_data(replace_all_args=True, label_namer=None)
4896+
@_preprocess_data()
49564897
@docstring.dedent_interpd
49574898
def barbs(self, *args, **kw):
49584899
"""
@@ -4966,9 +4907,9 @@ def barbs(self, *args, **kw):
49664907
self.autoscale_view()
49674908
return b
49684909

4969-
@_preprocess_data(replace_names=["x", "y"], label_namer=None,
4970-
positional_parameter_names=["x", "y", "c"])
4971-
def fill(self, *args, **kwargs):
4910+
# Uses a custom implementation of data-kwarg handling in
4911+
# _process_plot_var_args.
4912+
def fill(self, *args, data=None, **kwargs):
49724913
"""
49734914
Plot filled polygons.
49744915
@@ -4991,6 +4932,13 @@ def fill(self, *args, **kwargs):
49914932
ax.fill(x, y, x2, y2) # two polygons
49924933
ax.fill(x, y, "b", x2, y2, "r") # a blue and a red polygon
49934934
4935+
data : indexable object, optional
4936+
An object with labelled data. If given, provide the label names to
4937+
plot in *x* and *y*, e.g.::
4938+
4939+
ax.fill("time", "signal",
4940+
data={"time": [0, 1, 2], "signal": [0, 1, 0]})
4941+
49944942
Returns
49954943
-------
49964944
a list of :class:`~matplotlib.patches.Polygon`
@@ -5008,14 +4956,13 @@ def fill(self, *args, **kwargs):
50084956
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
50094957

50104958
patches = []
5011-
for poly in self._get_patches_for_fill(*args, **kwargs):
4959+
for poly in self._get_patches_for_fill(*args, data=data, **kwargs):
50124960
self.add_patch(poly)
50134961
patches.append(poly)
50144962
self.autoscale_view()
50154963
return patches
50164964

5017-
@_preprocess_data(replace_names=["x", "y1", "y2", "where"],
5018-
label_namer=None)
4965+
@_preprocess_data(replace_names=["x", "y1", "y2", "where"])
50194966
@docstring.dedent_interpd
50204967
def fill_between(self, x, y1, y2=0, where=None, interpolate=False,
50214968
step=None, **kwargs):
@@ -5197,8 +5144,7 @@ def get_interp_point(ind):
51975144
self.autoscale_view()
51985145
return collection
51995146

5200-
@_preprocess_data(replace_names=["y", "x1", "x2", "where"],
5201-
label_namer=None)
5147+
@_preprocess_data(replace_names=["y", "x1", "x2", "where"])
52025148
@docstring.dedent_interpd
52035149
def fill_betweenx(self, y, x1, x2=0, where=None,
52045150
step=None, interpolate=False, **kwargs):
@@ -5380,7 +5326,7 @@ def get_interp_point(ind):
53805326
return collection
53815327

53825328
#### plotting z(x,y): imshow, pcolor and relatives, contour
5383-
@_preprocess_data(label_namer=None)
5329+
@_preprocess_data()
53845330
def imshow(self, X, cmap=None, norm=None, aspect=None,
53855331
interpolation=None, alpha=None, vmin=None, vmax=None,
53865332
origin=None, extent=None, shape=None, filternorm=1,
@@ -5647,7 +5593,7 @@ def _pcolorargs(funcname, *args, allmatch=False):
56475593
C = cbook.safe_masked_invalid(C)
56485594
return X, Y, C
56495595

5650-
@_preprocess_data(label_namer=None)
5596+
@_preprocess_data()
56515597
@docstring.dedent_interpd
56525598
def pcolor(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
56535599
vmax=None, **kwargs):
@@ -5884,7 +5830,7 @@ def pcolor(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
58845830
self.autoscale_view()
58855831
return collection
58865832

5887-
@_preprocess_data(label_namer=None)
5833+
@_preprocess_data()
58885834
@docstring.dedent_interpd
58895835
def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
58905836
vmax=None, shading='flat', antialiased=False, **kwargs):
@@ -6097,7 +6043,7 @@ def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
60976043
self.autoscale_view()
60986044
return collection
60996045

6100-
@_preprocess_data(label_namer=None)
6046+
@_preprocess_data()
61016047
@docstring.dedent_interpd
61026048
def pcolorfast(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
61036049
vmax=None, **kwargs):
@@ -6863,7 +6809,7 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
68636809
else:
68646810
return tops, bins, cbook.silent_list('Lists of Patches', patches)
68656811

6866-
@_preprocess_data(replace_names=["x", "y", "weights"], label_namer=None)
6812+
@_preprocess_data(replace_names=["x", "y", "weights"])
68676813
def hist2d(self, x, y, bins=10, range=None, normed=False, weights=None,
68686814
cmin=None, cmax=None, **kwargs):
68696815
"""
@@ -6971,7 +6917,7 @@ def hist2d(self, x, y, bins=10, range=None, normed=False, weights=None,
69716917

69726918
return h, xedges, yedges, pc
69736919

6974-
@_preprocess_data(replace_names=["x"], label_namer=None)
6920+
@_preprocess_data(replace_names=["x"])
69756921
@docstring.dedent_interpd
69766922
def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
69776923
window=None, noverlap=None, pad_to=None,
@@ -7206,7 +7152,7 @@ def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None,
72067152
else:
72077153
return pxy, freqs, line
72087154

7209-
@_preprocess_data(replace_names=["x"], label_namer=None)
7155+
@_preprocess_data(replace_names=["x"])
72107156
@docstring.dedent_interpd
72117157
def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,
72127158
pad_to=None, sides=None, scale=None,
@@ -7309,7 +7255,7 @@ def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,
73097255

73107256
return spec, freqs, lines[0]
73117257

7312-
@_preprocess_data(replace_names=["x"], label_namer=None)
7258+
@_preprocess_data(replace_names=["x"])
73137259
@docstring.dedent_interpd
73147260
def angle_spectrum(self, x, Fs=None, Fc=None, window=None,
73157261
pad_to=None, sides=None, **kwargs):
@@ -7391,7 +7337,7 @@ def angle_spectrum(self, x, Fs=None, Fc=None, window=None,
73917337

73927338
return spec, freqs, lines[0]
73937339

7394-
@_preprocess_data(replace_names=["x"], label_namer=None)
7340+
@_preprocess_data(replace_names=["x"])
73957341
@docstring.dedent_interpd
73967342
def phase_spectrum(self, x, Fs=None, Fc=None, window=None,
73977343
pad_to=None, sides=None, **kwargs):
@@ -7472,7 +7418,7 @@ def phase_spectrum(self, x, Fs=None, Fc=None, window=None,
74727418

74737419
return spec, freqs, lines[0]
74747420

7475-
@_preprocess_data(replace_names=["x", "y"], label_namer=None)
7421+
@_preprocess_data(replace_names=["x", "y"])
74767422
B706 @docstring.dedent_interpd
74777423
def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
74787424
window=mlab.window_hanning, noverlap=0, pad_to=None,
@@ -7537,7 +7483,7 @@ def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
75377483

75387484
return cxy, freqs
75397485

7540-
@_preprocess_data(replace_names=["x"], label_namer=None)
7486+
@_preprocess_data(replace_names=["x"])
75417487
@docstring.dedent_interpd
75427488
def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
75437489
window=None, noverlap=None,
@@ -7889,7 +7835,7 @@ def matshow(self, Z, **kwargs):
78897835
integer=True))
78907836
return im
78917837

7892-
@_preprocess_data(replace_names=["dataset"], label_namer=None)
7838+
@_preprocess_data(replace_names=["dataset"])
78937839
def violinplot(self, dataset, positions=None, vert=True, widths=0.5,
78947840
showmeans=False, showextrema=True, showmedians=False,
78957841
points=100, bw_method=None):

0 commit comments

Comments
 (0)
0