Search code examples
pythonmatplotlibaxessubplot

matplotlib change size of subplots


I try to make a figure with different subplots. In the example the left panel is an imshow image and it is a bit too small. How could I enlarge ax1? In order to have the colorbar at the level of the x-axes of ax2 and ax3?

The code and output is:

import matplotlib.pyplot as plt
import numpy as np


fig=plt.figure(figsize=(15,5.5))
ax1=plt.subplot2grid((1,3),(0,0))
ax2=plt.subplot2grid((1,3),(0,1))
ax3=plt.subplot2grid((1,3),(0,2))


image=np.random.random_integers(1,10,size=(100,100))
cax=ax1.imshow(image,interpolation="none",aspect='equal')
cbar=fig.colorbar(cax,ax=ax1,orientation=u'horizontal')

x=np.linspace(0,1)
ax2.plot(x,x**2)
ax3.plot(x,x**3)

plt.show()

enter image description here


Solution

  • Taking a cue from this answer, you can adjust the layout of your colorbar with AxisDivider.

    import matplotlib.pyplot as plt
    import numpy as np
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    fig=plt.figure(figsize=(15,5.5))
    ax1=plt.subplot2grid((1,3),(0,0))
    ax2=plt.subplot2grid((1,3),(0,1))
    ax3=plt.subplot2grid((1,3),(0,2))
    
    image=np.random.random_integers(1,10,size=(100,100))
    im = ax1.imshow(image,interpolation="none",aspect='equal')
    
    divider = make_axes_locatable(ax1)
    cax = divider.append_axes("bottom",size="5%",pad=0.7)
    cbar=fig.colorbar(im,cax=cax,orientation=u'horizontal')
    
    x=np.linspace(0,1)
    ax2.plot(x,x**2)
    ax3.plot(x,x**3)
    
    plt.show()
    

    enter image description here

    pad=0.7 looked about right to me. You may need to play around with that parameter as well as figsize height to get it exactly the way you want.