Skip to content

Instantly share code, notes, and snippets.

@RonKG
Forked from soply/disp_multiple_images.py
Created October 29, 2017 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RonKG/1cc36c68bae12f043b981884d3c1bb3a to your computer and use it in GitHub Desktop.
Save RonKG/1cc36c68bae12f043b981884d3c1bb3a to your computer and use it in GitHub Desktop.
Plot multiple images with matplotlib in a single figure. Titles can be given optionally as second argument.
import matplotlib.pyplot as plt
import numpy as np
def show_images(images, cols = 1, titles = None):
"""Display a list of images in a single figure with matplotlib.
Parameters
---------
images: List of np.arrays compatible with plt.imshow.
cols (Default = 1): Number of columns in figure (number of rows is
set to np.ceil(n_images/float(cols))).
titles: List of titles corresponding to each image. Must have
the same length as titles.
"""
assert((titles is None)or (len(images) == len(titles)))
n_images = len(images)
if titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)]
fig = plt.figure()
for n, (image, title) in enumerate(zip(images, titles)):
a = fig.add_subplot(cols, np.ceil(n_images/float(cols)), n + 1)
if image.ndim == 2:
plt.gray()
plt.imshow(image)
a.set_title(title)
fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment