Saving a matplotlib.pyplot figure as a border-less frame-less image

Captured at: 2013-05-23 10:10:27 UTC

The point of this post isn’t to explain how Matplotlib’s savefig works. The litte code-snippet below allows us to save the output of a figure into an image format such as a PNG while getting rid of the border and frame of the image. Why is this useful? If you need to create a ground-overlay for Google-Earth for example, figuring out the bounding co-ordinates of the output image is much more difficult if there is a frame and padding involved too. The code below should take care of all that:

Save Figure as Image without borders and frames

import pylab
import matplotlib.pyplot as plt

def SaveFigureAsImage(fileName,fig=None,**kwargs):
    ''' Save a Matplotlib figure as an image without borders or frames.
       Args:
            fileName (str): String that ends in .png etc.

            fig (Matplotlib figure instance): figure you want to save as the image
        Keyword Args:
            orig_size (tuple): width, height of the original image used to maintain 
            aspect ratio.
    '''
    fig.patch.set_alpha(0)
    if kwargs.has_key('orig_size'): # Aspect ratio scaling if required
        w,h = kwargs['orig_size']
        fig_size = fig.get_size_inches()
        w2,h2 = fig_size[0],fig_size[1]
        fig.set_size_inches([(w2/w)*w,(w2/w)*h])
        fig.set_dpi((w2/w)*fig.get_dpi())
    a=fig.gca()
    a.set_frame_on(False)
    a.set_xticks([]); a.set_yticks([])
    plt.axis('off')
    plt.xlim(0,h); plt.ylim(w,0)
    fig.savefig(fileName, transparent=True, bbox_inches='tight', \
        pad_inches=0)