Matplotlib Plot All Images with Dynamic Row (Grid)

September 13, 2020
import pathlib

from IPython.display import Image
import matplotlib.pyplot as plt

output_dir = pathlib.Path("/content/output/")
images = list(output_dir.glob('*.jpg'))

Usually I predefined the col and row, assumeing 3x3, thus it cannot show more than 9 images.

# set the canvas size in inches
plt.figure(figsize=(10,10))

for i, img_path in enumerate(images):
  if i >= 9:
    break

  img_path = str(img_path)
  # the number of images in the grid is 3*3 (9)
  plt.subplot(3,3,i+1)    
  img = plt.imread(img_path)
  plt.imshow(img)
  plt.title(Path(img_path).name)
  plt.axis("off")

plt.show()
plt.close()

What if I want to plot all the images? I assume then we would need to know the total number of images.

NOTE: I am still pretty new with matplotlib, so I am not sure is there a dynamic ways to do this if the total number of images or row is not known in advance.

import math

col = 3
image_count = len(images)
row = math.ceil(image_count/col)
plt.figure(figsize=(col*4,row*4))

for i, img_path in enumerate(images):
    img_path = str(img_path)
    
    img = plt.imread(img_path)

    plt.subplot(row, col, i + 1)
    plt.imshow(img)
    plt.title(pathlib.Path(img_path).name)
    plt.axis("off")

plt.show()
plt.close()
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.