Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 965f599

Browse files
committed
Make kwargs names in scale.py not include the axis direction.
- Make names of kwargs to Scale subclasses independent of whether the underlying axis is x or y (so that after the deprecation period, one can just have a normal signature -- `def __init__(self, *, base=10, ...)`. We could possibly also change semilogx and semilogy to use the unsuffixed names (with deprecation), leaving only loglog with the suffixed names, or even also make loglog use unsuffixed names, in which case it would become impossible to set separate x and y bases directly in loglog -- one should then do `gca().set_xscale("log", base=...)` which doesn't seem too onerous. (loglog is the only case where the suffixed names has *some* utility.) In general, note that having kwargs that depend on the axis direction doesn't really scale -- for example, if we were to finally add log-scale support to mplot3d, should scale.py know about it and add `basez`? Should we have `baser` for log-scale polar plots? (at least in the radial direction, they make sense) - Move argument validation up the the Transform subclasses. - Make SymmetricalLogScale.{base,linthresh,linscale} properties mapping to the underlying transform so that they can't go out of sync.
1 parent 1cd9137 commit 965f599

File tree

9 files changed

+88
-100
lines changed

9 files changed

+88
-100
lines changed

doc/api/next_api_changes/deprecations.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,13 @@ PDF and PS character tracking internals
4747
The ``used_characters`` attribute and ``track_characters`` and
4848
``merge_used_characters`` methods of `.RendererPdf`, `.PdfFile`, and
4949
`.RendererPS` are deprecated.
50+
51+
Signature of `.LogScale` and `.SymLogScale`
52+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
53+
These classes used to take keyword arguments that depends on the axis
54+
orientation ("basex" vs "basey", "nonposx" vs "nonposy"); these parameter
55+
names are now deprecated in favor of "base", "nonpos", etc. This deprecation
56+
also affects e.g. ``ax.set_yscale("log", basey=...)`` which must now be
57+
spelled ``ax.set_yscale("log", base=...)``. The only place where "basex", etc.
58+
remain in use is in the helper functions `~.Axes.loglog`, `~.Axes.semilogx`,
59+
and `~.Axes.semilogy` (because `~.Axes.loglog` takes both "basex" and "basey").

examples/scales/log_demo.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
ax2.grid()
2727

2828
# log x and y axis
29-
ax3.loglog(t, 20 * np.exp(-t / 10.0), basex=2)
29+
ax3.loglog(t, 20 * np.exp(-t / 10.0))
30+
ax3.set_xscale('log', base=2)
3031
ax3.set(title='loglog base 2 on x')
3132
ax3.grid()
3233

@@ -35,8 +36,8 @@
3536
x = 10.0**np.linspace(0.0, 2.0, 20)
3637
y = x**2.0
3738

38-
ax4.set_xscale("log", nonposx='clip')
39-
ax4.set_yscale("log", nonposy='clip')
39+
ax4.set_xscale("log", nonpos='clip')
40+
ax4.set_yscale("log", nonpos='clip')
4041
ax4.set(title='Errorbars go negative')
4142
ax4.errorbar(x, y, xerr=0.1 * x, yerr=5.0 + 0.75 * y)
4243
# ylim must be set after errorbar to allow errorbar to autoscale limits

examples/scales/scales.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
# symmetric log
4646
ax = axs[1, 1]
4747
ax.plot(x, y - y.mean())
48-
ax.set_yscale('symlog', linthreshy=0.02)
48+
ax.set_yscale('symlog', linthresh=0.02)
4949
ax.set_title('symlog')
5050
ax.grid(True)
5151

examples/scales/symlog_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
plt.subplot(313)
2828
plt.plot(x, np.sin(x / 3.0))
2929
plt.xscale('symlog')
30-
plt.yscale('symlog', linthreshy=0.015)
30+
plt.yscale('symlog', linthresh=0.015)
3131
plt.grid(True)
3232
plt.ylabel('symlog both')
3333

lib/matplotlib/axes/_axes.py

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1802,16 +1802,13 @@ def loglog(self, *args, **kwargs):
18021802
**kwargs
18031803
All parameters supported by `.plot`.
18041804
"""
1805-
dx = {k: kwargs.pop(k) for k in ['basex', 'subsx', 'nonposx']
1805+
dx = {k[:-1]: kwargs.pop(k) for k in ['basex', 'subsx', 'nonposx']
18061806
if k in kwargs}
1807-
dy = {k: kwargs.pop(k) for k in ['basey', 'subsy', 'nonposy']
1808-
if k in kwargs}
1809-
18101807
self.set_xscale('log', **dx)
1808+
dy = {k[:-1]: kwargs.pop(k) for k in ['basey', 'subsy', 'nonposy']
1809+
if k in kwargs}
18111810
self.set_yscale('log', **dy)
1812-
1813-
l = self.plot(*args, **kwargs)
1814-
return l
1811+
return self.plot(*args, **kwargs)
18151812

18161813
# @_preprocess_data() # let 'plot' do the unpacking..
18171814
@docstring.dedent_interpd
@@ -1855,12 +1852,10 @@ def semilogx(self, *args, **kwargs):
18551852
**kwargs
18561853
All parameters supported by `.plot`.
18571854
"""
1858-
d = {k: kwargs.pop(k) for k in ['basex', 'subsx', 'nonposx']
1855+
d = {k[:-1]: kwargs.pop(k) for k in ['basex', 'subsx', 'nonposx']
18591856
if k in kwargs}
1860-
18611857
self.set_xscale('log', **d)
1862-
l = self.plot(*args, **kwargs)
1863-
return l
1858+
return self.plot(*args, **kwargs)
18641859

18651860
# @_preprocess_data() # let 'plot' do the unpacking..
18661861
@docstring.dedent_interpd
@@ -1904,12 +1899,10 @@ def semilogy(self, *args, **kwargs):
19041899
**kwargs
19051900
All parameters supported by `.plot`.
19061901
"""
1907-
d = {k: kwargs.pop(k) for k in ['basey', 'subsy', 'nonposy']
1902+
d = {k[:-1]: kwargs.pop(k) for k in ['basey', 'subsy', 'nonposy']
19081903
if k in kwargs}
19091904
self.set_yscale('log', **d)
1910-
l = self.plot(*args, **kwargs)
1911-
1912-
return l
1905+
return self.plot(*args, **kwargs)
19131906

19141907
@_preprocess_data(replace_names=["x"], label_namer="x")
19151908
def acorr(self, x, **kwargs):
@@ -2350,11 +2343,11 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
23502343
if orientation == 'vertical':
23512344
self._process_unit_info(xdata=x, ydata=height, kwargs=kwargs)
23522345
if log:
2353-
self.set_yscale('log', nonposy='clip')
2346+
self.set_yscale('log', nonpos='clip')
23542347
elif orientation == 'horizontal':
23552348
self._process_unit_info(xdata=width, ydata=y, kwargs=kwargs)
23562349
if log:
2357-
self.set_xscale('log', nonposx='clip')
2350+
self.set_xscale('log', nonpos='clip')
23582351

23592352
# lets do some conversions now since some types cannot be
23602353
# subtracted uniformly
@@ -6780,9 +6773,9 @@ def hist(self, x, bins=None, range=None, density=False, weights=None,
67806773

67816774
if log:
67826775
if orientation == 'horizontal':
6783-
self.set_xscale('log', nonposx='clip')
6776+
self.set_xscale('log', nonpos='clip')
67846777
else: # orientation == 'vertical'
6785-
self.set_yscale('log', nonposy='clip')
6778+
self.set_yscale('log', nonpos='clip')
67866779

67876780
if align == 'left':
67886781
x -= 0.5*(bins[1]-bins[0])

lib/matplotlib/scale.py

Lines changed: 50 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,11 @@ class LogTransform(Transform):
280280

281281
def __init__(self, base, nonpos='clip'):
282282
Transform.__init__(self)
283+
if base <= 0 or base == 1:
284+
raise ValueError('The log base cannot be <= 0 or == 1')
283285
self.base = base
284-
self._clip = {"clip": True, "mask": False}[nonpos]
286+
self._clip = cbook._check_getitem(
287+
{"clip": True, "mask": False}, nonpos=nonpos)
285288

286289
def __str__(self):
287290
return "{}(base={}, nonpos={!r})".format(
@@ -353,41 +356,28 @@ def __init__(self, axis, **kwargs):
353356
----------
354357
axis : `~matplotlib.axis.Axis`
355358
The axis for the scale.
356-
basex, basey : float, default: 10
359+
base : float, default: 10
357360
The base of the logarithm.
358-
nonposx, nonposy : {'clip', 'mask'}, default: 'clip'
361+
nonpos : {'clip', 'mask'}, default: 'clip'
359362
Determines the behavior for non-positive values. They can either
360363
be masked as invalid, or clipped to a very small positive number.
361-
subsx, subsy : sequence of int, default: None
362-
Where to place the subticks between each major tick.
363-
For example, in a log10 scale: ``[2, 3, 4, 5, 6, 7, 8, 9]``
364-
will place 8 logarithmically spaced minor ticks between
365-
each major tick.
364+
subs : sequence of int, default: None
365+
Where to place the subticks between each major tick. For example,
366+
in a log10 scale, ``[2, 3, 4, 5, 6, 7, 8, 9]`` will place 8
367+
logarithmically spaced minor ticks between each major tick.
366368
"""
367-
if axis.axis_name == 'x':
368-
base = kwargs.pop('basex', 10.0)
369-
subs = kwargs.pop('subsx', None)
370-
nonpos = kwargs.pop('nonposx', 'clip')
371-
cbook._check_in_list(['mask', 'clip'], nonposx=nonpos)
372-
else:
373-
base = kwargs.pop('basey', 10.0)
374-
subs = kwargs.pop('subsy', None)
375-
nonpos = kwargs.pop('nonposy', 'clip')
376-
cbook._check_in_list(['mask', 'clip'], nonposy=nonpos)
377-
378-
if kwargs:
379-
raise TypeError(f"LogScale got an unexpected keyword "
380-
f"argument {next(iter(kwargs))!r}")
381-
382-
if base <= 0 or base == 1:
383-
raise ValueError('The log base cannot be <= 0 or == 1')
384-
369+
axis_name = getattr(axis, "axis_name", "x")
370+
@cbook._rename_parameter("3.3", f"base{axis_name}", "base")
371+
@cbook._rename_parameter("3.3", f"subs{axis_name}", "subs")
372+
@cbook._rename_parameter("3.3", f"nonpos{axis_name}", "nonpos")
373+
def __init__(*, base=10, subs=None, nonpos='clip'):
374+
return base, subs, nonpos
375+
376+
base, subs, nonpos = __init__(**kwargs)
385377
self._transform = LogTransform(base, nonpos)
386378
self.subs = subs
387379

388-
@property
389-
def base(self):
390-
return self._transform.base
380+
base = property(lambda self: self._transform.base)
391381

392382
def set_default_locators_and_formatters(self, axis):
393383
# docstring inherited
@@ -455,6 +445,12 @@ class SymmetricalLogTransform(Transform):
455445

456446
def __init__(self, base, linthresh, linscale):
457447
Transform.__init__(self)
448+
if base <= 1.0:
449+
raise ValueError("'base' must be larger than 1")
450+
if linthresh <= 0.0:
451+
raise ValueError("'linthresh' must be positive")
452+
if linscale <= 0.0:
453+
raise ValueError("'linscale' must be positive")
458454
self.base = base
459455
self.linthresh = linthresh
460456
self.linscale = linscale
@@ -515,19 +511,19 @@ class SymmetricalLogScale(ScaleBase):
515511
516512
Parameters
517513
----------
518-
basex, basey : float
514+
base : float
519515
The base of the logarithm. Defaults to 10.
520516
521-
linthreshx, linthreshy : float
517+
linthresh : float
522518
Defines the range ``(-x, x)``, within which the plot is linear.
523519
This avoids having the plot go to infinity around zero. Defaults to 2.
524520
525-
subsx, subsy : sequence of int
521+
subs : sequence of int
526522
Where to place the subticks between each major tick.
527523
For example, in a log10 scale: ``[2, 3, 4, 5, 6, 7, 8, 9]`` will place
528524
8 logarithmically spaced minor ticks between each major tick.
529525
530-
linscalex, linscaley : float, optional
526+
linscale : float, optional
531527
This allows the linear range ``(-linthresh, linthresh)`` to be
532528
stretched relative to the logarithmic range. Its value is the number of
533529
decades to use for each half of the linear range. For example, when
@@ -541,40 +537,30 @@ class SymmetricalLogScale(ScaleBase):
541537
InvertedSymmetricalLogTransform = InvertedSymmetricalLogTransform
542538

543539
def __init__(self, axis, **kwargs):
544-
if axis.axis_name == 'x':
545-
base = kwargs.pop('basex', 10.0)
546-
linthresh = kwargs.pop('linthreshx', 2.0)
547-
subs = kwargs.pop('subsx', None)
548-
linscale = kwargs.pop('linscalex', 1.0)
549-
else:
550-
base = kwargs.pop('basey', 10.0)
551-
linthresh = kwargs.pop('linthreshy', 2.0)
552-
subs = kwargs.pop('subsy', None)
553-
linscale = kwargs.pop('linscaley', 1.0)
554-
if kwargs:
555-
warn_deprecated(
556-
'3.2.0',
557-
message=(
558-
f"SymmetricalLogScale got an unexpected keyword "
559-
f"argument {next(iter(kwargs))!r}. "
560-
'In the future this will raise TypeError')
561-
)
562-
# raise TypeError(f"SymmetricalLogScale got an unexpected keyword "
563-
# f"argument {next(iter(kwargs))!r}")
564-
565-
if base <= 1.0:
566-
raise ValueError("'basex/basey' must be larger than 1")
567-
if linthresh <= 0.0:
568-
raise ValueError("'linthreshx/linthreshy' must be positive")
569-
if linscale <= 0.0:
570-
raise ValueError("'linscalex/linthreshy' must be positive")
571-
540+
axis_name = getattr(axis, "axis_name", "x")
541+
@cbook._rename_parameter("3.3", f"base{axis_name}", "base")
542+
@cbook._rename_parameter("3.3", f"linthresh{axis_name}", "linthresh")
543+
@cbook._rename_parameter("3.3", f"subs{axis_name}", "subs")
544+
@cbook._rename_parameter("3.3", f"linscale{axis_name}", "linscale")
545+
def __init__(*, base=10, linthresh=2, subs=None, linscale=1, **kwargs):
546+
if kwargs:
547+
warn_deprecated(
548+
"3.2.0",
549+
message=(
550+
f"SymmetricalLogScale got an unexpected keyword "
551+
f"argument {next(iter(kwargs))!r}; in the future, "
552+
f"this will raise a TypeError")
553+
)
554+
return base, linthresh, subs, linscale
555+
556+
base, linthresh, subs, linscale = __init__(**kwargs)
572557
self._transform = SymmetricalLogTransform(base, linthresh, linscale)
573-
self.base = base
574-
self.linthresh = linthresh
575-
self.linscale = linscale
576558
self.subs = subs
577559

560+
base = property(lambda self: self._transform.base)
561+
linthresh = property(lambda self: self._transform.linthresh)
562+
linscale = property(lambda self: self._transform.linscale)
563+
578564
def set_default_locators_and_formatters(self, axis):
579565
# docstring inherited
580566
axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))

lib/matplotlib/tests/test_axes.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,9 +1118,9 @@ def test_symlog2():
11181118
x = np.arange(-50, 50, 0.001)
11191119

11201120
fig, axs = plt.subplots(5, 1)
1121-
for ax, linthreshx in zip(axs, [20., 2., 1., 0.1, 0.01]):
1121+
for ax, linthresh in zip(axs, [20., 2., 1., 0.1, 0.01]):
11221122
ax.plot(x, x)
1123-
ax.set_xscale('symlog', linthreshx=linthreshx)
1123+
ax.set_xscale('symlog', linthresh=linthresh)
11241124
ax.grid(True)
11251125
axs[-1].set_ylim(-0.1, 0.1)
11261126

@@ -2187,9 +2187,9 @@ def test_log_scales():
21872187
fig = plt.figure()
21882188
ax = fig.add_subplot(1, 1, 1)
21892189
ax.plot(np.log(np.linspace(0.1, 100)))
2190-
ax.set_yscale('log', basey=5.5)
2190+
ax.set_yscale('log', base=5.5)
21912191
ax.invert_yaxis()
2192-
ax.set_xscale('log', basex=9.0)
2192+
ax.set_xscale('log', base=9.0)
21932193

21942194

21952195
def test_log_scales_no_data():

lib/matplotlib/tests/test_scale.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def test_log_scatter():
8888

8989
def test_logscale_subs():
9090
fig, ax = plt.subplots()
91-
ax.set_yscale('log', subsy=np.array([2, 3, 4]))
91+
ax.set_yscale('log', subs=np.array([2, 3, 4]))
9292
# force draw
9393
fig.canvas.draw()
9494

@@ -108,16 +108,14 @@ def test_logscale_mask():
108108
def test_extra_kwargs_raise_or_warn():
109109
fig, ax = plt.subplots()
110110

111-
# with pytest.raises(TypeError):
112111
with pytest.warns(MatplotlibDeprecationWarning):
113-
ax.set_yscale('linear', nonpos='mask')
112+
ax.set_yscale('linear', foo='mask')
114113

115114
with pytest.raises(TypeError):
116-
ax.set_yscale('log', nonpos='mask')
115+
ax.set_yscale('log', foo='mask')
117116

118-
# with pytest.raises(TypeError):
119117
with pytest.warns(MatplotlibDeprecationWarning):
120-
ax.set_yscale('symlog', nonpos='mask')
118+
ax.set_yscale('symlog', foo='mask')
121119

122120

123121
def test_logscale_invert_transform():
@@ -150,7 +148,7 @@ def test_logscale_nonpos_values():
150148
ax1.hist(xs, range=(-5, 5), bins=10)
151149
ax1.set_yscale('log')
152150
ax2.hist(xs, range=(-5, 5), bins=10)
153-
ax2.set_yscale('log', nonposy='mask')
151+
ax2.set_yscale('log', nonpos='mask')
154152

155153
xdata = np.arange(0, 10, 0.01)
156154
ydata = np.exp(-xdata)

tutorials/introductory/pyplot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,7 @@ def f(t):
449449
# symmetric log
450450
plt.subplot(223)
451451
plt.plot(x, y - y.mean())
452-
plt.yscale('symlog', linthreshy=0.01)
452+
plt.yscale('symlog', linthresh=0.01)
453453
plt.title('symlog')
454454
plt.grid(True)
455455

0 commit comments

Comments
 (0)