Skip to content

Instantly share code, notes, and snippets.

@afvincent
Last active February 18, 2018 17:07
Show Gist options
  • Save afvincent/0e6b743e32a3fa62b580657693163b7e to your computer and use it in GitHub Desktop.
Save afvincent/0e6b743e32a3fa62b580657693163b7e to your computer and use it in GitHub Desktop.
Display slices of a picture
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec # only for Method 2
# A lot of information about GridSpec can be found here:
# https://matplotlib.org/tutorials/intermediate/gridspec.html
# Dummy data
uu = np.linspace(0, np.pi, 128)
data = np.cos(uu - 0.5) * np.cos(uu.reshape((-1, 1)) - 1.0)
# Figure with three axes of different width and height. Axis-sharing
# is used to make easier interactive exploration but could perfectly
# be removed if not needed.
#
# Method 1: pass GridSpec kwargs to the helper function plt.subplots
#fig, axs = plt.subplots(
# 2, 2, figsize=(6.4, 6.4), sharex='col', sharey='row',
# gridspec_kw={'height_ratios': [1, 3], 'width_ratios': [3, 1]})
#((axh, ax_), (ax0, axv)) = axs # mostly to have the same names with Method 2
#ax_.set_visible(False) # hide the useless (bottom right) Axes
#
# Method 2: set up a GridSpec grid and add the desired Axes one by one
fig = plt.figure(figsize=(6.4, 6.4))
gs = GridSpec(2, 2, height_ratios=[1, 3], width_ratios=[3, 1])
ax0 = fig.add_subplot(gs[1, 0])
axh = fig.add_subplot(gs[0, 0], sharex=ax0)
axv = fig.add_subplot(gs[1, 1], sharey=ax0)
# Where are the slices and how to display them
hslice_pos = data.shape[0] // 2 # vertical half of the picture
vslice_pos = 9 * data.shape[1] // 10 # horizontal 9/10 of the picture
hslice_opts = {'ls': '--', 'color': '0.25'}
vslice_opts = {'ls': '-.', 'color': '0.25'}
# Imshow global view. Some documentation about imshow:
# https://matplotlib.org/gallery/images_contours_and_fields/image_demo.html
im = ax0.imshow(data, origin='bottom', aspect='auto', cmap='coolwarm')
ax0.set_ylabel('Row Index (#)')
ax0.set_xlabel('Column Index (#)')
# Just to show where the slices are done. Another example in Matplotlib
# gallery about the relevant functions:
# https://matplotlib.org/gallery/subplots_axes_and_figures/axhspan_demo.html
ax0.axhline(hslice_pos, **hslice_opts)
ax0.axvline(vslice_pos, **vslice_opts)
# One can also annotate the slice markers. More information
# about `ax.annotate` here:
# https://matplotlib.org/tutorials/text/annotations.html
ax0.annotate('y = {}'.format(hslice_pos), xy=(10, hslice_pos + 3),
xycoords='data', color=hslice_opts['color'])
ax0.annotate('x = {}'.format(vslice_pos), xy=(vslice_pos - 6, 20),
xycoords='data', color=hslice_opts['color'], rotation='vertical')
# Horizontal Slice Profile
axh.set_xmargin(0) # otherwise ax0 may have white margins
axh.set_ylabel('Horizontal Slice (a.u.)')
axh.plot(range(data.shape[1]), data[hslice_pos], **hslice_opts)
axh.set_ylim(-1, 1)
axh.set_yticks([-1, 0, 1])
# NB: More examples of fancy customisation of ticks and formatters here:
# https://matplotlib.org/gallery/ticks_and_spines/tick-locators.html
# https://matplotlib.org/gallery/ticks_and_spines/tick-formatters.html
# Vertical Slice Profile
axv.set_ymargin(0) # otherwise ax0 may have white margins
axv.set_xlabel('Vertical Slice (a.u.)')
axv.plot(data[vslice_pos], range(data.shape[0]), **vslice_opts)
axv.set_xlim(-1, 1)
axv.set_xticks([-1, 0, 1])
# "Despine" the slice profiles and hide the relevant axis
for ax, spines in ((axh, ('top', 'bottom', 'right')),
(axv, ('top', 'left', 'right'))):
for sp in spines:
ax.spines[sp].set_visible(False)
axh.xaxis.set_visible(False)
axv.yaxis.set_visible(False)
# Tweak a bit the figure layout
fig.tight_layout()
fig.subplots_adjust(wspace=0.03, hspace=0.03)
fig.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment