Gregory
Gregory

Reputation: 349

Equal width plot sizes in pyplot, while keeping aspect ratio equal

I want to have two plots be the same width, however the resulting code shrinks the imshow plot.

xx = np.linspace(0.0,255.5,512)
yy = np.linspace(0.0,255.5,512)
Func = np.random.rand(len(xx),len(yy))

f, axarr = plt.subplots(2,1)
f.tight_layout()

im = axarr[0].imshow(Func, cmap = 'jet', interpolation = 'lanczos',origin = 'lower')
pos = axarr[0].get_position()
colorbarpos = [pos.x0+1.05*pos.width,pos.y0,0.02,pos.height]
cbar_ax = f.add_axes(colorbarpos)
cbar = f.colorbar(im,cax=cbar_ax)

axarr[1].plot(xx,Func[:,255],yy,Func[255,:])

plt.show()
plt.close('all')

EDIT: I would also like to keep imshow's plot from looking stretched (essentially, I need the width and length stretched appropriately so the aspect ratio's are still equal).

Upvotes: 3

Views: 2022

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

Some options:

A. `aspect="auto"

Use `aspect="auto" on the imshow plot

    plt.imshow(...,  aspect="auto")

enter image description here

B. adjust the figure margings

Adjust the figure margings or the figure size, such that the lower axes will have the same size as the imshow plot, e.g.

    plt.subplots_adjust(left=0.35, right=0.65)

enter image description here

C. using a divider

You can use make_axes_locatable functionality from mpl_toolkits.axes_grid1 to divide the image axes to make space for the other axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

xx = np.linspace(0.0,255.5,512)
yy = np.linspace(0.0,255.5,512)
Func = np.random.rand(len(xx),len(yy))

fig, ax = plt.subplots(figsize=(4,5))

im = ax.imshow(Func, cmap = 'jet', interpolation = 'lanczos',origin = 'lower')

divider = make_axes_locatable(ax)
ax2 = divider.append_axes("bottom", size=0.8, pad=0.3)
cax = divider.append_axes("right", size=0.08, pad=0.1)

ax2.plot(xx,Func[:,255],yy,Func[255,:])
cbar = fig.colorbar(im,cax=cax)

plt.show()

enter image description here

Upvotes: 6

Related Questions