简体   繁体   中英

How to plot images in subplots

Suppose I have 3 directories of.jpg files: dataset 1, dataset 2, dataset 3.

I would like to make a 5 by 3 subplots using matplotlib. For each row, the subplot shows the data from dataset 1, dataset 2 and dataset 3 in order. The expected format is like this:

plot1, plot2, plot3,

plot4.......

plot13, plot14, plot15.

How should I do that?

something like this:

plt.figure(figsize=(10, 10)) 
for data1, data2, data3 in dataset1, dataset2, dataset3"
....
import matplotlib.pyplot as plt
from pathlib import Path

# create a list of directories
dirs = ['../Pictures/dataset1', '../Pictures/dataset2', '../Pictures/dataset3']

# extract the image paths into a list
files = [f for dir_ in dirs for f in list(Path(dir_).glob('*.jpg'))]

# create the figure
fig, axs = plt.subplots(nrows=5, ncols=3, figsize=(10, 10))

# flatten the axis into a 1-d array to make it easier to access each axes
axs = axs.flatten()

# iterate through and enumerate the files, use i to index the axes
for i, file in enumerate(files):
    
    # read the image in
    pic = plt.imread(file)

    # add the image to the axes
    axs[i].imshow(pic)

    # add an axes title; .stem is a pathlib method to get the filename
    axs[i].set(title=file.stem)

# add a figure title
fig.suptitle('Images from https://www.heroforge.com/', fontsize=18)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM