本文介绍了如何在子图中绘制图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有 3 个 .jpg 文件目录:数据集 1、数据集 2、数据集 3.
我想使用 matplotlib 制作一个 5 x 3 的子图.对于每一行,子图按顺序显示来自数据集 1、数据集 2 和数据集 3 的数据.预期的格式是这样的:
plot1、plot2、plot3、
plot4.......
plot13、plot14、plot15.
我该怎么做?
像这样:
plt.figure(figsize=(10, 10))对于数据集 1、数据集 2、数据集 3 中的数据 1、数据 2、数据 3";....
解决方案
- 此示例使用
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" ....
解决方案- This example uses
Path(...).glob()
frompathlib
to find all of the image paths in each directory, and unpack them in a list comprehension. matplotlib.pyplot.imread
andmatplotlib.pyplot.imshow
are used to read and show the images, respectively.
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)
这篇关于如何在子图中绘制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- This example uses