问题
I want to show images var_1.png,...,var_40.png in a 2x3 matrix format inside a Jupyter Notebook.
However, I only manage to do it manually:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
img1=mpimg.imread('Variable_8.png')
img2=mpimg.imread('Variable_17.png')
img3=mpimg.imread('Variable_18.png')
...
fig, ((ax1, ax2, ax3), (ax4,ax5,ax6)) = plt.subplots(2, 3, sharex=True, sharey=True)
ax1.imshow(img1)
ax1.axis('off')
ax2.imshow(img2)
ax2.axis('off')
....
I want something cleaner. Something like a list comprehension that specifies
image=[img(i)=mpimg.imread('Variable_(i).png') for i in [8,17,28, ..]
[ax[j].imshow(img(j)),ax[j].axis('off') for j in range(len(image))]
Some help?
回答1:
List comprehensions quickly become unreadable if there is more than one thing they do. Also it appears it is considered bad style to use list comprehensions if the content of the list is not actually used at all.
Hence I would propose the following
import matplotlib.pyplot as plt
images = [plt.imread(f"Variable_{i}.png") for i in [8,17,28,29,31,35]]
fig, axes = plt.subplots(2, 3, sharex=True, sharey=True)
for img, ax in zip(images, axes.flat):
ax.imshow(img)
ax.axis('off')
回答2:
What about:
imgs_names = ...
imgs = [mpimg.imread(name) for name in imgs_names]
n_rows = 2
n_cols = 3
fig, axes = subplots(n_rows, n_cols)
[(axes[i][j].imshow(imgs[i*n_cols + j]), axes[i][j].axis('off')) for i in range(n_rows) for j in range(n_cols)]
?
Rmk: this does not work if n_cols=1 or n_rows=1, because axes is then a list, not an array.
来源:https://stackoverflow.com/questions/55981650/grid-of-images-using-a-loop-in-jupyter-notebook-how