When plotting two (or more) subplots which share the same axes, I see large areas of white spaces within the plots as seen here:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
ax.imshow(np.random.random((10,10)))
ax.autoscale(False)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax, sharey=ax)
ax2.imshow(np.random.random((10,10)))
ax2.autoscale(False)
plt.show()
These white spaces persist even after autoscale(False)
, ax.set_xlim(0, 10)
, and/or ax.set_xbound(0, 10)
. One way to get rid of the white spaces is to set aspect=auto
in imshow()
, but this is not always ideal.
One could also set a figsize
and manually adjust the axes to get the image contained exactly within the figure without white spaces, but resizing the figure would make the white spaces appear again.
Is there a way to correct for this behaviour?
@mlynn1 – thanks I now know what you’re after (the behaviour before vs after of the share definition was the key).
I’ve just learnt something new about mpl in the process of digging into this one. There is an
adjustable
attribute (if you look inmatplotlib.axes.Axes.__init__
you will see that this is set when sharing) which controls whether the axis is squeezed up to the data. To force the behaviour which you see when not sharing, set this to ‘bbox-forced’:When I do this, I get the same behaviour as when not sharing, only with the nice functionality that sharing adds.
HTH