a.smiet
a.smiet

Reputation: 1825

matplotlib imshow centering with disabled axes

How can I center a matlotlib imshow figure after disabling the axes? Example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5,5))
plt.axis('off')

plt.imshow(np.random.randint(10, size=(100, 100)))
plt.show()

Now the image is not really centered, especially if I apply a tight_layout since it does take the axes into account although they are disabled?!

plt.tight_layout()

Same problem occurs if I e.g. add a colorbar. Of course one could adjust the borders manually by command or in the UI, however, I would prefer a more robust solution that works automatically with different image shapes and sizes. Moreover, the figure size should not be changed during centering. Any hints?

Upvotes: 0

Views: 1025

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339350

The subplot parameters set by the default rc file are

figure.subplot.left    : 0.125  ## the left side of the subplots of the figure
figure.subplot.right   : 0.9    ## the right side of the subplots of the figure
figure.subplot.bottom  : 0.11   ## the bottom of the subplots of the figure
figure.subplot.top     : 0.88   ## the top of the subplots of the figure

As you can see, they are asymmetric. You can set them to something symmetric, if you want

rc = {"figure.subplot.left"    : 0.1, 
      "figure.subplot.right"   : 0.9,
      "figure.subplot.bottom"  : 0.1,
      "figure.subplot.top"     : 0.9 }
plt.rcParams.update(rc)

or

fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9)

The fact that fig.tight_layout() does not produce a centered plot when the axes are off, is considered as bug. This has been fixed and will be working correctly from matplotlib 3.1 on (which will be released in a couple of days or weeks).

Upvotes: 1

Related Questions