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

Skip to content

Commit ec5e886

Browse files
committed
DOC: use OO-ish interface in img/contour examples
1 parent dbfc79c commit ec5e886

24 files changed

+242
-273
lines changed

examples/images_contours_and_fields/barb_demo.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,26 +22,23 @@
2222
data = np.array(data, dtype=[('x', np.float32), ('y', np.float32),
2323
('u', np.float32), ('v', np.float32)])
2424

25+
fig1, axs1 = plt.subplots(nrows=2, ncols=2)
2526
# Default parameters, uniform grid
26-
ax = plt.subplot(2, 2, 1)
27-
ax.barbs(X, Y, U, V)
27+
axs1[0, 0].barbs(X, Y, U, V)
2828

2929
# Arbitrary set of vectors, make them longer and change the pivot point
3030
# (point around which they're rotated) to be the middle
31-
ax = plt.subplot(2, 2, 2)
32-
ax.barbs(data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle')
31+
axs1[0, 1].barbs(data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle')
3332

3433
# Showing colormapping with uniform grid. Fill the circle for an empty barb,
3534
# don't round the values, and change some of the size parameters
36-
ax = plt.subplot(2, 2, 3)
37-
ax.barbs(X, Y, U, V, np.sqrt(U * U + V * V), fill_empty=True, rounding=False,
38-
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
35+
axs1[1, 0].barbs(X, Y, U, V, np.sqrt(U * U + V * V), fill_empty=True, rounding=False,
36+
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
3937

4038
# Change colors as well as the increments for parts of the barbs
41-
ax = plt.subplot(2, 2, 4)
42-
ax.barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r',
43-
barbcolor=['b', 'g'],
44-
barb_increments=dict(half=10, full=20, flag=100), flip_barb=True)
39+
axs1[1, 1].barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r',
40+
barbcolor=['b', 'g'], flip_barb=True,
41+
barb_increments=dict(half=10, full=20, flag=100))
4542

4643
# Masked arrays are also supported
4744
masked_u = np.ma.masked_array(data['u'])
@@ -50,8 +47,7 @@
5047

5148
# Identical plot to panel 2 in the first figure, but with the point at
5249
# (0.5, 0.25) missing (masked)
53-
fig2 = plt.figure()
54-
ax = fig2.add_subplot(1, 1, 1)
55-
ax.barbs(data['x'], data['y'], masked_u, data['v'], length=8, pivot='middle')
50+
fig2, ax2 = plt.subplots()
51+
ax2.barbs(data['x'], data['y'], masked_u, data['v'], length=8, pivot='middle')
5652

5753
plt.show()

examples/images_contours_and_fields/barcode_demo.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@
2020
fig = plt.figure()
2121

2222
# a vertical barcode -- this is broken at present
23-
ax = fig.add_axes([0.1, 0.3, 0.1, 0.6], **axprops)
24-
ax.imshow(x.reshape((-1, 1)), **barprops)
23+
ax1 = fig.add_axes([0.1, 0.3, 0.1, 0.6], **axprops)
24+
ax1.imshow(x.reshape((-1, 1)), **barprops)
2525

2626
# a horizontal barcode
27-
ax = fig.add_axes([0.3, 0.1, 0.6, 0.1], **axprops)
28-
ax.imshow(x.reshape((1, -1)), **barprops)
27+
ax2 = fig.add_axes([0.3, 0.1, 0.6, 0.1], **axprops)
28+
ax2.imshow(x.reshape((1, -1)), **barprops)
2929

3030

3131
plt.show()

examples/images_contours_and_fields/contour_corner_mask.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,16 @@
2323
z = np.ma.array(z, mask=mask)
2424

2525
corner_masks = [False, True]
26-
for i, corner_mask in enumerate(corner_masks):
27-
plt.subplot(1, 2, i + 1)
28-
cs = plt.contourf(x, y, z, corner_mask=corner_mask)
29-
plt.contour(cs, colors='k')
30-
plt.title('corner_mask = {0}'.format(corner_mask))
26+
fig, axs = plt.subplots(ncols=2)
27+
for ax, corner_mask in zip(axs, corner_masks):
28+
cs = ax.contourf(x, y, z, corner_mask=corner_mask)
29+
ax.contour(cs, colors='k')
30+
ax.set_title('corner_mask = {0}'.format(corner_mask))
3131

3232
# Plot grid.
33-
plt.grid(c='k', ls='-', alpha=0.3)
33+
ax.grid(c='k', ls='-', alpha=0.3)
3434

3535
# Indicate masked points with red circles.
36-
plt.plot(np.ma.array(x, mask=~mask), y, 'ro')
36+
ax.plot(np.ma.array(x, mask=~mask), y, 'ro')
3737

3838
plt.show()

examples/images_contours_and_fields/contour_demo.py

Lines changed: 31 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -30,96 +30,90 @@
3030
# over the line segments of the contour, removing the lines beneath
3131
# the label
3232

33-
plt.figure()
34-
CS = plt.contour(X, Y, Z)
35-
plt.clabel(CS, inline=1, fontsize=10)
36-
plt.title('Simplest default with labels')
33+
fig, ax = plt.subplots()
34+
CS = ax.contour(X, Y, Z)
35+
ax.clabel(CS, inline=1, fontsize=10)
36+
ax.set_title('Simplest default with labels')
3737

3838

3939
###############################################################################
4040
# contour labels can be placed manually by providing list of positions
4141
# (in data coordinate). See ginput_manual_clabel.py for interactive
4242
# placement.
4343

44-
plt.figure()
45-
CS = plt.contour(X, Y, Z)
44+
fig, ax = plt.subplots()
45+
CS = ax.contour(X, Y, Z)
4646
manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)]
47-
plt.clabel(CS, inline=1, fontsize=10, manual=manual_locations)
48-
plt.title('labels at selected locations')
47+
ax.clabel(CS, inline=1, fontsize=10, manual=manual_locations)
48+
ax.set_title('labels at selected locations')
4949

5050

5151
###############################################################################
5252
# You can force all the contours to be the same color.
5353

54-
plt.figure()
55-
CS = plt.contour(X, Y, Z, 6,
54+
fig, ax = plt.subplots()
55+
CS = ax.contour(X, Y, Z, 6,
5656
colors='k', # negative contours will be dashed by default
5757
)
58-
plt.clabel(CS, fontsize=9, inline=1)
59-
plt.title('Single color - negative contours dashed')
58+
ax.clabel(CS, fontsize=9, inline=1)
59+
ax.set_title('Single color - negative contours dashed')
6060

6161
###############################################################################
6262
# You can set negative contours to be solid instead of dashed:
6363

6464
matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
65-
plt.figure()
66-
CS = plt.contour(X, Y, Z, 6,
65+
fig, ax = plt.subplots()
66+
CS = ax.contour(X, Y, Z, 6,
6767
colors='k', # negative contours will be dashed by default
6868
)
69-
plt.clabel(CS, fontsize=9, inline=1)
70-
plt.title('Single color - negative contours solid')
69+
ax.clabel(CS, fontsize=9, inline=1)
70+
ax.set_title('Single color - negative contours solid')
7171

7272

7373
###############################################################################
7474
# And you can manually specify the colors of the contour
7575

76-
plt.figure()
77-
CS = plt.contour(X, Y, Z, 6,
76+
fig, ax = plt.subplots()
77+
CS = ax.contour(X, Y, Z, 6,
7878
linewidths=np.arange(.5, 4, .5),
7979
colors=('r', 'green', 'blue', (1, 1, 0), '#afeeee', '0.5')
8080
)
81-
plt.clabel(CS, fontsize=9, inline=1)
82-
plt.title('Crazy lines')
81+
ax.clabel(CS, fontsize=9, inline=1)
82+
ax.set_title('Crazy lines')
8383

8484

8585
###############################################################################
8686
# Or you can use a colormap to specify the colors; the default
8787
# colormap will be used for the contour lines
8888

89-
plt.figure()
90-
im = plt.imshow(Z, interpolation='bilinear', origin='lower',
89+
fig, ax = plt.subplots()
90+
im = ax.imshow(Z, interpolation='bilinear', origin='lower',
9191
cmap=cm.gray, extent=(-3, 3, -2, 2))
9292
levels = np.arange(-1.2, 1.6, 0.2)
93-
CS = plt.contour(Z, levels,
94-
origin='lower',
95-
linewidths=2,
96-
extent=(-3, 3, -2, 2))
93+
CS = ax.contour(Z, levels, origin='lower', cmap='flag',
94+
linewidths=2, extent=(-3, 3, -2, 2))
9795

9896
# Thicken the zero contour.
9997
zc = CS.collections[6]
10098
plt.setp(zc, linewidth=4)
10199

102-
plt.clabel(CS, levels[1::2], # label every second level
103-
inline=1,
104-
fmt='%1.1f',
105-
fontsize=14)
100+
ax.clabel(CS, levels[1::2], # label every second level
101+
inline=1, fmt='%1.1f',
102+
cmap='flag', fontsize=14)
106103

107104
# make a colorbar for the contour lines
108-
CB = plt.colorbar(CS, shrink=0.8, extend='both')
105+
CB = fig.colorbar(CS, shrink=0.8, extend='both')
109106

110-
plt.title('Lines with colorbar')
111-
#plt.hot() # Now change the colormap for the contour lines and colorbar
112-
plt.flag()
107+
ax.set_title('Lines with colorbar')
113108

114109
# We can still add a colorbar for the image, too.
115-
CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8)
110+
CBI = fig.colorbar(im, orientation='horizontal', shrink=0.8)
116111

117112
# This makes the original colorbar look a bit out of place,
118113
# so let's improve its position.
119114

120-
l, b, w, h = plt.gca().get_position().bounds
115+
l, b, w, h = ax.get_position().bounds
121116
ll, bb, ww, hh = CB.ax.get_position().bounds
122117
CB.ax.set_position([ll, b + 0.1*h, ww, h*0.8])
123118

124-
125119
plt.show()

examples/images_contours_and_fields/contour_image.py

Lines changed: 22 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,12 @@
3434
norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max())
3535
cmap = cm.PRGn
3636

37-
fig = plt.figure()
37+
fig, _axs = plt.subplots(nrows=2, ncols=2)
3838
fig.subplots_adjust(hspace=0.3)
39+
axs = _axs.flatten()
3940

40-
41-
plt.subplot(2, 2, 1)
42-
43-
cset1 = plt.contourf(X, Y, Z, levels,
44-
cmap=cm.get_cmap(cmap, len(levels) - 1), norm=norm)
41+
cset1 = axs[0].contourf(X, Y, Z, levels, norm=norm,
42+
cmap=cm.get_cmap(cmap, len(levels) - 1))
4543
# It is not necessary, but for the colormap, we need only the
4644
# number of levels minus 1. To avoid discretization error, use
4745
# either this number or a large number such as the default (256).
@@ -51,7 +49,7 @@
5149
# of the polygons in the collections returned by contourf.
5250
# Use levels output from previous call to guarantee they are the same.
5351

54-
cset2 = plt.contour(X, Y, Z, cset1.levels, colors='k')
52+
cset2 = axs[0].contour(X, Y, Z, cset1.levels, colors='k')
5553

5654
# We don't really need dashed contour lines to indicate negative
5755
# regions, so let's turn them off.
@@ -64,44 +62,32 @@
6462
# We are making a thick green line as a zero contour.
6563
# Specify the zero level as a tuple with only 0 in it.
6664

67-
cset3 = plt.contour(X, Y, Z, (0,), colors='g', linewidths=2)
68-
plt.title('Filled contours')
69-
plt.colorbar(cset1)
70-
65+
cset3 = axs[0].contour(X, Y, Z, (0,), colors='g', linewidths=2)
66+
axs[0].set_title('Filled contours')
67+
fig.colorbar(cset1, ax=axs[0])
7168

72-
plt.subplot(2, 2, 2)
7369

74-
plt.imshow(Z, extent=extent, cmap=cmap, norm=norm)
75-
v = plt.axis()
76-
plt.contour(Z, levels, colors='k', origin='upper', extent=extent)
77-
plt.axis(v)
78-
plt.title("Image, origin 'upper'")
70+
axs[1].imshow(Z, extent=extent, cmap=cmap, norm=norm)
71+
axs[1].contour(Z, levels, colors='k', origin='upper', extent=extent)
72+
axs[1].set_title("Image, origin 'upper'")
7973

80-
plt.subplot(2, 2, 3)
81-
82-
plt.imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm)
83-
v = plt.axis()
84-
plt.contour(Z, levels, colors='k', origin='lower', extent=extent)
85-
plt.axis(v)
86-
plt.title("Image, origin 'lower'")
87-
88-
plt.subplot(2, 2, 4)
74+
axs[2].imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm)
75+
axs[2].contour(Z, levels, colors='k', origin='lower', extent=extent)
76+
axs[2].set_title("Image, origin 'lower'")
8977

9078
# We will use the interpolation "nearest" here to show the actual
9179
# image pixels.
9280
# Note that the contour lines don't extend to the edge of the box.
9381
# This is intentional. The Z values are defined at the center of each
9482
# image pixel (each color block on the following subplot), so the
9583
# domain that is contoured does not extend beyond these pixel centers.
96-
im = plt.imshow(Z, interpolation='nearest', extent=extent,
84+
im = axs[3].imshow(Z, interpolation='nearest', extent=extent,
9785
cmap=cmap, norm=norm)
98-
v = plt.axis()
99-
plt.contour(Z, levels, colors='k', origin='image', extent=extent)
100-
plt.axis(v)
101-
ylim = plt.get(plt.gca(), 'ylim')
102-
plt.setp(plt.gca(), ylim=ylim[::-1])
103-
plt.title("Origin from rc, reversed y-axis")
104-
plt.colorbar(im)
105-
106-
plt.tight_layout()
86+
axs[3].contour(Z, levels, colors='k', origin='image', extent=extent)
87+
ylim = axs[3].get_ylim()
88+
axs[3].set_ylim(ylim[::-1])
89+
axs[3].set_title("Origin from rc, reversed y-axis")
90+
fig.colorbar(im, ax=axs[3])
91+
92+
fig.tight_layout()
10793
plt.show()

examples/images_contours_and_fields/contour_label_demo.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
99
See also contour_demo.py.
1010
"""
11+
1112
import matplotlib
1213
import numpy as np
1314
import matplotlib.cm as cm
@@ -32,14 +33,10 @@
3233
# Make contour labels using creative float classes
3334
# Follows suggestion of Manuel Metz
3435

35-
plt.figure()
36-
37-
# Basic contour plot
38-
CS = plt.contour(X, Y, Z)
39-
40-
4136
# Define a class that forces representation of float to look a certain way
4237
# This remove trailing zero so '1.0' becomes '1'
38+
39+
4340
class nf(float):
4441
def __repr__(self):
4542
str = '%.1f' % (self.__float__(),)
@@ -49,6 +46,10 @@ def __repr__(self):
4946
return '%.1f' % self.__float__()
5047

5148

49+
# Basic contour plot
50+
fig, ax = plt.subplots()
51+
CS = ax.contour(X, Y, Z)
52+
5253
# Recast levels to new class
5354
CS.levels = [nf(val) for val in CS.levels]
5455

@@ -57,33 +58,34 @@ def __repr__(self):
5758
fmt = r'%r \%%'
5859
else:
5960
fmt = '%r %%'
60-
plt.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10)
61+
62+
ax.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10)
6163

6264
###############################################################################
6365
# Label contours with arbitrary strings using a dictionary
6466

65-
plt.figure()
67+
fig1, ax1 = plt.subplots()
6668

6769
# Basic contour plot
68-
CS = plt.contour(X, Y, Z)
70+
CS1 = ax1.contour(X, Y, Z)
6971

7072
fmt = {}
7173
strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']
72-
for l, s in zip(CS.levels, strs):
74+
for l, s in zip(CS1.levels, strs):
7375
fmt[l] = s
7476

7577
# Label every other level using strings
76-
plt.clabel(CS, CS.levels[::2], inline=True, fmt=fmt, fontsize=10)
78+
ax1.clabel(CS1, CS1.levels[::2], inline=True, fmt=fmt, fontsize=10)
7779

7880
###############################################################################
7981
# Use a Formatter
8082

81-
plt.figure()
83+
fig2, ax2 = plt.subplots()
8284

83-
CS = plt.contour(X, Y, 100**Z, locator=plt.LogLocator())
85+
CS2 = ax2.contour(X, Y, 100**Z, locator=plt.LogLocator())
8486
fmt = ticker.LogFormatterMathtext()
8587
fmt.create_dummy_axis()
86-
plt.clabel(CS, CS.levels, fmt=fmt)
87-
plt.title("$100^Z$")
88+
ax2.clabel(CS2, CS2.levels, fmt=fmt)
89+
ax2.set_title("$100^Z$")
8890

8991
plt.show()

0 commit comments

Comments
 (0)