The following question arose while toying around with figure sizes. I am trying to create figures of the same size (let's say 5 by 5 inches). Thing is, when I change the notation of the colorbar
, the figure size seems to change. In the code below, this can be achieved by changing the final if to tick_check=False
. How can I force the figures to be the same size, regardless of the colorbar
notation?
Here's my MWE:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
def foo(arr, sub, fig, _str, vmin, vmax, ticks, fontsize, check, tick_check):
cm=plt.cm.jet
P2A=0.12; box_size=5
image=sub.matshow(arr,origin='low',cmap=cm,vmin=vmin,vmax=vmax,extent=[-10.92,10.92,-10.92,10.92],interpolation='bilinear')
sub.axis([-box_size,box_size,-box_size,box_size])
divider = make_axes_locatable(sub)
sub.set_title(_str,fontsize=fontsize); sub.set_xlabel(r"A",fontsize=fontsize); sub.set_ylabel(r"B",fontsize=fontsize)
if tick_check: cbar=fig.colorbar(image, cax=divider.append_axes("right", size="5%", pad=0.05), format='%.1E')
else: cbar=fig.colorbar(image, cax=divider.append_axes("right", size="5%", pad=0.05), format='%.1f')
cbar.set_ticks(ticks); sub.xaxis.tick_bottom(); sub.tick_params(labelsize=10);sub.set_title(_str, y=1.01); plt.tight_layout(h_pad=1)
d_arr=np.random.rand(182,182)
fig0, (a1) = plt.subplots(ncols=1,figsize=(5,5))
im=foo(d_arr,a1,fig0,r'Test',np.min(d_arr),np.max(d_arr),np.arange(np.min(d_arr),np.max(d_arr),0.1),10,False,True)
plt.savefig('Foo.eps',bbox_inches='tight',dpi=100)
Any help is appreciated.
Turns out, the solution to this problem is the keyword aspect
, which needs to be set to auto
. So:
image=sub.matshow(arr,origin='low',cmap=cm,vmin=vmin,vmax=vmax,extent=[-10.92,10.92,-10.92,10.92],interpolation='bilinear', aspect='auto')