Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

python - 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"
....
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...