Issues removing vertical white spaces between rows of images in matplotlib

Viewed 116

I am displaying images from a 2D array with pyplot and have removed axis markings and padding. However, between rows of images, there is still whitespace which I would like to remove. The images themselves have no whitespace.

fig = plt.figure(figsize=(10, 10))

for x in range(quads_x):
    for y in range(quads_y):
        # ADD IMAGES
        fig.add_subplot(quads_y, quads_x, (quads_x * x) + y + 1)
        plt.imshow(cv2.imread("./map/" + winning_maps[x][y], 0))

        # PYPLOT FORMATTING
        plt.subplots_adjust(wspace=0, hspace=0)
        ax = plt.gca()
        ax.axis("off")
        ax.xaxis.set_major_locator(matplotlib.ticker.NullLocator())
        ax.yaxis.set_major_locator(matplotlib.ticker.NullLocator())

The code yields something like

this

Any ideas on how I should deal with the issue?

1 Answers

Normally using plt.subplots_adjust(wspace=0, hspace=0) would collapse all of the axes onto each other. The issue you are running into is that using imshow fixes the aspect ratio of the axes in the plot.

To compensate, you need to adjust the size of your canvas so that the frame has the same ratio as the images you are showing. The next issue is that the border padding around the axes is a ratio of the size of the image. If you are ok with it, you can remove the border, drop in the images, then adjust the height of the canvas to be the figure height times the ratio of the images times the number of rows of images divided by the number of columns of images.

Here is an example:

from matplotlib import pyplot as plt
from PIL import Image

img = Image.open('fox.jpg').resize(80,50)

fig, axes = plt.subplots(rows, columns, figsize=(7,7))
for ax in axes.ravel():
    ax.imshow(img)
    ax.set_autoscale_on(False)
    ax.axis('off')
plt.subplots_adjust(hspace=0, wspace=0, left=0, bottom=0, right=1, top=1)
r, c = axes.shape
fig.set_figheight(fig.get_figwidth() * ax.get_data_ratio() * r / c )
plt.show()

Here is the image before using set_figheight:

enter image description here

And here it is with the adjustment:

enter image description here

Related