Skip to content

Commit 4cc7ef3

Browse files
authored
Merge pull request #23192 from oscargus/axesbasetest
Add tests, improve error messages in axis/_base, and code cleanup
2 parents 3407cbc + bf3a554 commit 4cc7ef3

File tree

3 files changed

+122
-42
lines changed

3 files changed

+122
-42
lines changed

lib/matplotlib/axes/_axes.py

+21-20
Original file line numberDiff line numberDiff line change
@@ -2336,7 +2336,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
23362336
if orientation == 'vertical':
23372337
if y is None:
23382338
y = 0
2339-
elif orientation == 'horizontal':
2339+
else: # horizontal
23402340
if x is None:
23412341
x = 0
23422342

@@ -2345,7 +2345,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
23452345
[("x", x), ("y", height)], kwargs, convert=False)
23462346
if log:
23472347
self.set_yscale('log', nonpositive='clip')
2348-
elif orientation == 'horizontal':
2348+
else: # horizontal
23492349
self._process_unit_info(
23502350
[("x", width), ("y", y)], kwargs, convert=False)
23512351
if log:
@@ -2374,7 +2374,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
23742374
if orientation == 'vertical':
23752375
tick_label_axis = self.xaxis
23762376
tick_label_position = x
2377-
elif orientation == 'horizontal':
2377+
else: # horizontal
23782378
tick_label_axis = self.yaxis
23792379
tick_label_position = y
23802380

@@ -2403,15 +2403,15 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
24032403
f'and width ({width.dtype}) '
24042404
f'are incompatible') from e
24052405
bottom = y
2406-
elif orientation == 'horizontal':
2406+
else: # horizontal
24072407
try:
24082408
bottom = y - height / 2
24092409
except TypeError as e:
24102410
raise TypeError(f'the dtypes of parameters y ({y.dtype}) '
24112411
f'and height ({height.dtype}) '
24122412
f'are incompatible') from e
24132413
left = x
2414-
elif align == 'edge':
2414+
else: # edge
24152415
left = x
24162416
bottom = y
24172417

@@ -2431,7 +2431,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
24312431
r.get_path()._interpolation_steps = 100
24322432
if orientation == 'vertical':
24332433
r.sticky_edges.y.append(b)
2434-
elif orientation == 'horizontal':
2434+
else: # horizontal
24352435
r.sticky_edges.x.append(l)
24362436
self.add_patch(r)
24372437
patches.append(r)
@@ -2442,7 +2442,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
24422442
ex = [l + 0.5 * w for l, w in zip(left, width)]
24432443
ey = [b + h for b, h in zip(bottom, height)]
24442444

2445-
elif orientation == 'horizontal':
2445+
else: # horizontal
24462446
# using list comps rather than arrays to preserve unit info
24472447
ex = [l + w for l, w in zip(left, width)]
24482448
ey = [b + 0.5 * h for b, h in zip(bottom, height)]
@@ -2459,7 +2459,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
24592459

24602460
if orientation == 'vertical':
24612461
datavalues = height
2462-
elif orientation == 'horizontal':
2462+
else: # horizontal
24632463
datavalues = width
24642464

24652465
bar_container = BarContainer(patches, errorbar, datavalues=datavalues,
@@ -2670,46 +2670,47 @@ def sign(x):
26702670
if orientation == "vertical":
26712671
extrema = max(y0, y1) if dat >= 0 else min(y0, y1)
26722672
length = abs(y0 - y1)
2673-
elif orientation == "horizontal":
2673+
else: # horizontal
26742674
extrema = max(x0, x1) if dat >= 0 else min(x0, x1)
26752675
length = abs(x0 - x1)
26762676

26772677
if err is None or np.size(err) == 0:
26782678
endpt = extrema
26792679
elif orientation == "vertical":
26802680
endpt = err[:, 1].max() if dat >= 0 else err[:, 1].min()
2681-
elif orientation == "horizontal":
2681+
else: # horizontal
26822682
endpt = err[:, 0].max() if dat >= 0 else err[:, 0].min()
26832683

26842684
if label_type == "center":
26852685
value = sign(dat) * length
2686-
elif label_type == "edge":
2686+
else: # edge
26872687
value = extrema
26882688

26892689
if label_type == "center":
26902690
xy = xc, yc
2691-
elif label_type == "edge" and orientation == "vertical":
2692-
xy = xc, endpt
2693-
elif label_type == "edge" and orientation == "horizontal":
2694-
xy = endpt, yc
2691+
else: # edge
2692+
if orientation == "vertical":
2693+
xy = xc, endpt
2694+
else: # horizontal
2695+
xy = endpt, yc
26952696

26962697
if orientation == "vertical":
26972698
y_direction = -1 if y_inverted else 1
26982699
xytext = 0, y_direction * sign(dat) * padding
2699-
else:
2700+
else: # horizontal
27002701
x_direction = -1 if x_inverted else 1
27012702
xytext = x_direction * sign(dat) * padding, 0
27022703

27032704
if label_type == "center":
27042705
ha, va = "center", "center"
2705-
elif label_type == "edge":
2706+
else: # edge
27062707
if orientation == "vertical":
27072708
ha = 'center'
27082709
if y_inverted:
27092710
va = 'top' if dat > 0 else 'bottom' # also handles NaN
27102711
else:
27112712
va = 'top' if dat < 0 else 'bottom' # also handles NaN
2712-
elif orientation == "horizontal":
2713+
else: # horizontal
27132714
if x_inverted:
27142715
ha = 'right' if dat > 0 else 'left' # also handles NaN
27152716
else:
@@ -2911,7 +2912,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
29112912

29122913
if orientation == 'vertical':
29132914
locs, heads = self._process_unit_info([("x", locs), ("y", heads)])
2914-
else:
2915+
else: # horizontal
29152916
heads, locs = self._process_unit_info([("x", heads), ("y", locs)])
29162917

29172918
# defaults for formats
@@ -7796,7 +7797,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
77967797
self.title.set_y(1.05)
77977798
if origin == "upper":
77987799
self.xaxis.tick_top()
7799-
else:
7800+
else: # lower
78007801
self.xaxis.tick_bottom()
78017802
self.xaxis.set_ticks_position('both')
78027803
self.xaxis.set_major_locator(

lib/matplotlib/axes/_base.py

+20-22
Original file line numberDiff line numberDiff line change
@@ -880,7 +880,7 @@ def get_xaxis_transform(self, which='grid'):
880880
# for cartesian projection, this is top spine
881881
return self.spines.top.get_spine_transform()
882882
else:
883-
raise ValueError('unknown value for which')
883+
raise ValueError(f'unknown value for which: {which!r}')
884884

885885
def get_xaxis_text1_transform(self, pad_points):
886886
"""
@@ -956,7 +956,7 @@ def get_yaxis_transform(self, which='grid'):
956956
# for cartesian projection, this is top spine
957957
return self.spines.right.get_spine_transform()
958958
else:
959-
raise ValueError('unknown value for which')
959+
raise ValueError(f'unknown value for which: {which!r}')
960960

961961
def get_yaxis_text1_transform(self, pad_points):
962962
"""
@@ -3174,15 +3174,13 @@ def set_axisbelow(self, b):
31743174
--------
31753175
get_axisbelow
31763176
"""
3177+
# Check that b is True, False or 'line'
31773178
self._axisbelow = axisbelow = validate_axisbelow(b)
3178-
if axisbelow is True:
3179-
zorder = 0.5
3180-
elif axisbelow is False:
3181-
zorder = 2.5
3182-
elif axisbelow == "line":
3183-
zorder = 1.5
3184-
else:
3185-
raise ValueError("Unexpected axisbelow value")
3179+
zorder = {
3180+
True: 0.5,
3181+
'line': 1.5,
3182+
False: 2.5,
3183+
}[axisbelow]
31863184
for axis in self._axis_map.values():
31873185
axis.set_zorder(zorder)
31883186
self.stale = True
@@ -3495,12 +3493,12 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,
34953493
else mpl.rcParams['xaxis.labellocation'])
34963494
_api.check_in_list(('left', 'center', 'right'), loc=loc)
34973495

3498-
if loc == 'left':
3499-
kwargs.update(x=0, horizontalalignment='left')
3500-
elif loc == 'center':
3501-
kwargs.update(x=0.5, horizontalalignment='center')
3502-
elif loc == 'right':
3503-
kwargs.update(x=1, horizontalalignment='right')
3496+
x = {
3497+
'left': 0,
3498+
'center': 0.5,
3499+
'right': 1,
3500+
}[loc]
3501+
kwargs.update(x=x, horizontalalignment=loc)
35043502

35053503
return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)
35063504

@@ -3784,12 +3782,12 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,
37843782
else mpl.rcParams['yaxis.labellocation'])
37853783
_api.check_in_list(('bottom', 'center', 'top'), loc=loc)
37863784

3787-
if loc == 'bottom':
3788-
kwargs.update(y=0, horizontalalignment='left')
3789-
elif loc == 'center':
3790-
kwargs.update(y=0.5, horizontalalignment='center')
3791-
elif loc == 'top':
3792-
kwargs.update(y=1, horizontalalignment='right')
3785+
y, ha = {
3786+
'bottom': (0, 'left'),
3787+
'center': (0.5, 'center'),
3788+
'top': (1, 'right')
3789+
}[loc]
3790+
kwargs.update(y=y, horizontalalignment=ha)
37933791

37943792
return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)
37953793

lib/matplotlib/tests/test_axes.py

+81
Original file line numberDiff line numberDiff line change
@@ -5123,6 +5123,32 @@ def test_axis_errors(err, args, kwargs, match):
51235123
plt.axis(*args, **kwargs)
51245124

51255125

5126+
def test_axis_method_errors():
5127+
ax = plt.gca()
5128+
with pytest.raises(ValueError, match="unknown value for which: 'foo'"):
5129+
ax.get_xaxis_transform('foo')
5130+
with pytest.raises(ValueError, match="unknown value for which: 'foo'"):
5131+
ax.get_yaxis_transform('foo')
5132+
with pytest.raises(TypeError, match="Cannot supply both positional and"):
5133+
ax.set_prop_cycle('foo', label='bar')
5134+
with pytest.raises(ValueError, match="argument must be among"):
5135+
ax.set_anchor('foo')
5136+
with pytest.raises(ValueError, match="scilimits must be a sequence"):
5137+
ax.ticklabel_format(scilimits=1)
5138+
with pytest.raises(TypeError, match="Specifying 'loc' is disallowed"):
5139+
ax.set_xlabel('foo', loc='left', x=1)
5140+
with pytest.raises(TypeError, match="Specifying 'loc' is disallowed"):
5141+
ax.set_ylabel('foo', loc='top', y=1)
5142+
with pytest.raises(TypeError, match="Cannot pass both 'left'"):
5143+
ax.set_xlim(left=0, xmin=1)
5144+
with pytest.raises(TypeError, match="Cannot pass both 'right'"):
5145+
ax.set_xlim(right=0, xmax=1)
5146+
with pytest.raises(TypeError, match="Cannot pass both 'bottom'"):
5147+
ax.set_ylim(bottom=0, ymin=1)
5148+
with pytest.raises(TypeError, match="Cannot pass both 'top'"):
5149+
ax.set_ylim(top=0, ymax=1)
5150+
5151+
51265152
@pytest.mark.parametrize('twin', ('x', 'y'))
51275153
def test_twin_with_aspect(twin):
51285154
fig, ax = plt.subplots()
@@ -7169,6 +7195,7 @@ def test_box_aspect():
71697195
axtwin.plot([12, 344])
71707196

71717197
ax1.set_box_aspect(1)
7198+
assert ax1.get_box_aspect() == 1.0
71727199

71737200
fig2, ax2 = plt.subplots()
71747201
ax2.margins(0)
@@ -7714,6 +7741,60 @@ def test_plot_format_errors(fmt, match, data):
77147741
ax.plot("string", fmt, data=data)
77157742

77167743

7744+
def test_plot_format():
7745+
fig, ax = plt.subplots()
7746+
line = ax.plot([1, 2, 3], '1.0')
7747+
assert line[0].get_color() == (1.0, 1.0, 1.0, 1.0)
7748+
assert line[0].get_marker() == 'None'
7749+
fig, ax = plt.subplots()
7750+
line = ax.plot([1, 2, 3], '1')
7751+
assert line[0].get_marker() == '1'
7752+
fig, ax = plt.subplots()
7753+
line = ax.plot([1, 2], [1, 2], '1.0', "1")
7754+
fig.canvas.draw()
7755+
assert line[0].get_color() == (1.0, 1.0, 1.0, 1.0)
7756+
assert ax.get_yticklabels()[0].get_text() == '1'
7757+
fig, ax = plt.subplots()
7758+
line = ax.plot([1, 2], [1, 2], '1', "1.0")
7759+
fig.canvas.draw()
7760+
assert line[0].get_marker() == '1'
7761+
assert ax.get_yticklabels()[0].get_text() == '1.0'
7762+
fig, ax = plt.subplots()
7763+
line = ax.plot([1, 2, 3], 'k3')
7764+
assert line[0].get_marker() == '3'
7765+
assert line[0].get_color() == 'k'
7766+
7767+
7768+
def test_automatic_legend():
7769+
fig, ax = plt.subplots()
7770+
ax.plot("a", "b", data={"d": 2})
7771+
leg = ax.legend()
7772+
fig.canvas.draw()
7773+
assert leg.get_texts()[0].get_text() == 'a'
7774+
assert ax.get_yticklabels()[0].get_text() == 'a'
7775+
7776+
fig, ax = plt.subplots()
7777+
ax.plot("a", "b", "c", data={"d": 2})
7778+
leg = ax.legend()
7779+
fig.canvas.draw()
7780+
assert leg.get_texts()[0].get_text() == 'b'
7781+
assert ax.get_xticklabels()[0].get_text() == 'a'
7782+
assert ax.get_yticklabels()[0].get_text() == 'b'
7783+
7784+
7785+
def test_plot_errors():
7786+
with pytest.raises(TypeError, match="plot got an unexpected keyword"):
7787+
plt.plot([1, 2, 3], x=1)
7788+
with pytest.raises(ValueError, match=r"plot\(\) with multiple groups"):
7789+
plt.plot([1, 2, 3], [1, 2, 3], [2, 3, 4], [2, 3, 4], label=['1', '2'])
7790+
with pytest.raises(ValueError, match="x and y must have same first"):
7791+
plt.plot([1, 2, 3], [1])
7792+
with pytest.raises(ValueError, match="x and y can be no greater than"):
7793+
plt.plot(np.ones((2, 2, 2)))
7794+
with pytest.raises(ValueError, match="Using arbitrary long args with"):
7795+
plt.plot("a", "b", "c", "d", data={"a": 2})
7796+
7797+
77177798
def test_clim():
77187799
ax = plt.figure().add_subplot()
77197800
for plot_method in [

0 commit comments

Comments
 (0)