From 365d54c7eadcad1d9ff065299f75da7ca5f80d28 Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Thu, 5 Jul 2018 23:45:31 +0200 Subject: [PATCH] Use plt.subplots() --- .../lines_bars_and_markers/simple_plot.py | 2 - examples/misc/load_converter.py | 3 +- examples/pyplots/annotate_transform.py | 3 +- examples/pyplots/auto_subplots_adjust.py | 3 +- .../tick_labels_from_values.py | 3 +- lib/matplotlib/lines.py | 3 +- lib/matplotlib/mlab.py | 3 +- lib/matplotlib/tests/test_artist.py | 3 +- lib/matplotlib/tests/test_axes.py | 117 +++++------------- lib/matplotlib/tests/test_backend_svg.py | 3 +- .../tests/test_backends_interactive.py | 3 +- lib/matplotlib/tests/test_colorbar.py | 3 +- .../tests/test_constrainedlayout.py | 1 - lib/matplotlib/tests/test_contour.py | 24 ++-- lib/matplotlib/tests/test_cycles.py | 18 +-- lib/matplotlib/tests/test_image.py | 40 ++---- lib/matplotlib/tests/test_tightlayout.py | 6 +- lib/matplotlib/tests/test_ttconv.py | 3 +- tutorials/advanced/path_tutorial.py | 10 +- tutorials/advanced/transforms_tutorial.py | 13 +- tutorials/intermediate/artists.py | 7 +- tutorials/introductory/usage.py | 3 +- tutorials/text/pgf.py | 6 +- 23 files changed, 85 insertions(+), 195 deletions(-) diff --git a/examples/lines_bars_and_markers/simple_plot.py b/examples/lines_bars_and_markers/simple_plot.py index 20f2875d6a9d..f51e16015b2e 100644 --- a/examples/lines_bars_and_markers/simple_plot.py +++ b/examples/lines_bars_and_markers/simple_plot.py @@ -14,8 +14,6 @@ t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) -# Note that using plt.subplots below is equivalent to using -# fig = plt.figure() and then ax = fig.add_subplot(111) fig, ax = plt.subplots() ax.plot(t, s) diff --git a/examples/misc/load_converter.py b/examples/misc/load_converter.py index 86a92ab72359..33a482cb27b7 100644 --- a/examples/misc/load_converter.py +++ b/examples/misc/load_converter.py @@ -17,8 +17,7 @@ converters={0: bytespdate2num('%d-%b-%y')}, skiprows=1, usecols=(0, 2), unpack=True) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot_date(dates, closes, '-') fig.autofmt_xdate() plt.show() diff --git a/examples/pyplots/annotate_transform.py b/examples/pyplots/annotate_transform.py index 67e7d6536289..249dee2efdc1 100644 --- a/examples/pyplots/annotate_transform.py +++ b/examples/pyplots/annotate_transform.py @@ -13,8 +13,7 @@ x = np.arange(0, 10, 0.005) y = np.exp(-x/2.) * np.sin(2*np.pi*x) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10) ax.set_ylim(-1, 1) diff --git a/examples/pyplots/auto_subplots_adjust.py b/examples/pyplots/auto_subplots_adjust.py index 7b13cda9e90b..574fb15a8bb3 100644 --- a/examples/pyplots/auto_subplots_adjust.py +++ b/examples/pyplots/auto_subplots_adjust.py @@ -13,8 +13,7 @@ """ import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(range(10)) ax.set_yticks((2,5,7)) labels = ax.set_yticklabels(('really, really, really', 'long', 'labels')) diff --git a/examples/ticks_and_spines/tick_labels_from_values.py b/examples/ticks_and_spines/tick_labels_from_values.py index fca78eb46ff1..c504796b7a1b 100644 --- a/examples/ticks_and_spines/tick_labels_from_values.py +++ b/examples/ticks_and_spines/tick_labels_from_values.py @@ -17,8 +17,7 @@ import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter, MaxNLocator -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() xs = range(26) ys = range(26) labels = list('abcdefghijklmnopqrstuvwxyz') diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index 2de67b64c814..3f30770767d3 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -1372,8 +1372,7 @@ def process_selected(self, ind, xs, ys): self.markers.set_data(xs, ys) self.canvas.draw() - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() x, y = np.random.rand(2, 30) line, = ax.plot(x, y, 'bs-', picker=5) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 1cc3b434d2ee..477397915d26 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -3876,8 +3876,7 @@ def cross_from_below(x, threshold): t = np.arange(0.0, 2.0, 0.1) s = np.sin(2*np.pi*t) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.plot(t, s, '-o') ax.axhline(0.5) ax.axhline(-0.5) diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index 4b4c76ce293d..283db9abe97e 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -129,8 +129,7 @@ def test_cull_markers(): x = np.random.random(20000) y = np.random.random(20000) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.plot(x, y, 'k.') ax.set_xlim(2, 3) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index c8993dfaeb2f..093c89d7c0b9 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -821,9 +821,7 @@ def test_axhspan_epoch(): remove_text=True, extensions=['png']) def test_hexbin_extent(): # this test exposes sf bug 2856228 - fig = plt.figure() - - ax = fig.add_subplot(111) + fig, ax = plt.subplots() data = (np.arange(2000) / 2000).reshape((2, 1000)) x, y = data @@ -832,8 +830,7 @@ def test_hexbin_extent(): # Reuse testcase from above for a labeled data test data = {"x": x, "y": y} - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.hexbin("x", "y", extent=[.1, .3, .6, .7], data=data) @@ -852,9 +849,7 @@ def __init__(self, x, y): self.x = x self.y = y - fig = plt.figure() - - ax = fig.add_subplot(111) + fig, ax = plt.subplots() data = (np.arange(200) / 200).reshape((2, 100)) x, y = data hb = ax.hexbin(x, y, extent=[.1, .3, .6, .7], picker=-1) @@ -867,14 +862,13 @@ def __init__(self, x, y): extensions=['png']) def test_hexbin_log(): # Issue #1636 - fig = plt.figure() - np.random.seed(0) n = 100000 x = np.random.standard_normal(n) y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n) y = np.power(2, y * 0.5) - ax = fig.add_subplot(111) + + fig, ax = plt.subplots() ax.hexbin(x, y, yscale='log') @@ -882,8 +876,7 @@ def test_inverted_limits(): # Test gh:1553 # Calling invert_xaxis prior to plotting should not disable autoscaling # while still maintaining the inverted direction - fig = plt.figure() - ax = fig.gca() + fig, ax = plt.subplots() ax.invert_xaxis() ax.plot([-5, -3, 2, 4], [1, 2, -3, 5]) @@ -891,8 +884,7 @@ def test_inverted_limits(): assert ax.get_ylim() == (-3, 5) plt.close() - fig = plt.figure() - ax = fig.gca() + fig, ax = plt.subplots() ax.invert_yaxis() ax.plot([-5, -3, 2, 4], [1, 2, -3, 5]) @@ -908,8 +900,7 @@ def test_nonfinite_limits(): with np.errstate(divide='ignore'): y = np.log(x) x[len(x)//2] = np.nan - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.plot(x, y) @@ -924,9 +915,7 @@ def test_imshow(): r = np.sqrt(x**2+y**2-x*y) # Create a contour plot at N/4 and extract both the clip path and transform - fig = plt.figure() - ax = fig.add_subplot(111) - + fig, ax = plt.subplots() ax.imshow(r) # Reuse testcase from above for a labeled data test @@ -948,8 +937,7 @@ def test_imshow_clip(): r = np.sqrt(x**2+y**2-x*y) # Create a contour plot at N/4 and extract both the clip path and transform - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() c = ax.contour(r, [N/4]) x = c.collections[0] @@ -970,8 +958,7 @@ def test_polycollection_joinstyle(): from matplotlib import collections as mcoll - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() verts = np.array([[1, 1], [1, 2], [2, 2], [2, 1]]) c = mcoll.PolyCollection([verts], linewidths=40) ax.add_collection(c) @@ -991,8 +978,7 @@ def test_polycollection_joinstyle(): ] ) def test_fill_between_input(x, y1, y2): - fig = plt.figure() - ax = fig.add_subplot(211) + fig, ax = plt.subplots() with pytest.raises(ValueError): ax.fill_between(x, y1, y2) @@ -1009,8 +995,7 @@ def test_fill_between_input(x, y1, y2): ] ) def test_fill_betweenx_input(y, x1, x2): - fig = plt.figure() - ax = fig.add_subplot(211) + fig, ax = plt.subplots() with pytest.raises(ValueError): ax.fill_betweenx(y, x1, x2) @@ -1022,23 +1007,21 @@ def test_fill_between_interpolate(): y1 = np.sin(2*np.pi*x) y2 = 1.2*np.sin(4*np.pi*x) - fig = plt.figure() - ax = fig.add_subplot(211) - ax.plot(x, y1, x, y2, color='black') - ax.fill_between(x, y1, y2, where=y2 >= y1, facecolor='white', hatch='/', - interpolate=True) - ax.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', - interpolate=True) + fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) + ax1.plot(x, y1, x, y2, color='black') + ax1.fill_between(x, y1, y2, where=y2 >= y1, facecolor='white', hatch='/', + interpolate=True) + ax1.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', + interpolate=True) # Test support for masked arrays. y2 = np.ma.masked_greater(y2, 1.0) # Test that plotting works for masked arrays with the first element masked y2[0] = np.ma.masked - ax1 = fig.add_subplot(212, sharex=ax) - ax1.plot(x, y1, x, y2, color='black') - ax1.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green', + ax2.plot(x, y1, x, y2, color='black') + ax2.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green', interpolate=True) - ax1.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', + ax2.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True) @@ -1049,8 +1032,7 @@ def test_fill_between_interpolate_decreasing(): t = np.array([9.4, 7, 2.2]) prof = np.array([7.9, 6.6, 3.8]) - fig = plt.figure(figsize=(9, 9)) - ax = fig.add_subplot(1, 1, 1) + fig, ax = plt.subplots(figsize=(9, 9)) ax.plot(t, p, 'tab:red') ax.plot(prof, p, 'k') @@ -1069,8 +1051,7 @@ def test_symlog(): x = np.array([0, 1, 2, 4, 6, 9, 12, 24]) y = np.array([1000000, 500000, 100000, 100, 5, 0, 0, 0]) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.plot(x, y) ax.set_yscale('symlog') ax.set_xscale('linear') @@ -1083,37 +1064,12 @@ def test_symlog2(): # Numbers from -50 to 50, with 0.1 as step x = np.arange(-50, 50, 0.001) - fig = plt.figure() - ax = fig.add_subplot(511) - # Plots a simple linear function 'f(x) = x' - ax.plot(x, x) - ax.set_xscale('symlog', linthreshx=20.0) - ax.grid(True) - - ax = fig.add_subplot(512) - # Plots a simple linear function 'f(x) = x' - ax.plot(x, x) - ax.set_xscale('symlog', linthreshx=2.0) - ax.grid(True) - - ax = fig.add_subplot(513) - # Plots a simple linear function 'f(x) = x' - ax.plot(x, x) - ax.set_xscale('symlog', linthreshx=1.0) - ax.grid(True) - - ax = fig.add_subplot(514) - # Plots a simple linear function 'f(x) = x' - ax.plot(x, x) - ax.set_xscale('symlog', linthreshx=0.1) - ax.grid(True) - - ax = fig.add_subplot(515) - # Plots a simple linear function 'f(x) = x' - ax.plot(x, x) - ax.set_xscale('symlog', linthreshx=0.01) - ax.grid(True) - ax.set_ylim(-0.1, 0.1) + fig, axs = plt.subplots(5, 1) + for ax, linthreshx in zip(axs, [20., 2., 1., 0.1, 0.01]): + ax.plot(x, x) + ax.set_xscale('symlog', linthreshx=linthreshx) + ax.grid(True) + axs[-1].set_ylim(-0.1, 0.1) def test_pcolorargs_5205(): @@ -1145,15 +1101,10 @@ def test_pcolormesh(): # The color array can include masked values: Zm = ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z) - fig = plt.figure() - ax = fig.add_subplot(131) - ax.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k') - - ax = fig.add_subplot(132) - ax.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w']) - - ax = fig.add_subplot(133) - ax.pcolormesh(Qx, Qz, Z, shading="gouraud") + fig, (ax1, ax2, ax3) = plt.subplots(1, 3) + ax1.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k') + ax2.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w']) + ax3.pcolormesh(Qx, Qz, Z, shading="gouraud") @image_comparison(baseline_images=['pcolormesh_datetime_axis'], diff --git a/lib/matplotlib/tests/test_backend_svg.py b/lib/matplotlib/tests/test_backend_svg.py index 2dc364404087..861c8922a8c6 100644 --- a/lib/matplotlib/tests/test_backend_svg.py +++ b/lib/matplotlib/tests/test_backend_svg.py @@ -18,8 +18,7 @@ def test_visibility(): - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() x = np.linspace(0, 4 * np.pi, 50) y = np.sin(x) diff --git a/lib/matplotlib/tests/test_backends_interactive.py b/lib/matplotlib/tests/test_backends_interactive.py index 0d4d41420839..7e6922ebcd43 100644 --- a/lib/matplotlib/tests/test_backends_interactive.py +++ b/lib/matplotlib/tests/test_backends_interactive.py @@ -49,8 +49,7 @@ def _get_testable_interactive_backends(): "webagg.port_retries": 1, }) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot([0, 1], [2, 3]) if rcParams["backend"].startswith("GTK3"): diff --git a/lib/matplotlib/tests/test_colorbar.py b/lib/matplotlib/tests/test_colorbar.py index e9c83841b45c..d956209c599b 100644 --- a/lib/matplotlib/tests/test_colorbar.py +++ b/lib/matplotlib/tests/test_colorbar.py @@ -210,8 +210,7 @@ def test_remove_from_figure(use_gridspec): """ Test `remove_from_figure` with the specified ``use_gridspec`` setting """ - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() sc = ax.scatter([1, 2], [3, 4], cmap="spring") sc.set_array(np.array([5, 6])) pre_figbox = np.array(ax.figbox) diff --git a/lib/matplotlib/tests/test_constrainedlayout.py b/lib/matplotlib/tests/test_constrainedlayout.py index 07950ee38bf5..c1ad1050c374 100644 --- a/lib/matplotlib/tests/test_constrainedlayout.py +++ b/lib/matplotlib/tests/test_constrainedlayout.py @@ -163,7 +163,6 @@ def test_constrained_layout9(): 'Test for handling suptitle and for sharex and sharey' fig, axs = plt.subplots(2, 2, constrained_layout=True, sharex=False, sharey=False) - # ax = fig.add_subplot(111) for ax in axs.flatten(): pcm = example_pcolor(ax, fontsize=24) ax.set_xlabel('') diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py index 9709a151a350..76af52341de9 100644 --- a/lib/matplotlib/tests/test_contour.py +++ b/lib/matplotlib/tests/test_contour.py @@ -15,8 +15,7 @@ def test_contour_shape_1d_valid(): y = np.arange(9) z = np.random.random((9, 10)) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.contour(x, y, z) @@ -27,8 +26,7 @@ def test_contour_shape_2d_valid(): xg, yg = np.meshgrid(x, y) z = np.random.random((9, 10)) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.contour(xg, yg, z) @@ -38,8 +36,7 @@ def test_contour_shape_mismatch_1(): y = np.arange(9) z = np.random.random((9, 10)) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) @@ -52,8 +49,7 @@ def test_contour_shape_mismatch_2(): y = np.arange(10) z = np.random.random((9, 10)) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) @@ -67,8 +63,7 @@ def test_contour_shape_mismatch_3(): xg, yg = np.meshgrid(x, y) z = np.random.random((9, 10)) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(xg, y, z) @@ -85,8 +80,7 @@ def test_contour_shape_mismatch_4(): b = np.random.random((9, 9)) z = np.random.random((9, 10)) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(b, g, z) @@ -105,8 +99,7 @@ def test_contour_shape_invalid_1(): y = np.random.random((3, 3, 3)) z = np.random.random((9, 10)) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) @@ -119,8 +112,7 @@ def test_contour_shape_invalid_2(): y = np.random.random((3, 3, 3)) z = np.random.random((3, 3, 3)) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) diff --git a/lib/matplotlib/tests/test_cycles.py b/lib/matplotlib/tests/test_cycles.py index ac876ee7fa3c..d1992e045507 100644 --- a/lib/matplotlib/tests/test_cycles.py +++ b/lib/matplotlib/tests/test_cycles.py @@ -12,8 +12,7 @@ @image_comparison(baseline_images=['color_cycle_basic'], remove_text=True, extensions=['png']) def test_colorcycle_basic(): - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.set_prop_cycle(cycler('color', ['r', 'g', 'y'])) xs = np.arange(10) ys = 0.25 * xs + 2 @@ -30,8 +29,7 @@ def test_colorcycle_basic(): @image_comparison(baseline_images=['marker_cycle', 'marker_cycle'], remove_text=True, extensions=['png']) def test_marker_cycle(): - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) + cycler('marker', ['.', '*', 'x'])) xs = np.arange(10) @@ -45,8 +43,7 @@ def test_marker_cycle(): ax.plot(xs, ys, label='red2 dot', lw=4, ms=16) ax.legend(loc='upper left') - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() # Test keyword arguments, numpy arrays, and generic iterators ax.set_prop_cycle(c=np.array(['r', 'g', 'y']), marker=iter(['.', '*', 'x'])) @@ -65,8 +62,7 @@ def test_marker_cycle(): @image_comparison(baseline_images=['lineprop_cycle_basic'], remove_text=True, extensions=['png']) def test_linestylecycle_basic(): - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.set_prop_cycle(cycler('ls', ['-', '--', ':'])) xs = np.arange(10) ys = 0.25 * xs + 2 @@ -83,8 +79,7 @@ def test_linestylecycle_basic(): @image_comparison(baseline_images=['fill_cycle_basic'], remove_text=True, extensions=['png']) def test_fillcycle_basic(): - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) + cycler('hatch', ['xx', 'O', '|-']) + cycler('linestyle', ['-', '--', ':'])) @@ -103,8 +98,7 @@ def test_fillcycle_basic(): @image_comparison(baseline_images=['fill_cycle_ignore'], remove_text=True, extensions=['png']) def test_fillcycle_ignore(): - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']) + cycler('hatch', ['xx', 'O', '|-']) + cycler('marker', ['.', '*', 'D'])) diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index 3897bacd50e8..d47e2c9b7748 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -102,8 +102,7 @@ def test_figimage1(): def test_image_python_io(): - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.plot([1,2,3]) buffer = io.BytesIO() fig.savefig(buffer) @@ -282,8 +281,7 @@ def test_image_clip(): def test_image_cliprect(): import matplotlib.patches as patches - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() d = [[1,2],[3,4]] im = ax.imshow(d, extent=(0,5,0,5)) @@ -294,12 +292,8 @@ def test_image_cliprect(): @image_comparison(baseline_images=['imshow'], remove_text=True, style='mpl20') def test_imshow(): - import numpy as np - import matplotlib.pyplot as plt - - fig = plt.figure() + fig, ax = plt.subplots() arr = np.arange(100).reshape((10, 10)) - ax = fig.add_subplot(111) ax.imshow(arr, interpolation="bilinear", extent=(1,2,1,2)) ax.set_xlim(0,3) ax.set_ylim(0,3) @@ -326,8 +320,7 @@ def test_image_shift(): tMin=734717.945208 tMax=734717.946366 - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.imshow(imgData, norm=LogNorm(), interpolation='none', extent=(tMin, tMax, 1, 100)) ax.set_aspect('auto') @@ -365,8 +358,7 @@ def test_image_edges(): remove_text=True, style='mpl20') def test_image_composite_background(): - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() arr = np.arange(12).reshape(4, 3) ax.imshow(arr, extent=[0, 2, 15, 0]) ax.imshow(arr, extent=[4, 6, 15, 0]) @@ -381,8 +373,7 @@ def test_image_composite_alpha(): Tests that the alpha value is recognized and correctly applied in the process of compositing images together. """ - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() arr = np.zeros((11, 21, 4)) arr[:, :, 0] = 1 arr[:, :, 3] = np.concatenate((np.arange(0, 1.1, 0.1), np.arange(0, 1, 0.1)[::-1])) @@ -410,9 +401,6 @@ def test_rasterize_dpi(): # when images end up in the wrong place in case of non-standard dpi setting. # Instead of high-res rasterization i use low-res. Therefore the fact that the # resolution is non-standard is easily checked by image_comparison. - import numpy as np - import matplotlib.pyplot as plt - img = np.asarray([[1, 2], [3, 4]]) fig, axes = plt.subplots(1, 3, figsize = (3, 1)) @@ -442,7 +430,7 @@ def test_bbox_image_inverted(): # This is just used to produce an image to feed to BboxImage image = np.arange(100).reshape((10, 10)) - ax = plt.subplot(111) + fig, ax = plt.subplots() bbox_im = BboxImage( TransformedBbox(Bbox([[100, 100], [0, 0]]), ax.transData)) bbox_im.set_data(image) @@ -467,8 +455,7 @@ def test_get_window_extent_for_AxisImage(): im = np.array([[0.25, 0.75, 1.0, 0.75], [0.1, 0.65, 0.5, 0.4], [0.6, 0.3, 0.0, 0.2], [0.7, 0.9, 0.4, 0.6]]) - fig = plt.figure(figsize=(10, 10), dpi=100) - ax = plt.subplot() + fig, ax = plt.subplots(figsize=(10, 10), dpi=100) ax.set_position([0, 0, 1, 1]) ax.set_xlim(0, 1) ax.set_ylim(0, 1) @@ -489,8 +476,7 @@ def test_zoom_and_clip_upper_origin(): image = np.arange(100) image = image.reshape((10, 10)) - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.imshow(image) ax.set_ylim(2.0, -0.5) ax.set_xlim(-0.5, 2.0) @@ -633,9 +619,7 @@ def test_log_scale_image(recwarn): Z = np.zeros((10, 10)) Z[::2] = 1 - fig = plt.figure() - ax = fig.add_subplot(111) - + fig, ax = plt.subplots() ax.imshow(Z, extent=[1, 100, 1, 100], cmap='viridis', vmax=1, vmin=-1) ax.set_yscale('log') @@ -920,8 +904,8 @@ def test_composite(fmt, counted, composite_image, count): # (on a single set of axes) into a single composite image. X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) Z = np.sin(Y ** 2) - fig = plt.figure() - ax = fig.add_subplot(1, 1, 1) + + fig, ax = plt.subplots() ax.set_xlim(0, 3) ax.imshow(Z, extent=[0, 1, 0, 1]) ax.imshow(Z[::-1], extent=[2, 3, 0, 1]) diff --git a/lib/matplotlib/tests/test_tightlayout.py b/lib/matplotlib/tests/test_tightlayout.py index 68139fc68c81..6bb0a5670adb 100644 --- a/lib/matplotlib/tests/test_tightlayout.py +++ b/lib/matplotlib/tests/test_tightlayout.py @@ -19,8 +19,7 @@ def example_plot(ax, fontsize=12): @image_comparison(baseline_images=['tight_layout1']) def test_tight_layout1(): 'Test tight_layout for a single subplot' - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() example_plot(ax, fontsize=24) plt.tight_layout() @@ -133,9 +132,8 @@ def test_tight_layout6(): @image_comparison(baseline_images=['tight_layout7']) def test_tight_layout7(): # tight layout with left and right titles - fig = plt.figure() fontsize = 24 - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.plot([1, 2]) ax.locator_params(nbins=3) ax.set_xlabel('x-label', fontsize=fontsize) diff --git a/lib/matplotlib/tests/test_ttconv.py b/lib/matplotlib/tests/test_ttconv.py index 6bb6feac74d5..31214e5ed2e9 100644 --- a/lib/matplotlib/tests/test_ttconv.py +++ b/lib/matplotlib/tests/test_ttconv.py @@ -12,8 +12,7 @@ def test_truetype_conversion(): fontname = os.path.abspath(fontname) fontprop = FontProperties(fname=fontname, size=80) matplotlib.rcParams['pdf.fonttype'] = 3 - fig = plt.figure() - ax = fig.add_subplot(111) + fig, ax = plt.subplots() ax.text(0, 0, "ABCDE", fontproperties=fontprop) ax.set_xticks([]) ax.set_yticks([]) diff --git a/tutorials/advanced/path_tutorial.py b/tutorials/advanced/path_tutorial.py index a440a8b2aeaf..e0444c5e1cae 100644 --- a/tutorials/advanced/path_tutorial.py +++ b/tutorials/advanced/path_tutorial.py @@ -36,8 +36,7 @@ path = Path(verts, codes) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() patch = patches.PathPatch(path, facecolor='orange', lw=2) ax.add_patch(patch) ax.set_xlim(-2, 2) @@ -91,8 +90,7 @@ path = Path(verts, codes) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() patch = patches.PathPatch(path, facecolor='none', lw=2) ax.add_patch(patch) @@ -182,9 +180,7 @@ import matplotlib.patches as patches import matplotlib.path as path -fig = plt.figure() -ax = fig.add_subplot(111) - +fig, ax = plt.subplots() # Fixing random state for reproducibility np.random.seed(19680801) diff --git a/tutorials/advanced/transforms_tutorial.py b/tutorials/advanced/transforms_tutorial.py index 5e0d8dc5e85c..de12aeec7e0a 100644 --- a/tutorials/advanced/transforms_tutorial.py +++ b/tutorials/advanced/transforms_tutorial.py @@ -92,8 +92,7 @@ x = np.arange(0, 10, 0.005) y = np.exp(-x/2.) * np.sin(2*np.pi*x) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10) ax.set_ylim(-1, 1) @@ -141,8 +140,7 @@ x = np.arange(0, 10, 0.005) y = np.exp(-x/2.) * np.sin(2*np.pi*x) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10) ax.set_ylim(-1, 1) @@ -244,8 +242,7 @@ # move, but the circle will remain fixed because it is not in `data` # coordinates and will always remain at the center of the axes. -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() x, y = 10*np.random.rand(2, 1000) ax.plot(x, y, 'go', alpha=0.2) # plot some data in data coordinates @@ -278,9 +275,7 @@ import matplotlib.transforms as transforms -fig = plt.figure() -ax = fig.add_subplot(111) - +fig, ax = plt.subplots() x = np.random.randn(1000) ax.hist(x, 30) diff --git a/tutorials/intermediate/artists.py b/tutorials/intermediate/artists.py index 3ee20a910d73..14f8f830bfad 100644 --- a/tutorials/intermediate/artists.py +++ b/tutorials/intermediate/artists.py @@ -437,9 +437,7 @@ class in the matplotlib API, and the one you will be working with most # # .. sourcecode:: ipython # -# In [261]: fig = plt.figure() -# -# In [262]: ax = fig.add_subplot(111) +# In [262]: fig, ax = plt.subplots() # # # create a rectangle instance # In [263]: rect = matplotlib.patches.Rectangle( (1,1), width=5, height=12) @@ -683,8 +681,7 @@ class in the matplotlib API, and the one you will be working with most # Fixing random state for reproducibility np.random.seed(19680801) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(100*np.random.rand(20)) formatter = ticker.FormatStrFormatter('$%1.2f') diff --git a/tutorials/introductory/usage.py b/tutorials/introductory/usage.py index 33860d5280bc..7aa538c66bf1 100644 --- a/tutorials/introductory/usage.py +++ b/tutorials/introductory/usage.py @@ -221,8 +221,7 @@ x = np.arange(0, 10, 0.2) y = np.sin(x) -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() ax.plot(x, y) plt.show() diff --git a/tutorials/text/pgf.py b/tutorials/text/pgf.py index 54118744a74e..ec71c58281c1 100644 --- a/tutorials/text/pgf.py +++ b/tutorials/text/pgf.py @@ -69,13 +69,11 @@ with PdfPages('multipage.pdf', metadata={'author': 'Me'}) as pdf: - fig1 = plt.figure() - ax1 = fig1.add_subplot(1, 1, 1) + fig1, ax1 = plt.subplots() ax1.plot([1, 5, 3]) pdf.savefig(fig1) - fig2 = plt.figure() - ax2 = fig2.add_subplot(1, 1, 1) + fig2, ax2 = plt.subplots() ax2.plot([1, 5, 3]) pdf.savefig(fig2)