Matplotlib Plot All Images with Dynamic Row (Grid)

Sep 13, 2020
import pathlibfrom IPython.display import Imageimport matplotlib.pyplot as pltoutput_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 inchesplt.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 mathcol = 3image_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()

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.