Reputation: 2569
On the web, I have found similar issues but I have not figured out the solution yet.
The following code:
import numpy as np
import matplotlib.pyplot as plt
imgs = [np.random.randint(0, 256, size=(512, 512, 3)) for _ in range(3)]
_, axes = plt.subplots(1, 3)
title = plt.suptitle("My title")
axes[0].imshow(imgs[0])
axes[0].set_axis_off()
axes[1].imshow(imgs[1])
axes[1].set_axis_off()
axes[2].imshow(imgs[2])
axes[2].set_axis_off()
plt.savefig("myfig.png", bbox_inches="tight",
bbox_extra_artists=[title])
plt.close()
Gives me the following output:
How can I remove the extra space between the title and the images?
Upvotes: 2
Views: 2106
Reputation: 5913
The problem here is that your axes have a fixed aspect ratio, and your plot is taller than needed. There will be white space above and below your plot, which you try and get rid of with box_inches='tight'
.
A straightforward solution in Matplotlib is to make the aspect ratio of the figure close to the aspect ratio of the axes:
fig, axs = plt.subplots(1, 3, figsize(6, 2)
is close, and then you can play with the result after.
A second approach is to not use suptitle, which is generic, and instead use ax.text
directly, and use the transAxes
property of the axes to make the x and y be in fraction of the axes:
axes[1].text(0.5, 1.02, 'Boo!!!!!!', transform=axes[1].transAxes, ha='center')
Upvotes: 1