I am trying to plot matshow with aspect ratio 1, but when I rely on the method suggested here I get an extra space around the plot that I cannot get rid off. What is the solution?
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import ticker
def forceAspect(ax,aspect=1):
im = ax.get_images()
extent = im[0].get_extent()
ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)
a=np.random.randn(8,4)
plt.matshow(a)
plt.colorbar(shrink=.5)
ax=plt.gca()
forceAspect(ax,aspect=1)
plt.xticks(np.arange(0, 4, 1), np.arange(1, 5, 1))
plt.yticks(np.arange(0, 8, 1), np.arange(1, 9, 1))
#plt.tight_layout()
#ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%1d'))
#ax.xaxis.set_ticks(np.arange(1, 6, 1))
plt.show()