0

I want to plot images (in the 1st row) along with some diagrams (the 2nd and 3rd rows) using subplots from matplotlib.pyplot. However, imshow fucntion adds some additional white space around images I can't get rid of. Here is my code and the plot I'm getting:

rcParams['figure.figsize'] = (16, 14)
_, axes = plt.subplots(3, 3)

axes[0][0].imshow(image)
axes[0][0].set_title('title')
axes[0][0].set_xticklabels(list())
axes[0][0].set_yticklabels(list())
axes[0][0].grid(False)

axes[0][1].imshow(image)
axes[0][1].set_title('title')
axes[0][1].set_xticklabels(list())
axes[0][1].set_yticklabels(list())
axes[0][1].grid(False)

axes[0][2].imshow(image)
axes[0][2].set_title('title')
axes[0][2].set_xticklabels(list())
axes[0][2].set_yticklabels(list())
axes[0][2].grid(False)

plt.savefig(file_name, bbox_inches='tight')

in the plot below you can clearly see that there is significantly more space between the 1st and 2nd rows:

the plot I'm getting

I would like to have an equal space between all subplots. What would be the easiest way to do this?

Thanks in advance for any advice!

Best, Alexey

Alexey Abramov
  • 435
  • 1
  • 3
  • 16

1 Answers1

0

This is because imshow is showing the image with square pixels. If the image as a ratio of e.g. 16:9, the subplot will be reshaped to fit the image size. They will therefore have a different shape from the other subplots (see the imshow documentation for more info).

From here, you have two solutions:

  • decrease the figure height in order to reduce manually the vertical space between subplots
  • prevent imshow to resize the axes based on the images. For this you can set the aspect ratio to automatic aspect="auto", and the image will fit the existing axes
Leonard
  • 2,510
  • 18
  • 37
  • aspect="auto" leads to equal space but for the price of image distortion – Alexey Abramov Sep 28 '20 at 08:03
  • In this case, only the first solution works for you: if you try with `rcParams['figure.figsize'] = (16, 11)` for instance, is it better? (you need to play around with the figure height). – Leonard Sep 28 '20 at 08:04
  • yes, it is getting better, but I'm not completely happy with the result... it's very strange somehow, seems to be a very basic thing – Alexey Abramov Sep 28 '20 at 08:37