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

Skip to content

DOC: use OO-ish interface in image, contour, field examples #10865

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 10 additions & 14 deletions examples/images_contours_and_fields/barb_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand All @@ -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()
8 changes: 4 additions & 4 deletions examples/images_contours_and_fields/barcode_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
14 changes: 7 additions & 7 deletions examples/images_contours_and_fields/contour_corner_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
68 changes: 31 additions & 37 deletions examples/images_contours_and_fields/contour_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,96 +30,90 @@
# 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')


###############################################################################
# contour labels can be placed manually by providing list of positions
# (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()
58 changes: 22 additions & 36 deletions examples/images_contours_and_fields/contour_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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.
Expand All @@ -64,44 +62,32 @@
# 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.
# Note that the contour lines don't extend to the edge of the box.
# 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()
32 changes: 17 additions & 15 deletions examples/images_contours_and_fields/contour_label_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

See also contour_demo.py.
"""

import matplotlib
import numpy as np
import matplotlib.cm as cm
Expand All @@ -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__(),)
Expand All @@ -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]

Expand All @@ -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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not reuse CS?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thought (which is behind e.g., fig1, ax1 as well) is that I want it to be completely clear to a totally "n00b" (to programming, python, or matplotlib) that we're starting over and working on something new.


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()
Loading