Issue
I need to display 20 images in grid, and my code as follows
def plot_matric_demo(img, nrows, ncols):
fig, ax = plt.subplots(nrows=nrows, ncols=ncols)
cur_index = 0
for row in ax:
for col in row:
col.imshow(img)
cur_index = cur_index + 1
col.axis('off')
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
plt.show()
subplot_img = cv2.imread("subplots.png")
plot_matric_demo(subplot_img, 5, 4)
It seems that the images in the subplots were too small, meanwhile the distance were large, I was wondering how could I make the images in the subplots larger?
Solution
TL;DR use plt.subplots(nrows=nr, ncols=nc, figsize=(..., ...))
to adjust the figure size so that the individual subplot has, at least approximately, the same aspect ratio of the images that are to be shown.
The key point is, imshow
will use square pixels, so if your image has a 1:2 aspect ratio, the images as plotted will have a 1:2 aspect ratio and each one will stand in the middle of its own subplot — if the aspect ratio of the subplot is different from the aspect ratio of the image you will experience the "large white border syndrome".
Lets start with the imports and a fake image, with a 1:2 aspect ratio
In [1]: import numpy as np
...: import matplotlib.pyplot as plt
In [2]: img = np.arange(54*108).reshape(108,54)
and replicate your arrangement, in which you subdivided a 8x6 (x:y) figure in 4x5 (x:y) subplots — you have subplots that are horizontally wide (8/4=2) and vertically short (6/5=1.2) and each image, when centered in its subplot, has a WIDE horizontal margin.
In [3]: f, axs = plt.subplots(5, 4)
...: for x in axs.flatten():
...: x.imshow(img) ; x.axis('off')
Now revert the role of row and columns, now your subplots are smaller in horizontal (8/5=1.6) and taller (6/4=1.5), the placement of images is decidedly better due to decreased horizontal white margins and the increase in the image size, because the available height is greater
In [4]: f, axs = plt.subplots(4, 5)
...: for x in axs.flatten():
...: x.imshow(img) ; x.axis('off')
To end the story, what is key is to have subplots that have (at least approximately) the same aspect ratio as the images that you use, and with this aim we have to intervene on the figsize
parameter, assigning a width:height that is equal to (ncols×1):(nrows×2), in my example below figsize=(5,8)
In [5]: f, axs = plt.subplots(4, 5, figsize=(5,8))
...: for x in axs.flatten():
...: x.imshow(img) ; x.axis('off')
Answered By - gboffi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.