pythonmatplotlib

Resize a figure automatically in matplotlib


Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image?

I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.

I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?


Solution

  • Use bbox_inches='tight'

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    
    X = 10*np.random.rand(5,3)
    
    fig = plt.figure(figsize=(15,5),facecolor='w') 
    ax = fig.add_subplot(111)
    ax.imshow(X, cmap=cm.jet)
    
    plt.savefig("image.png",bbox_inches='tight',dpi=100)
    

    ...only works when saving images though, not showing them.