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

Skip to content

Commit 34f99a9

Browse files
authored
Merge pull request #18553 from timhoffm/test-subplots
Use fig, ax = plt.subplots() in tests
2 parents 94d73b7 + ff1a934 commit 34f99a9

9 files changed

+49
-84
lines changed

lib/matplotlib/tests/test_axes.py

Lines changed: 20 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2425,8 +2425,7 @@ def test_pyplot_axes():
24252425

24262426
@image_comparison(['log_scales'])
24272427
def test_log_scales():
2428-
fig = plt.figure()
2429-
ax = fig.add_subplot(1, 1, 1)
2428+
fig, ax = plt.subplots()
24302429
ax.plot(np.log(np.linspace(0.1, 100)))
24312430
ax.set_yscale('log', base=5.5)
24322431
ax.invert_yaxis()
@@ -2441,8 +2440,7 @@ def test_log_scales_no_data():
24412440

24422441

24432442
def test_log_scales_invalid():
2444-
fig = plt.figure()
2445-
ax = fig.add_subplot(1, 1, 1)
2443+
fig, ax = plt.subplots()
24462444
ax.set_xscale('log')
24472445
with pytest.warns(UserWarning, match='Attempted to set non-positive'):
24482446
ax.set_xlim(-1, 10)
@@ -2465,8 +2463,7 @@ def test_stackplot():
24652463

24662464
# Reuse testcase from above for a labeled data test
24672465
data = {"x": x, "y1": y1, "y2": y2, "y3": y3}
2468-
fig = plt.figure()
2469-
ax = fig.add_subplot(1, 1, 1)
2466+
fig, ax = plt.subplots()
24702467
ax.stackplot("x", "y1", "y2", "y3", data=data)
24712468
ax.set_xlim((0, 10))
24722469
ax.set_ylim((0, 70))
@@ -3317,27 +3314,26 @@ def test_errorbar_limits():
33173314
yerr = 0.2
33183315
ls = 'dotted'
33193316

3320-
fig = plt.figure()
3321-
ax = fig.add_subplot(1, 1, 1)
3317+
fig, ax = plt.subplots()
33223318

33233319
# standard error bars
3324-
plt.errorbar(x, y, xerr=xerr, yerr=yerr, ls=ls, color='blue')
3320+
ax.errorbar(x, y, xerr=xerr, yerr=yerr, ls=ls, color='blue')
33253321

33263322
# including upper limits
33273323
uplims = np.zeros_like(x)
33283324
uplims[[1, 5, 9]] = True
3329-
plt.errorbar(x, y+0.5, xerr=xerr, yerr=yerr, uplims=uplims, ls=ls,
3330-
color='green')
3325+
ax.errorbar(x, y+0.5, xerr=xerr, yerr=yerr, uplims=uplims, ls=ls,
3326+
color='green')
33313327

33323328
# including lower limits
33333329
lolims = np.zeros_like(x)
33343330
lolims[[2, 4, 8]] = True
3335-
plt.errorbar(x, y+1.0, xerr=xerr, yerr=yerr, lolims=lolims, ls=ls,
3336-
color='red')
3331+
ax.errorbar(x, y+1.0, xerr=xerr, yerr=yerr, lolims=lolims, ls=ls,
3332+
color='red')
33373333

33383334
# including upper and lower limits
3339-
plt.errorbar(x, y+1.5, marker='o', ms=8, xerr=xerr, yerr=yerr,
3340-
lolims=lolims, uplims=uplims, ls=ls, color='magenta')
3335+
ax.errorbar(x, y+1.5, marker='o', ms=8, xerr=xerr, yerr=yerr,
3336+
lolims=lolims, uplims=uplims, ls=ls, color='magenta')
33413337

33423338
# including xlower and xupper limits
33433339
xerr = 0.2
@@ -3349,10 +3345,10 @@ def test_errorbar_limits():
33493345
uplims = np.zeros_like(x)
33503346
lolims[[6]] = True
33513347
uplims[[3]] = True
3352-
plt.errorbar(x, y+2.1, marker='o', ms=8, xerr=xerr, yerr=yerr,
3353-
xlolims=xlolims, xuplims=xuplims, uplims=uplims,
3354-
lolims=lolims, ls='none', mec='blue', capsize=0,
3355-
color='cyan')
3348+
ax.errorbar(x, y+2.1, marker='o', ms=8, xerr=xerr, yerr=yerr,
3349+
xlolims=xlolims, xuplims=xuplims, uplims=uplims,
3350+
lolims=lolims, ls='none', mec='blue', capsize=0,
3351+
color='cyan')
33563352
ax.set_xlim((0, 5.5))
33573353
ax.set_title('Errorbar upper and lower limits')
33583354

@@ -3484,13 +3480,11 @@ def test_stem(use_line_collection):
34843480
ax.stem(x, np.cos(x),
34853481
linefmt='C2-.', markerfmt='k+', basefmt='C1-.', label=' ',
34863482
use_line_collection=use_line_collection)
3487-
34883483
ax.legend()
34893484

34903485

34913486
def test_stem_args():
3492-
fig = plt.figure()
3493-
ax = fig.add_subplot(1, 1, 1)
3487+
fig, ax = plt.subplots()
34943488

34953489
x = list(range(10))
34963490
y = list(range(10))
@@ -4229,8 +4223,7 @@ def test_step_linestyle():
42294223
@image_comparison(['mixed_collection'], remove_text=True)
42304224
def test_mixed_collection():
42314225
# First illustrate basic pyplot interface, using defaults where possible.
4232-
fig = plt.figure()
4233-
ax = fig.add_subplot(1, 1, 1)
4226+
fig, ax = plt.subplots()
42344227

42354228
c = mpatches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green')
42364229

@@ -4571,8 +4564,7 @@ def test_rcparam_grid_minor():
45714564

45724565
for locator, result in values:
45734566
matplotlib.rcParams['axes.grid.which'] = locator
4574-
fig = plt.figure()
4575-
ax = fig.add_subplot(1, 1, 1)
4567+
fig, ax = plt.subplots()
45764568
assert (ax.xaxis._gridOnMajor, ax.xaxis._gridOnMinor) == result
45774569

45784570
matplotlib.rcParams['axes.grid'] = orig_grid
@@ -5786,16 +5778,14 @@ def test_title_no_move_off_page():
57865778

57875779
def test_offset_label_color():
57885780
# Tests issue 6440
5789-
fig = plt.figure()
5790-
ax = fig.add_subplot(1, 1, 1)
5781+
fig, ax = plt.subplots()
57915782
ax.plot([1.01e9, 1.02e9, 1.03e9])
57925783
ax.yaxis.set_tick_params(labelcolor='red')
57935784
assert ax.yaxis.get_offset_text().get_color() == 'red'
57945785

57955786

57965787
def test_offset_text_visible():
5797-
fig = plt.figure()
5798-
ax = fig.add_subplot(1, 1, 1)
5788+
fig, ax = plt.subplots()
57995789
ax.plot([1.01e9, 1.02e9, 1.03e9])
58005790
ax.yaxis.set_tick_params(label1On=False, label2On=True)
58015791
assert ax.yaxis.get_offset_text().get_visible()

lib/matplotlib/tests/test_backend_pdf.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ def test_use14corefonts():
3131
and containing some French characters and the euro symbol:
3232
"Merci pépé pour les 10 €"'''
3333

34-
fig = plt.figure()
35-
ax = fig.add_subplot(1, 1, 1)
34+
fig, ax = plt.subplots()
3635
ax.set_title('Test PDF backend with option use14corefonts=True')
3736
ax.text(0.5, 0.5, text, horizontalalignment='center',
3837
verticalalignment='bottom',
@@ -111,8 +110,7 @@ def test_composite_image():
111110
# (on a single set of axes) into a single composite image.
112111
X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))
113112
Z = np.sin(Y ** 2)
114-
fig = plt.figure()
115-
ax = fig.add_subplot(1, 1, 1)
113+
fig, ax = plt.subplots()
116114
ax.set_xlim(0, 3)
117115
ax.imshow(Z, extent=[0, 1, 0, 1])
118116
ax.imshow(Z[::-1], extent=[2, 3, 0, 1])

lib/matplotlib/tests/test_backend_svg.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,7 @@ def test_visibility():
4040

4141
@image_comparison(['fill_black_with_alpha.svg'], remove_text=True)
4242
def test_fill_black_with_alpha():
43-
fig = plt.figure()
44-
ax = fig.add_subplot(1, 1, 1)
43+
fig, ax = plt.subplots()
4544
ax.scatter(x=[0, 0.1, 1], y=[0, 0, 0], c='k', alpha=0.1, s=10000)
4645

4746

@@ -50,8 +49,7 @@ def test_noscale():
5049
X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))
5150
Z = np.sin(Y ** 2)
5251

53-
fig = plt.figure()
54-
ax = fig.add_subplot(1, 1, 1)
52+
fig, ax = plt.subplots()
5553
ax.imshow(Z, cmap='gray', interpolation='none')
5654

5755

@@ -71,8 +69,7 @@ def test_text_urls():
7169

7270
@image_comparison(['bold_font_output.svg'])
7371
def test_bold_font_output():
74-
fig = plt.figure()
75-
ax = fig.add_subplot(1, 1, 1)
72+
fig, ax = plt.subplots()
7673
ax.plot(np.arange(10), np.arange(10))
7774
ax.set_xlabel('nonbold-xlabel')
7875
ax.set_ylabel('bold-ylabel', fontweight='bold')
@@ -82,8 +79,7 @@ def test_bold_font_output():
8279
@image_comparison(['bold_font_output_with_none_fonttype.svg'])
8380
def test_bold_font_output_with_none_fonttype():
8481
plt.rcParams['svg.fonttype'] = 'none'
85-
fig = plt.figure()
86-
ax = fig.add_subplot(1, 1, 1)
82+
fig, ax = plt.subplots()
8783
ax.plot(np.arange(10), np.arange(10))
8884
ax.set_xlabel('nonbold-xlabel')
8985
ax.set_ylabel('bold-ylabel', fontweight='bold')

lib/matplotlib/tests/test_collections.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,7 @@ def generate_EventCollection_plot():
3636
antialiased=antialiased
3737
)
3838

39-
fig = plt.figure()
40-
ax = fig.add_subplot(1, 1, 1)
39+
fig, ax = plt.subplots()
4140
ax.add_collection(coll)
4241
ax.set_title('EventCollection: default')
4342
props = {'positions': positions,
@@ -519,8 +518,7 @@ def test_joinstyle():
519518

520519
@image_comparison(['cap_and_joinstyle.png'])
521520
def test_cap_and_joinstyle_image():
522-
fig = plt.figure()
523-
ax = fig.add_subplot(1, 1, 1)
521+
fig, ax = plt.subplots()
524522
ax.set_xlim([-0.5, 1.5])
525523
ax.set_ylim([-0.5, 2.5])
526524

lib/matplotlib/tests/test_dates.py

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -74,18 +74,16 @@ def test_date_empty():
7474
# make sure we do the right thing when told to plot dates even
7575
# if no date data has been presented, cf
7676
# http://sourceforge.net/tracker/?func=detail&aid=2850075&group_id=80706&atid=560720
77-
fig = plt.figure()
78-
ax = fig.add_subplot(1, 1, 1)
77+
fig, ax = plt.subplots()
7978
ax.xaxis_date()
8079

8180

8281
@image_comparison(['date_axhspan.png'])
8382
def test_date_axhspan():
84-
# test ax hspan with date inputs
83+
# test axhspan with date inputs
8584
t0 = datetime.datetime(2009, 1, 20)
8685
tf = datetime.datetime(2009, 1, 21)
87-
fig = plt.figure()
88-
ax = fig.add_subplot(1, 1, 1)
86+
fig, ax = plt.subplots()
8987
ax.axhspan(t0, tf, facecolor="blue", alpha=0.25)
9088
ax.set_ylim(t0 - datetime.timedelta(days=5),
9189
tf + datetime.timedelta(days=5))
@@ -94,11 +92,10 @@ def test_date_axhspan():
9492

9593
@image_comparison(['date_axvspan.png'])
9694
def test_date_axvspan():
97-
# test ax hspan with date inputs
95+
# test axvspan with date inputs
9896
t0 = datetime.datetime(2000, 1, 20)
9997
tf = datetime.datetime(2010, 1, 21)
100-
fig = plt.figure()
101-
ax = fig.add_subplot(1, 1, 1)
98+
fig, ax = plt.subplots()
10299
ax.axvspan(t0, tf, facecolor="blue", alpha=0.25)
103100
ax.set_xlim(t0 - datetime.timedelta(days=720),
104101
tf + datetime.timedelta(days=720))
@@ -107,11 +104,10 @@ def test_date_axvspan():
107104

108105
@image_comparison(['date_axhline.png'])
109106
def test_date_axhline():
110-
# test ax hline with date inputs
107+
# test axhline with date inputs
111108
t0 = datetime.datetime(2009, 1, 20)
112109
tf = datetime.datetime(2009, 1, 31)
113-
fig = plt.figure()
114-
ax = fig.add_subplot(1, 1, 1)
110+
fig, ax = plt.subplots()
115111
ax.axhline(t0, color="blue", lw=3)
116112
ax.set_ylim(t0 - datetime.timedelta(days=5),
117113
tf + datetime.timedelta(days=5))
@@ -120,11 +116,10 @@ def test_date_axhline():
120116

121117
@image_comparison(['date_axvline.png'])
122118
def test_date_axvline():
123-
# test ax hline with date inputs
119+
# test axvline with date inputs
124120
t0 = datetime.datetime(2000, 1, 20)
125121
tf = datetime.datetime(2000, 1, 21)
126-
fig = plt.figure()
127-
ax = fig.add_subplot(1, 1, 1)
122+
fig, ax = plt.subplots()
128123
ax.axvline(t0, color="red", lw=3)
129124
ax.set_xlim(t0 - datetime.timedelta(days=5),
130125
tf + datetime.timedelta(days=5))
@@ -140,8 +135,7 @@ def test_too_many_date_ticks(caplog):
140135
caplog.set_level("WARNING")
141136
t0 = datetime.datetime(2000, 1, 20)
142137
tf = datetime.datetime(2000, 1, 20)
143-
fig = plt.figure()
144-
ax = fig.add_subplot(1, 1, 1)
138+
fig, ax = plt.subplots()
145139
with pytest.warns(UserWarning) as rec:
146140
ax.set_xlim((t0, tf), auto=True)
147141
assert len(rec) == 1
@@ -733,8 +727,7 @@ def test_date_inverted_limit():
733727
# test ax hline with date inputs
734728
t0 = datetime.datetime(2009, 1, 20)
735729
tf = datetime.datetime(2009, 1, 31)
736-
fig = plt.figure()
737-
ax = fig.add_subplot(1, 1, 1)
730+
fig, ax = plt.subplots()
738731
ax.axhline(t0, color="blue", lw=3)
739732
ax.set_ylim(t0 - datetime.timedelta(days=5),
740733
tf + datetime.timedelta(days=5))

lib/matplotlib/tests/test_legend.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,7 @@ def test_hatching():
215215

216216

217217
def test_legend_remove():
218-
fig = plt.figure()
219-
ax = fig.add_subplot(1, 1, 1)
218+
fig, ax = plt.subplots()
220219
lines = ax.plot(range(10))
221220
leg = fig.legend(lines, "test")
222221
leg.remove()

lib/matplotlib/tests/test_lines.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,7 @@ def test_invisible_Line_rendering():
7373

7474

7575
def test_set_line_coll_dash():
76-
fig = plt.figure()
77-
ax = fig.add_subplot(1, 1, 1)
76+
fig, ax = plt.subplots()
7877
np.random.seed(0)
7978
# Testing setting linestyles for line collections.
8079
# This should not produce an error.
@@ -83,15 +82,13 @@ def test_set_line_coll_dash():
8382

8483
@image_comparison(['line_dashes'], remove_text=True)
8584
def test_line_dashes():
86-
fig = plt.figure()
87-
ax = fig.add_subplot(1, 1, 1)
85+
fig, ax = plt.subplots()
8886

8987
ax.plot(range(10), linestyle=(0, (3, 3)), lw=5)
9088

9189

9290
def test_line_colors():
93-
fig = plt.figure()
94-
ax = fig.add_subplot(1, 1, 1)
91+
fig, ax = plt.subplots()
9592
ax.plot(range(10), color='none')
9693
ax.plot(range(10), color='r')
9794
ax.plot(range(10), color='.3')
@@ -107,8 +104,7 @@ def test_valid_colors():
107104

108105

109106
def test_linestyle_variants():
110-
fig = plt.figure()
111-
ax = fig.add_subplot(1, 1, 1)
107+
fig, ax = plt.subplots()
112108
for ls in ["-", "solid", "--", "dashed",
113109
"-.", "dashdot", ":", "dotted"]:
114110
ax.plot(range(10), linestyle=ls)
@@ -155,8 +151,7 @@ def test_set_drawstyle():
155151

156152
@image_comparison(['line_collection_dashes'], remove_text=True, style='mpl20')
157153
def test_set_line_coll_dash_image():
158-
fig = plt.figure()
159-
ax = fig.add_subplot(1, 1, 1)
154+
fig, ax = plt.subplots()
160155
np.random.seed(0)
161156
ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])
162157

lib/matplotlib/tests/test_patches.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,8 +226,7 @@ def test_patch_linestyle_accents():
226226
linestyles = ["-", "--", "-.", ":",
227227
"solid", "dashed", "dashdot", "dotted"]
228228

229-
fig = plt.figure()
230-
ax = fig.add_subplot(1, 1, 1)
229+
fig, ax = plt.subplots()
231230
for i, ls in enumerate(linestyles):
232231
star = mpath.Path(verts + i, codes)
233232
patch = mpatches.PathPatch(star,

lib/matplotlib/tests/test_spines.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@ def test_spines_axes_positions():
2323

2424
@image_comparison(['spines_data_positions'])
2525
def test_spines_data_positions():
26-
fig = plt.figure()
27-
ax = fig.add_subplot(1, 1, 1)
26+
fig, ax = plt.subplots()
2827
ax.spines['left'].set_position(('data', -1.5))
2928
ax.spines['top'].set_position(('data', 0.5))
3029
ax.spines['right'].set_position(('data', -0.5))
@@ -58,15 +57,13 @@ def test_spine_nonlinear_data_positions(fig_test, fig_ref):
5857
def test_spines_capstyle():
5958
# issue 2542
6059
plt.rc('axes', linewidth=20)
61-
fig = plt.figure()
62-
ax = fig.add_subplot(1, 1, 1)
60+
fig, ax = plt.subplots()
6361
ax.set_xticks([])
6462
ax.set_yticks([])
6563

6664

6765
def test_label_without_ticks():
68-
fig = plt.figure()
69-
ax = fig.add_subplot(1, 1, 1)
66+
fig, ax = plt.subplots()
7067
plt.subplots_adjust(left=0.3, bottom=0.3)
7168
ax.plot(np.arange(10))
7269
ax.yaxis.set_ticks_position('left')

0 commit comments

Comments
 (0)