I'm creating a grid of images using plt.subplots.
How can I ensure that the title of one subplot doesn't extend beyond the width of the image beneath it?
In other words, is there a way to set the maximum size of the subplot title so that there is no possibility that it overlaps with an adjacent title?
If the title would extend beyond the image below, I want to decrease its font size so that it does not.
You could iteratively change the fontsize until the title width is smaller than the axes. I guess it makes sense to not make the title smaller than 1pt (even that isn't readable any more, so feel free to choose a different number). The below iterates in fontsize steps of 1pt; also this may be adapted.
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.plot([1,2])
ax1.set_title("Short title")
ax2.plot([2,1])
ax2.set_title("Loooooong title, which exceeds plot axes width.")
def adjust_title(ax):
title = ax.title
ax.figure.canvas.draw()
def _get_t():
ax_width = ax.get_window_extent().width
ti_width = title.get_window_extent().width
return ax_width/ti_width
while _get_t() <= 1 and title.get_fontsize() > 1:
title.set_fontsize(title.get_fontsize()-1)
adjust_title(ax1)
adjust_title(ax2)
plt.show()

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With