Yolkions
Yolkions

Reputation: 91

How to automate placement of fig.suptitle properly when displaying wide images with imshow in matplotlib?

The issue is that fig.suptitle and ax.imshow (with wide images) do not work well together. I understand that there are some aspect ratio (or something) hurdles to overcome due to the image being wide and the figure being square. That said, I want to know a formula or the set of mpl config options I can use so I can consistently place the title regardless of the image size or grid size.
Something to the effect of F(image_shape, figsize) -> config / location of how to place the suptitle directly above the plot

For example:

import matplotlib.pyplot as plt
import numpy as np 
mat5x10 = (np.arange(5*10).reshape((5,10))%2 == 0)
fig,ax = plt.subplots()
ax.imshow(mat5x10)
fig.suptitle("mat 5x10")
_ = plt.show()

results in a title too high: fig sup title too high

I know I can use ax.set_title to place it better

mat5x10 = (np.arange(5*10).reshape((5,10))%2 == 0)
fig,ax = plt.subplots()
ax.imshow(mat5x10)
ax.set_title("mat 5x10")
_ = plt.show()

placed better

but this is not sufficient for when I do multiple plots. see that the suptitle goes even further up to account for the multi-columns.

fig,axes = plt.subplots(ncols =2)
mat5x10 = (np.arange(5*10).reshape((5,10))%2 == 0)
axes[0].imshow(mat5x10)

mat2_5x10 = (np.arange(5*10).reshape((5,10))%2 == 1)
axes[1].imshow(mat2_5x10)

fig.suptitle("Two mats")
_ = plt.show()

gives an even worse placement,

Even worse placement

By randomly guessing the figsize I can get the title closer to where I'd like it (that is less white space on the top of the figure)

fig,axes = plt.subplots(ncols =2, figsize=(10,3))
mat5x10 = (np.arange(5*10).reshape((5,10))%2 == 0)
axes[0].imshow(mat5x10)

mat2_5x10 = (np.arange(5*10).reshape((5,10))%2 == 1)
axes[1].imshow(mat2_5x10)

fig.suptitle("Two mats")
_ = plt.show()

Better placement through guess and check

However I do not know why (10,3) works for showing two (5x10) mats. I'm sure it's relating to the aspect ratio, but not sure how to devise a method for properly placing this title regardless of whatever odd shaped images I put in a figure.

things like constrained_layout and tight_layout seem ineffective... Advice?

Upvotes: 0

Views: 71

Answers (0)

Related Questions