From ec5e8863a6352da673b55cb971529f38278cf64e Mon Sep 17 00:00:00 2001 From: Paul Hobson Date: Thu, 22 Mar 2018 12:10:01 -0700 Subject: [PATCH] DOC: use OO-ish interface in img/contour examples --- .../images_contours_and_fields/barb_demo.py | 24 +++---- .../barcode_demo.py | 8 +-- .../contour_corner_mask.py | 14 ++-- .../contour_demo.py | 68 +++++++++---------- .../contour_image.py | 58 ++++++---------- .../contour_label_demo.py | 32 +++++---- .../contourf_demo.py | 33 ++++----- .../contourf_hatching.py | 23 +++---- .../demo_bboximage.py | 12 ++-- .../figimage_demo.py | 2 +- .../images_contours_and_fields/image_demo.py | 9 +-- .../image_masked.py | 2 +- .../interpolation_methods.py | 8 +-- .../quadmesh_demo.py | 3 +- .../images_contours_and_fields/quiver_demo.py | 30 ++++---- .../shading_example.py | 20 +++--- .../specgram_demo.py | 20 +++--- .../tricontour_demo.py | 26 +++---- .../tricontour_smooth_delaunay.py | 16 ++--- .../tricontour_smooth_user.py | 12 ++-- .../triinterp_demo.py | 39 ++++++----- .../tripcolor_demo.py | 34 +++++----- .../triplot_demo.py | 20 +++--- lib/matplotlib/axes/_base.py | 2 +- 24 files changed, 242 insertions(+), 273 deletions(-) diff --git a/examples/images_contours_and_fields/barb_demo.py b/examples/images_contours_and_fields/barb_demo.py index 12ad4d727ab2..36aa86410696 100644 --- a/examples/images_contours_and_fields/barb_demo.py +++ b/examples/images_contours_and_fields/barb_demo.py @@ -22,26 +22,23 @@ data = np.array(data, dtype=[('x', np.float32), ('y', np.float32), ('u', np.float32), ('v', np.float32)]) +fig1, axs1 = plt.subplots(nrows=2, ncols=2) # Default parameters, uniform grid -ax = plt.subplot(2, 2, 1) -ax.barbs(X, Y, U, V) +axs1[0, 0].barbs(X, Y, U, V) # Arbitrary set of vectors, make them longer and change the pivot point # (point around which they're rotated) to be the middle -ax = plt.subplot(2, 2, 2) -ax.barbs(data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle') +axs1[0, 1].barbs(data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle') # Showing colormapping with uniform grid. Fill the circle for an empty barb, # don't round the values, and change some of the size parameters -ax = plt.subplot(2, 2, 3) -ax.barbs(X, Y, U, V, np.sqrt(U * U + V * V), fill_empty=True, rounding=False, - sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3)) +axs1[1, 0].barbs(X, Y, U, V, np.sqrt(U * U + V * V), fill_empty=True, rounding=False, + sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3)) # Change colors as well as the increments for parts of the barbs -ax = plt.subplot(2, 2, 4) -ax.barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r', - barbcolor=['b', 'g'], - barb_increments=dict(half=10, full=20, flag=100), flip_barb=True) +axs1[1, 1].barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r', + barbcolor=['b', 'g'], flip_barb=True, + barb_increments=dict(half=10, full=20, flag=100)) # Masked arrays are also supported masked_u = np.ma.masked_array(data['u']) @@ -50,8 +47,7 @@ # Identical plot to panel 2 in the first figure, but with the point at # (0.5, 0.25) missing (masked) -fig2 = plt.figure() -ax = fig2.add_subplot(1, 1, 1) -ax.barbs(data['x'], data['y'], masked_u, data['v'], length=8, pivot='middle') +fig2, ax2 = plt.subplots() +ax2.barbs(data['x'], data['y'], masked_u, data['v'], length=8, pivot='middle') plt.show() diff --git a/examples/images_contours_and_fields/barcode_demo.py b/examples/images_contours_and_fields/barcode_demo.py index afe3700b2bb5..75227d01f42e 100644 --- a/examples/images_contours_and_fields/barcode_demo.py +++ b/examples/images_contours_and_fields/barcode_demo.py @@ -20,12 +20,12 @@ fig = plt.figure() # a vertical barcode -- this is broken at present -ax = fig.add_axes([0.1, 0.3, 0.1, 0.6], **axprops) -ax.imshow(x.reshape((-1, 1)), **barprops) +ax1 = fig.add_axes([0.1, 0.3, 0.1, 0.6], **axprops) +ax1.imshow(x.reshape((-1, 1)), **barprops) # a horizontal barcode -ax = fig.add_axes([0.3, 0.1, 0.6, 0.1], **axprops) -ax.imshow(x.reshape((1, -1)), **barprops) +ax2 = fig.add_axes([0.3, 0.1, 0.6, 0.1], **axprops) +ax2.imshow(x.reshape((1, -1)), **barprops) plt.show() diff --git a/examples/images_contours_and_fields/contour_corner_mask.py b/examples/images_contours_and_fields/contour_corner_mask.py index 1a2466bf899b..03d821959299 100644 --- a/examples/images_contours_and_fields/contour_corner_mask.py +++ b/examples/images_contours_and_fields/contour_corner_mask.py @@ -23,16 +23,16 @@ z = np.ma.array(z, mask=mask) corner_masks = [False, True] -for i, corner_mask in enumerate(corner_masks): - plt.subplot(1, 2, i + 1) - cs = plt.contourf(x, y, z, corner_mask=corner_mask) - plt.contour(cs, colors='k') - plt.title('corner_mask = {0}'.format(corner_mask)) +fig, axs = plt.subplots(ncols=2) +for ax, corner_mask in zip(axs, corner_masks): + cs = ax.contourf(x, y, z, corner_mask=corner_mask) + ax.contour(cs, colors='k') + ax.set_title('corner_mask = {0}'.format(corner_mask)) # Plot grid. - plt.grid(c='k', ls='-', alpha=0.3) + ax.grid(c='k', ls='-', alpha=0.3) # Indicate masked points with red circles. - plt.plot(np.ma.array(x, mask=~mask), y, 'ro') + ax.plot(np.ma.array(x, mask=~mask), y, 'ro') plt.show() diff --git a/examples/images_contours_and_fields/contour_demo.py b/examples/images_contours_and_fields/contour_demo.py index 4689d3507f64..a3366c88979a 100644 --- a/examples/images_contours_and_fields/contour_demo.py +++ b/examples/images_contours_and_fields/contour_demo.py @@ -30,10 +30,10 @@ # over the line segments of the contour, removing the lines beneath # the label -plt.figure() -CS = plt.contour(X, Y, Z) -plt.clabel(CS, inline=1, fontsize=10) -plt.title('Simplest default with labels') +fig, ax = plt.subplots() +CS = ax.contour(X, Y, Z) +ax.clabel(CS, inline=1, fontsize=10) +ax.set_title('Simplest default with labels') ############################################################################### @@ -41,85 +41,79 @@ # (in data coordinate). See ginput_manual_clabel.py for interactive # placement. -plt.figure() -CS = plt.contour(X, Y, Z) +fig, ax = plt.subplots() +CS = ax.contour(X, Y, Z) manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)] -plt.clabel(CS, inline=1, fontsize=10, manual=manual_locations) -plt.title('labels at selected locations') +ax.clabel(CS, inline=1, fontsize=10, manual=manual_locations) +ax.set_title('labels at selected locations') ############################################################################### # You can force all the contours to be the same color. -plt.figure() -CS = plt.contour(X, Y, Z, 6, +fig, ax = plt.subplots() +CS = ax.contour(X, Y, Z, 6, colors='k', # negative contours will be dashed by default ) -plt.clabel(CS, fontsize=9, inline=1) -plt.title('Single color - negative contours dashed') +ax.clabel(CS, fontsize=9, inline=1) +ax.set_title('Single color - negative contours dashed') ############################################################################### # You can set negative contours to be solid instead of dashed: matplotlib.rcParams['contour.negative_linestyle'] = 'solid' -plt.figure() -CS = plt.contour(X, Y, Z, 6, +fig, ax = plt.subplots() +CS = ax.contour(X, Y, Z, 6, colors='k', # negative contours will be dashed by default ) -plt.clabel(CS, fontsize=9, inline=1) -plt.title('Single color - negative contours solid') +ax.clabel(CS, fontsize=9, inline=1) +ax.set_title('Single color - negative contours solid') ############################################################################### # And you can manually specify the colors of the contour -plt.figure() -CS = plt.contour(X, Y, Z, 6, +fig, ax = plt.subplots() +CS = ax.contour(X, Y, Z, 6, linewidths=np.arange(.5, 4, .5), colors=('r', 'green', 'blue', (1, 1, 0), '#afeeee', '0.5') ) -plt.clabel(CS, fontsize=9, inline=1) -plt.title('Crazy lines') +ax.clabel(CS, fontsize=9, inline=1) +ax.set_title('Crazy lines') ############################################################################### # Or you can use a colormap to specify the colors; the default # colormap will be used for the contour lines -plt.figure() -im = plt.imshow(Z, interpolation='bilinear', origin='lower', +fig, ax = plt.subplots() +im = ax.imshow(Z, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=(-3, 3, -2, 2)) levels = np.arange(-1.2, 1.6, 0.2) -CS = plt.contour(Z, levels, - origin='lower', - linewidths=2, - extent=(-3, 3, -2, 2)) +CS = ax.contour(Z, levels, origin='lower', cmap='flag', + linewidths=2, extent=(-3, 3, -2, 2)) # Thicken the zero contour. zc = CS.collections[6] plt.setp(zc, linewidth=4) -plt.clabel(CS, levels[1::2], # label every second level - inline=1, - fmt='%1.1f', - fontsize=14) +ax.clabel(CS, levels[1::2], # label every second level + inline=1, fmt='%1.1f', + cmap='flag', fontsize=14) # make a colorbar for the contour lines -CB = plt.colorbar(CS, shrink=0.8, extend='both') +CB = fig.colorbar(CS, shrink=0.8, extend='both') -plt.title('Lines with colorbar') -#plt.hot() # Now change the colormap for the contour lines and colorbar -plt.flag() +ax.set_title('Lines with colorbar') # We can still add a colorbar for the image, too. -CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8) +CBI = fig.colorbar(im, orientation='horizontal', shrink=0.8) # This makes the original colorbar look a bit out of place, # so let's improve its position. -l, b, w, h = plt.gca().get_position().bounds +l, b, w, h = ax.get_position().bounds ll, bb, ww, hh = CB.ax.get_position().bounds CB.ax.set_position([ll, b + 0.1*h, ww, h*0.8]) - plt.show() diff --git a/examples/images_contours_and_fields/contour_image.py b/examples/images_contours_and_fields/contour_image.py index 3f0f007dcca4..94000053e159 100644 --- a/examples/images_contours_and_fields/contour_image.py +++ b/examples/images_contours_and_fields/contour_image.py @@ -34,14 +34,12 @@ norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max()) cmap = cm.PRGn -fig = plt.figure() +fig, _axs = plt.subplots(nrows=2, ncols=2) fig.subplots_adjust(hspace=0.3) +axs = _axs.flatten() - -plt.subplot(2, 2, 1) - -cset1 = plt.contourf(X, Y, Z, levels, - cmap=cm.get_cmap(cmap, len(levels) - 1), norm=norm) +cset1 = axs[0].contourf(X, Y, Z, levels, norm=norm, + cmap=cm.get_cmap(cmap, len(levels) - 1)) # It is not necessary, but for the colormap, we need only the # number of levels minus 1. To avoid discretization error, use # either this number or a large number such as the default (256). @@ -51,7 +49,7 @@ # of the polygons in the collections returned by contourf. # Use levels output from previous call to guarantee they are the same. -cset2 = plt.contour(X, Y, Z, cset1.levels, colors='k') +cset2 = axs[0].contour(X, Y, Z, cset1.levels, colors='k') # We don't really need dashed contour lines to indicate negative # regions, so let's turn them off. @@ -64,28 +62,18 @@ # We are making a thick green line as a zero contour. # Specify the zero level as a tuple with only 0 in it. -cset3 = plt.contour(X, Y, Z, (0,), colors='g', linewidths=2) -plt.title('Filled contours') -plt.colorbar(cset1) - +cset3 = axs[0].contour(X, Y, Z, (0,), colors='g', linewidths=2) +axs[0].set_title('Filled contours') +fig.colorbar(cset1, ax=axs[0]) -plt.subplot(2, 2, 2) -plt.imshow(Z, extent=extent, cmap=cmap, norm=norm) -v = plt.axis() -plt.contour(Z, levels, colors='k', origin='upper', extent=extent) -plt.axis(v) -plt.title("Image, origin 'upper'") +axs[1].imshow(Z, extent=extent, cmap=cmap, norm=norm) +axs[1].contour(Z, levels, colors='k', origin='upper', extent=extent) +axs[1].set_title("Image, origin 'upper'") -plt.subplot(2, 2, 3) - -plt.imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm) -v = plt.axis() -plt.contour(Z, levels, colors='k', origin='lower', extent=extent) -plt.axis(v) -plt.title("Image, origin 'lower'") - -plt.subplot(2, 2, 4) +axs[2].imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm) +axs[2].contour(Z, levels, colors='k', origin='lower', extent=extent) +axs[2].set_title("Image, origin 'lower'") # We will use the interpolation "nearest" here to show the actual # image pixels. @@ -93,15 +81,13 @@ # This is intentional. The Z values are defined at the center of each # image pixel (each color block on the following subplot), so the # domain that is contoured does not extend beyond these pixel centers. -im = plt.imshow(Z, interpolation='nearest', extent=extent, +im = axs[3].imshow(Z, interpolation='nearest', extent=extent, cmap=cmap, norm=norm) -v = plt.axis() -plt.contour(Z, levels, colors='k', origin='image', extent=extent) -plt.axis(v) -ylim = plt.get(plt.gca(), 'ylim') -plt.setp(plt.gca(), ylim=ylim[::-1]) -plt.title("Origin from rc, reversed y-axis") -plt.colorbar(im) - -plt.tight_layout() +axs[3].contour(Z, levels, colors='k', origin='image', extent=extent) +ylim = axs[3].get_ylim() +axs[3].set_ylim(ylim[::-1]) +axs[3].set_title("Origin from rc, reversed y-axis") +fig.colorbar(im, ax=axs[3]) + +fig.tight_layout() plt.show() diff --git a/examples/images_contours_and_fields/contour_label_demo.py b/examples/images_contours_and_fields/contour_label_demo.py index 7140b9b13a44..ba5e2301b20f 100644 --- a/examples/images_contours_and_fields/contour_label_demo.py +++ b/examples/images_contours_and_fields/contour_label_demo.py @@ -8,6 +8,7 @@ See also contour_demo.py. """ + import matplotlib import numpy as np import matplotlib.cm as cm @@ -32,14 +33,10 @@ # Make contour labels using creative float classes # Follows suggestion of Manuel Metz -plt.figure() - -# Basic contour plot -CS = plt.contour(X, Y, Z) - - # Define a class that forces representation of float to look a certain way # This remove trailing zero so '1.0' becomes '1' + + class nf(float): def __repr__(self): str = '%.1f' % (self.__float__(),) @@ -49,6 +46,10 @@ def __repr__(self): return '%.1f' % self.__float__() +# Basic contour plot +fig, ax = plt.subplots() +CS = ax.contour(X, Y, Z) + # Recast levels to new class CS.levels = [nf(val) for val in CS.levels] @@ -57,33 +58,34 @@ def __repr__(self): fmt = r'%r \%%' else: fmt = '%r %%' -plt.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10) + +ax.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10) ############################################################################### # Label contours with arbitrary strings using a dictionary -plt.figure() +fig1, ax1 = plt.subplots() # Basic contour plot -CS = plt.contour(X, Y, Z) +CS1 = ax1.contour(X, Y, Z) fmt = {} strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh'] -for l, s in zip(CS.levels, strs): +for l, s in zip(CS1.levels, strs): fmt[l] = s # Label every other level using strings -plt.clabel(CS, CS.levels[::2], inline=True, fmt=fmt, fontsize=10) +ax1.clabel(CS1, CS1.levels[::2], inline=True, fmt=fmt, fontsize=10) ############################################################################### # Use a Formatter -plt.figure() +fig2, ax2 = plt.subplots() -CS = plt.contour(X, Y, 100**Z, locator=plt.LogLocator()) +CS2 = ax2.contour(X, Y, 100**Z, locator=plt.LogLocator()) fmt = ticker.LogFormatterMathtext() fmt.create_dummy_axis() -plt.clabel(CS, CS.levels, fmt=fmt) -plt.title("$100^Z$") +ax2.clabel(CS2, CS2.levels, fmt=fmt) +ax2.set_title("$100^Z$") plt.show() diff --git a/examples/images_contours_and_fields/contourf_demo.py b/examples/images_contours_and_fields/contourf_demo.py index 41523cfdf7c2..d4becd6d8ef1 100644 --- a/examples/images_contours_and_fields/contourf_demo.py +++ b/examples/images_contours_and_fields/contourf_demo.py @@ -37,32 +37,33 @@ # this is usually not such a good idea, because they don't # occur on nice boundaries, but we do it here for purposes # of illustration. -CS = plt.contourf(X, Y, Z, 10, cmap=plt.cm.bone, origin=origin) + +fig1, ax2 = plt.subplots() +CS = ax2.contourf(X, Y, Z, 10, cmap=plt.cm.bone, origin=origin) # Note that in the following, we explicitly pass in a subset of # the contour levels used for the filled contours. Alternatively, # We could pass in additional levels to provide extra resolution, # or leave out the levels kwarg to use all of the original levels. -CS2 = plt.contour(CS, levels=CS.levels[::2], colors='r', origin=origin) +CS2 = ax2.contour(CS, levels=CS.levels[::2], colors='r', origin=origin) -plt.title('Nonsense (3 masked regions)') -plt.xlabel('word length anomaly') -plt.ylabel('sentence length anomaly') +ax2.set_title('Nonsense (3 masked regions)') +ax2.set_xlabel('word length anomaly') +ax2.set_ylabel('sentence length anomaly') # Make a colorbar for the ContourSet returned by the contourf call. -cbar = plt.colorbar(CS) +cbar = fig1.colorbar(CS) cbar.ax.set_ylabel('verbosity coefficient') # Add the contour line levels to the colorbar cbar.add_lines(CS2) -plt.figure() - +fig2, ax2 = plt.subplots() # Now make a contour plot with the levels specified, # and with the colormap generated automatically from a list # of colors. levels = [-1.5, -1, -0.5, 0, 0.5, 1] -CS3 = plt.contourf(X, Y, Z, levels, +CS3 = ax2.contourf(X, Y, Z, levels, colors=('r', 'g', 'b'), origin=origin, extend='both') @@ -72,16 +73,16 @@ CS3.cmap.set_under('yellow') CS3.cmap.set_over('cyan') -CS4 = plt.contour(X, Y, Z, levels, +CS4 = ax2.contour(X, Y, Z, levels, colors=('k',), linewidths=(3,), origin=origin) -plt.title('Listed colors (3 masked regions)') -plt.clabel(CS4, fmt='%2.1f', colors='w', fontsize=14) +ax2.set_title('Listed colors (3 masked regions)') +ax2.clabel(CS4, fmt='%2.1f', colors='w', fontsize=14) # Notice that the colorbar command gets all the information it # needs from the ContourSet object, CS3. -plt.colorbar(CS3) +fig2.colorbar(CS3) # Illustrate all 4 possible "extend" settings: extends = ["neither", "both", "min", "max"] @@ -94,12 +95,12 @@ # no effect: # cmap.set_bad("red") -fig, axs = plt.subplots(2, 2) -fig.subplots_adjust(hspace=0.3) +fig3, axs = plt.subplots(2, 2) +fig3.subplots_adjust(hspace=0.3) for ax, extend in zip(axs.ravel(), extends): cs = ax.contourf(X, Y, Z, levels, cmap=cmap, extend=extend, origin=origin) - fig.colorbar(cs, ax=ax, shrink=0.9) + fig3.colorbar(cs, ax=ax, shrink=0.9) ax.set_title("extend = %s" % extend) ax.locator_params(nbins=4) diff --git a/examples/images_contours_and_fields/contourf_hatching.py b/examples/images_contours_and_fields/contourf_hatching.py index f13c477a9613..698f69b4ce24 100644 --- a/examples/images_contours_and_fields/contourf_hatching.py +++ b/examples/images_contours_and_fields/contourf_hatching.py @@ -20,27 +20,22 @@ ############################################################################### # Plot 1: the simplest hatched plot with a colorbar -fig = plt.figure() -cs = plt.contourf(x, y, z, hatches=['-', '/', '\\', '//'], - cmap=plt.get_cmap('gray'), - extend='both', alpha=0.5 - ) -plt.colorbar() +fig1, ax1 = plt.subplots() +cs = ax1.contourf(x, y, z, hatches=['-', '/', '\\', '//'], + cmap='gray', extend='both', alpha=0.5) +fig1.colorbar(cs) ############################################################################### # Plot 2: a plot of hatches without color with a legend -plt.figure() +fig2, ax2 = plt.subplots() n_levels = 6 -plt.contour(x, y, z, n_levels, colors='black', linestyles='-') -cs = plt.contourf(x, y, z, n_levels, colors='none', +ax2.contour(x, y, z, n_levels, colors='black', linestyles='-') +cs = ax2.contourf(x, y, z, n_levels, colors='none', hatches=['.', '/', '\\', None, '\\\\', '*'], - extend='lower' - ) + extend='lower') # create a legend for the contour set artists, labels = cs.legend_elements() -plt.legend(artists, labels, handleheight=2) - - +ax2.legend(artists, labels, handleheight=2) plt.show() diff --git a/examples/images_contours_and_fields/demo_bboximage.py b/examples/images_contours_and_fields/demo_bboximage.py index d714a6a06b43..2e774337163d 100644 --- a/examples/images_contours_and_fields/demo_bboximage.py +++ b/examples/images_contours_and_fields/demo_bboximage.py @@ -11,10 +11,9 @@ if __name__ == "__main__": - fig = plt.figure(1) - ax = plt.subplot(121) + fig, (ax1, ax2) = plt.subplots(ncols=2) - txt = ax.text(0.5, 0.5, "test", size=30, ha="center", color="w") + txt = ax1.text(0.5, 0.5, "test", size=30, ha="center", color="w") kwargs = dict() bbox_image = BboxImage(txt.get_window_extent, @@ -25,9 +24,8 @@ ) a = np.arange(256).reshape(1, 256)/256. bbox_image.set_data(a) - ax.add_artist(bbox_image) + ax1.add_artist(bbox_image) - ax = plt.subplot(122) a = np.linspace(0, 1, 256).reshape(1, -1) a = np.vstack((a, a)) @@ -51,7 +49,7 @@ bbox0 = Bbox.from_bounds(ix*dx*(1 + xpad_fraction), 1. - iy*dy*(1 + ypad_fraction) - dy, dx, dy) - bbox = TransformedBbox(bbox0, ax.transAxes) + bbox = TransformedBbox(bbox0, ax2.transAxes) bbox_image = BboxImage(bbox, cmap=plt.get_cmap(m), @@ -61,7 +59,7 @@ ) bbox_image.set_data(a) - ax.add_artist(bbox_image) + ax2.add_artist(bbox_image) plt.draw() plt.show() diff --git a/examples/images_contours_and_fields/figimage_demo.py b/examples/images_contours_and_fields/figimage_demo.py index 126c3de56e34..1c4ef70a2939 100644 --- a/examples/images_contours_and_fields/figimage_demo.py +++ b/examples/images_contours_and_fields/figimage_demo.py @@ -3,7 +3,7 @@ Figimage Demo ============= -This illustrates placing images directly in the figure, with no axes. +This illustrates placing images directly in the figure, with no Axes objects. """ import numpy as np diff --git a/examples/images_contours_and_fields/image_demo.py b/examples/images_contours_and_fields/image_demo.py index 820114cc2be0..a527446d5958 100644 --- a/examples/images_contours_and_fields/image_demo.py +++ b/examples/images_contours_and_fields/image_demo.py @@ -28,9 +28,10 @@ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (Z1 - Z2) * 2 -im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn, - origin='lower', extent=[-3, 3, -3, 3], - vmax=abs(Z).max(), vmin=-abs(Z).max()) +fig, ax = plt.subplots() +im = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn, + origin='lower', extent=[-3, 3, -3, 3], + vmax=abs(Z).max(), vmin=-abs(Z).max()) plt.show() @@ -44,7 +45,7 @@ fig, ax = plt.subplots() ax.imshow(image) -ax.axis('off') # clear x- and y-axes +ax.axis('off') # clear x-axis and y-axis # And another image diff --git a/examples/images_contours_and_fields/image_masked.py b/examples/images_contours_and_fields/image_masked.py index 029201ef1a1b..cadba0fe9e49 100644 --- a/examples/images_contours_and_fields/image_masked.py +++ b/examples/images_contours_and_fields/image_masked.py @@ -42,7 +42,7 @@ # range to which the regular palette color scale is applied. # Anything above that range is colored based on palette.set_over, etc. -# set up the axes +# set up the Axes objets fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(6, 5.4)) # plot using 'continuous' color map diff --git a/examples/images_contours_and_fields/interpolation_methods.py b/examples/images_contours_and_fields/interpolation_methods.py index 0e613572089b..2108b79dbdba 100644 --- a/examples/images_contours_and_fields/interpolation_methods.py +++ b/examples/images_contours_and_fields/interpolation_methods.py @@ -27,13 +27,13 @@ grid = np.random.rand(4, 4) -fig, axes = plt.subplots(3, 6, figsize=(12, 6), - subplot_kw={'xticks': [], 'yticks': []}) +fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(12, 6), + subplot_kw={'xticks': [], 'yticks': []}) fig.subplots_adjust(hspace=0.3, wspace=0.05) -for ax, interp_method in zip(axes.flat, methods): +for ax, interp_method in zip(axs.flat, methods): ax.imshow(grid, interpolation=interp_method, cmap='viridis') - ax.set_title(interp_method) + ax.set_title(str(interp_method)) plt.show() diff --git a/examples/images_contours_and_fields/quadmesh_demo.py b/examples/images_contours_and_fields/quadmesh_demo.py index 33f2b78ca4c3..0c133e34200d 100644 --- a/examples/images_contours_and_fields/quadmesh_demo.py +++ b/examples/images_contours_and_fields/quadmesh_demo.py @@ -26,7 +26,7 @@ # The color array can include masked values. Zm = np.ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z) -fig, axs = plt.subplots(1, 3) +fig, axs = plt.subplots(nrows=1, ncols=3) axs[0].pcolormesh(Qx, Qz, Z, shading='gouraud') axs[0].set_title('Without masked values') @@ -42,5 +42,4 @@ axs[2].set_title('With masked values') fig.tight_layout() - plt.show() diff --git a/examples/images_contours_and_fields/quiver_demo.py b/examples/images_contours_and_fields/quiver_demo.py index bb92e10b5bc1..636a046ee0d5 100644 --- a/examples/images_contours_and_fields/quiver_demo.py +++ b/examples/images_contours_and_fields/quiver_demo.py @@ -6,7 +6,7 @@ Known problem: the plot autoscaling does not take into account the arrows, so those on the boundaries are often out of the picture. This is *not* an easy problem to solve in a perfectly general way. -The workaround is to manually expand the axes. +The workaround is to manually expand the Axes objects. """ import matplotlib.pyplot as plt import numpy as np @@ -18,31 +18,31 @@ ############################################################################### -plt.figure() -plt.title('Arrows scale with plot width, not view') -Q = plt.quiver(X, Y, U, V, units='width') -qk = plt.quiverkey(Q, 0.9, 0.9, 2, r'$2 \frac{m}{s}$', labelpos='E', +fig1, ax1 = plt.subplots() +ax1.set_title('Arrows scale with plot width, not view') +Q = ax1.quiver(X, Y, U, V, units='width') +qk = ax1.quiverkey(Q, 0.9, 0.9, 2, r'$2 \frac{m}{s}$', labelpos='E', coordinates='figure') ############################################################################### -plt.figure() -plt.title("pivot='mid'; every third arrow; units='inches'") -Q = plt.quiver(X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3], +fig2, ax2 = plt.subplots() +ax2.set_title("pivot='mid'; every third arrow; units='inches'") +Q = ax2.quiver(X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3], pivot='mid', units='inches') -qk = plt.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E', +qk = ax2.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E', coordinates='figure') -plt.scatter(X[::3, ::3], Y[::3, ::3], color='r', s=5) +ax2.scatter(X[::3, ::3], Y[::3, ::3], color='r', s=5) ############################################################################### -plt.figure() -plt.title("pivot='tip'; scales with x view") +fig3, ax3 = plt.subplots() +ax3.set_title("pivot='tip'; scales with x view") M = np.hypot(U, V) -Q = plt.quiver(X, Y, U, V, M, units='x', pivot='tip', width=0.022, +Q = ax3.quiver(X, Y, U, V, M, units='x', pivot='tip', width=0.022, scale=1 / 0.15) -qk = plt.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E', +qk = ax3.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E', coordinates='figure') -plt.scatter(X, Y, color='k', s=5) +ax3.scatter(X, Y, color='k', s=5) plt.show() diff --git a/examples/images_contours_and_fields/shading_example.py b/examples/images_contours_and_fields/shading_example.py index 795d5e3a6776..ef8d171a300e 100644 --- a/examples/images_contours_and_fields/shading_example.py +++ b/examples/images_contours_and_fields/shading_example.py @@ -35,26 +35,26 @@ def main(): def compare(z, cmap, ve=1): # Create subplots and hide ticks - fig, axes = plt.subplots(ncols=2, nrows=2) - for ax in axes.flat: + fig, axs = plt.subplots(ncols=2, nrows=2) + for ax in axs.flat: ax.set(xticks=[], yticks=[]) # Illuminate the scene from the northwest ls = LightSource(azdeg=315, altdeg=45) - axes[0, 0].imshow(z, cmap=cmap) - axes[0, 0].set(xlabel='Colormapped Data') + axs[0, 0].imshow(z, cmap=cmap) + axs[0, 0].set(xlabel='Colormapped Data') - axes[0, 1].imshow(ls.hillshade(z, vert_exag=ve), cmap='gray') - axes[0, 1].set(xlabel='Illumination Intensity') + axs[0, 1].imshow(ls.hillshade(z, vert_exag=ve), cmap='gray') + axs[0, 1].set(xlabel='Illumination Intensity') rgb = ls.shade(z, cmap=cmap, vert_exag=ve, blend_mode='hsv') - axes[1, 0].imshow(rgb) - axes[1, 0].set(xlabel='Blend Mode: "hsv" (default)') + axs[1, 0].imshow(rgb) + axs[1, 0].set(xlabel='Blend Mode: "hsv" (default)') rgb = ls.shade(z, cmap=cmap, vert_exag=ve, blend_mode='overlay') - axes[1, 1].imshow(rgb) - axes[1, 1].set(xlabel='Blend Mode: "overlay"') + axs[1, 1].imshow(rgb) + axs[1, 1].set(xlabel='Blend Mode: "overlay"') return fig diff --git a/examples/images_contours_and_fields/specgram_demo.py b/examples/images_contours_and_fields/specgram_demo.py index 15d1479826f2..681ac2ba36e6 100644 --- a/examples/images_contours_and_fields/specgram_demo.py +++ b/examples/images_contours_and_fields/specgram_demo.py @@ -11,7 +11,6 @@ # Fixing random state for reproducibility np.random.seed(19680801) - dt = 0.0005 t = np.arange(0.0, 20.0, dt) s1 = np.sin(2 * np.pi * 100 * t) @@ -25,16 +24,15 @@ nse = 0.01 * np.random.random(size=len(t)) x = s1 + s2 + nse # the signal -NFFT = 1024 # the length of the windowing segments +NFFT = 1024 # the length of the windowing segments Fs = int(1.0 / dt) # the sampling frequency -# Pxx is the segments x freqs array of instantaneous power, freqs is -# the frequency vector, bins are the centers of the time bins in which -# the power is computed, and im is the matplotlib.image.AxesImage -# instance - -ax1 = plt.subplot(211) -plt.plot(t, x) -plt.subplot(212, sharex=ax1) -Pxx, freqs, bins, im = plt.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900) +fig, (ax1, ax2) = plt.subplots(nrows=2) +ax1.plot(t, x) +Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900) +# The `specgram` method returns 4 objects. They are: +# - Pxx: the periodogram +# - freqs: the frequency vector +# - bins: the centers of the time bins +# - im: the matplotlib.image.AxesImage instance representing the data in the plot plt.show() diff --git a/examples/images_contours_and_fields/tricontour_demo.py b/examples/images_contours_and_fields/tricontour_demo.py index 47f8f74411ed..130ddfb02bcb 100644 --- a/examples/images_contours_and_fields/tricontour_demo.py +++ b/examples/images_contours_and_fields/tricontour_demo.py @@ -38,12 +38,12 @@ ############################################################################### # pcolor plot. -plt.figure() -plt.gca().set_aspect('equal') -plt.tricontourf(triang, z) -plt.colorbar() -plt.tricontour(triang, z, colors='k') -plt.title('Contour plot of Delaunay triangulation') +fig1, ax1 = plt.subplots() +ax1.set_aspect('equal') +tcf = ax1.tricontourf(triang, z) +fig1.colorbar(tcf) +ax1.tricontour(triang, z, colors='k') +ax1.set_title('Contour plot of Delaunay triangulation') ############################################################################### # You can specify your own triangulation rather than perform a Delaunay @@ -101,12 +101,12 @@ # object if the same triangulation was to be used more than once to save # duplicated calculations. -plt.figure() -plt.gca().set_aspect('equal') -plt.tricontourf(x, y, triangles, z) -plt.colorbar() -plt.title('Contour plot of user-specified triangulation') -plt.xlabel('Longitude (degrees)') -plt.ylabel('Latitude (degrees)') +fig2, ax2 = plt.subplots() +ax2.set_aspect('equal') +tcf = ax2.tricontourf(x, y, triangles, z) +fig2.colorbar(tcf) +ax2.set_title('Contour plot of user-specified triangulation') +ax2.set_xlabel('Longitude (degrees)') +ax2.set_ylabel('Latitude (degrees)') plt.show() diff --git a/examples/images_contours_and_fields/tricontour_smooth_delaunay.py b/examples/images_contours_and_fields/tricontour_smooth_delaunay.py index 5aa3560b9548..0af199b2fc68 100644 --- a/examples/images_contours_and_fields/tricontour_smooth_delaunay.py +++ b/examples/images_contours_and_fields/tricontour_smooth_delaunay.py @@ -114,26 +114,26 @@ def experiment_res(x, y): levels = np.arange(0., 1., 0.025) cmap = cm.get_cmap(name='Blues', lut=None) -plt.figure() -plt.gca().set_aspect('equal') -plt.title("Filtering a Delaunay mesh\n" + +fig, ax = plt.subplots() +ax.set_aspect('equal') +ax.set_title("Filtering a Delaunay mesh\n" + "(application to high-resolution tricontouring)") # 1) plot of the refined (computed) data contours: -plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, +ax.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, linewidths=[2.0, 0.5, 1.0, 0.5]) # 2) plot of the expected (analytical) data contours (dashed): if plot_expected: - plt.tricontour(tri_refi, z_expected, levels=levels, cmap=cmap, + ax.tricontour(tri_refi, z_expected, levels=levels, cmap=cmap, linestyles='--') # 3) plot of the fine mesh on which interpolation was done: if plot_refi_tri: - plt.triplot(tri_refi, color='0.97') + ax.triplot(tri_refi, color='0.97') # 4) plot of the initial 'coarse' mesh: if plot_tri: - plt.triplot(tri, color='0.7') + ax.triplot(tri, color='0.7') # 4) plot of the unvalidated triangles from naive Delaunay Triangulation: if plot_masked_tri: - plt.triplot(flat_tri, color='red') + ax.triplot(flat_tri, color='red') plt.show() diff --git a/examples/images_contours_and_fields/tricontour_smooth_user.py b/examples/images_contours_and_fields/tricontour_smooth_user.py index b51bcb0596cd..42b235d5543a 100644 --- a/examples/images_contours_and_fields/tricontour_smooth_user.py +++ b/examples/images_contours_and_fields/tricontour_smooth_user.py @@ -62,17 +62,17 @@ def function_z(x, y): #----------------------------------------------------------------------------- # Plot the triangulation and the high-res iso-contours #----------------------------------------------------------------------------- -plt.figure() -plt.gca().set_aspect('equal') -plt.triplot(triang, lw=0.5, color='white') +fig, ax = plt.subplots() +ax.set_aspect('equal') +ax.triplot(triang, lw=0.5, color='white') levels = np.arange(0., 1., 0.025) cmap = cm.get_cmap(name='terrain', lut=None) -plt.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap) -plt.tricontour(tri_refi, z_test_refi, levels=levels, +ax.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap) +ax.tricontour(tri_refi, z_test_refi, levels=levels, colors=['0.25', '0.5', '0.5', '0.5', '0.5'], linewidths=[1.0, 0.5, 0.5, 0.5, 0.5]) -plt.title("High-resolution tricontouring") +ax.set_title("High-resolution tricontouring") plt.show() diff --git a/examples/images_contours_and_fields/triinterp_demo.py b/examples/images_contours_and_fields/triinterp_demo.py index 9f8dacf0520f..650a4b621fe1 100644 --- a/examples/images_contours_and_fields/triinterp_demo.py +++ b/examples/images_contours_and_fields/triinterp_demo.py @@ -29,33 +29,32 @@ interp_cubic_min_E = mtri.CubicTriInterpolator(triang, z, kind='min_E') zi_cubic_min_E = interp_cubic_min_E(xi, yi) +# Set up the figure +fig, axs = plt.subplots(nrows=2, ncols=2) +axs = axs.flatten() # Plot the triangulation. -plt.subplot(221) -plt.tricontourf(triang, z) -plt.triplot(triang, 'ko-') -plt.title('Triangular grid') +axs[0].tricontourf(triang, z) +axs[0].triplot(triang, 'ko-') +axs[0].set_title('Triangular grid') # Plot linear interpolation to quad grid. -plt.subplot(222) -plt.contourf(xi, yi, zi_lin) -plt.plot(xi, yi, 'k-', lw=0.5, alpha=0.5) -plt.plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5) -plt.title("Linear interpolation") +axs[1].contourf(xi, yi, zi_lin) +axs[1].plot(xi, yi, 'k-', lw=0.5, alpha=0.5) +axs[1].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5) +axs[1].set_title("Linear interpolation") # Plot cubic interpolation to quad grid, kind=geom -plt.subplot(223) -plt.contourf(xi, yi, zi_cubic_geom) -plt.plot(xi, yi, 'k-', lw=0.5, alpha=0.5) -plt.plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5) -plt.title("Cubic interpolation,\nkind='geom'") +axs[2].contourf(xi, yi, zi_cubic_geom) +axs[2].plot(xi, yi, 'k-', lw=0.5, alpha=0.5) +axs[2].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5) +axs[2].set_title("Cubic interpolation,\nkind='geom'") # Plot cubic interpolation to quad grid, kind=min_E -plt.subplot(224) -plt.contourf(xi, yi, zi_cubic_min_E) -plt.plot(xi, yi, 'k-', lw=0.5, alpha=0.5) -plt.plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5) -plt.title("Cubic interpolation,\nkind='min_E'") +axs[3].contourf(xi, yi, zi_cubic_min_E) +axs[3].plot(xi, yi, 'k-', lw=0.5, alpha=0.5) +axs[3].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5) +axs[3].set_title("Cubic interpolation,\nkind='min_E'") -plt.tight_layout() +fig.tight_layout() plt.show() diff --git a/examples/images_contours_and_fields/tripcolor_demo.py b/examples/images_contours_and_fields/tripcolor_demo.py index 8c885744895d..877d434ae1e1 100644 --- a/examples/images_contours_and_fields/tripcolor_demo.py +++ b/examples/images_contours_and_fields/tripcolor_demo.py @@ -38,20 +38,20 @@ ############################################################################### # tripcolor plot. -plt.figure() -plt.gca().set_aspect('equal') -plt.tripcolor(triang, z, shading='flat') -plt.colorbar() -plt.title('tripcolor of Delaunay triangulation, flat shading') +fig1, ax1 = plt.subplots() +ax1.set_aspect('equal') +tpc = ax1.tripcolor(triang, z, shading='flat') +fig1.colorbar(tpc) +ax1.set_title('tripcolor of Delaunay triangulation, flat shading') ############################################################################### # Illustrate Gouraud shading. -plt.figure() -plt.gca().set_aspect('equal') -plt.tripcolor(triang, z, shading='gouraud') -plt.colorbar() -plt.title('tripcolor of Delaunay triangulation, gouraud shading') +fig2, ax2 = plt.subplots() +ax2.set_aspect('equal') +tpc = ax2.tripcolor(triang, z, shading='gouraud') +fig2.colorbar(tpc) +ax2.set_title('tripcolor of Delaunay triangulation, gouraud shading') ############################################################################### @@ -115,12 +115,12 @@ # Can specify one color value per face rather than one per point by using the # facecolors kwarg. -plt.figure() -plt.gca().set_aspect('equal') -plt.tripcolor(x, y, triangles, facecolors=zfaces, edgecolors='k') -plt.colorbar() -plt.title('tripcolor of user-specified triangulation') -plt.xlabel('Longitude (degrees)') -plt.ylabel('Latitude (degrees)') +fig3, ax3 = plt.subplots() +ax3.set_aspect('equal') +tpc = ax3.tripcolor(x, y, triangles, facecolors=zfaces, edgecolors='k') +fig3.colorbar(tpc) +ax3.set_title('tripcolor of user-specified triangulation') +ax3.set_xlabel('Longitude (degrees)') +ax3.set_ylabel('Latitude (degrees)') plt.show() diff --git a/examples/images_contours_and_fields/triplot_demo.py b/examples/images_contours_and_fields/triplot_demo.py index d3a65762d021..0efc7011b4a8 100644 --- a/examples/images_contours_and_fields/triplot_demo.py +++ b/examples/images_contours_and_fields/triplot_demo.py @@ -37,10 +37,10 @@ ############################################################################### # Plot the triangulation. -plt.figure() -plt.gca().set_aspect('equal') -plt.triplot(triang, 'bo-', lw=1) -plt.title('triplot of Delaunay triangulation') +fig1, ax1 = plt.subplots() +ax1.set_aspect('equal') +ax1.triplot(triang, 'bo-', lw=1) +ax1.set_title('triplot of Delaunay triangulation') ############################################################################### @@ -96,11 +96,11 @@ # if the same triangulation was to be used more than once to save duplicated # calculations. -plt.figure() -plt.gca().set_aspect('equal') -plt.triplot(x, y, triangles, 'go-', lw=1.0) -plt.title('triplot of user-specified triangulation') -plt.xlabel('Longitude (degrees)') -plt.ylabel('Latitude (degrees)') +fig2, ax2 = plt.subplots() +ax2.set_aspect('equal') +ax2.triplot(x, y, triangles, 'go-', lw=1.0) +ax2.set_title('triplot of user-specified triangulation') +ax2.set_xlabel('Longitude (degrees)') +ax2.set_ylabel('Latitude (degrees)') plt.show() diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 9979bc543036..7a27b77f7b15 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -53,7 +53,7 @@ def _process_plot_format(fmt): .. seealso:: :func:`~matplotlib.Line2D.lineStyles` and - :func:`~matplotlib.pyplot.colors` + :attr:`~matplotlib.colors.cnames` for all possible styles and color format string. """