Matplotlib savefig without border/frame


For some cases, the function ‘savefig’ with ‘bbox_inches=’tight” doesn’t work well and still generates images with borders that you want to remove.

plt.savefig('fn.jpg', dpi = 300, bbox_inches='tight')

One way to avoid this is to look into the axes properties before calling the function ‘savefig’. Basically, you just need to create an axes object without border/frame and add it to the pre-generated figure window.

def save_image(data, cm, fn):
  
    sizes = np.shape(data)
    height = float(sizes[0])
    width = float(sizes[1])
    
    fig = plt.figure()
    fig.set_size_inches(width/height, 1, forward=False)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)

    ax.imshow(data, cmap=cm)
    plt.savefig(fn, dpi = height) 
    plt.close()

One thought on “Matplotlib savefig without border/frame

  1. kaido karner

    there will be no border on left or right, but still is on top and bottom. ideas?

    from mpl_toolkits.basemap import Basemap, cm
    import matplotlib.pyplot as plt

    fig = plt.figure()
    fig.set_size_inches (15, 15, forward=False);

    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)

    m = Basemap(epsg=3857,
    llcrnrlon = 20.961126, llcrnrlat = 56.170661,
    urcrnrlon = 28.151320, urcrnrlat = 59.937223,
    resolution=”i”)

    m.drawcoastlines()
    m.drawcountries()

    plt.savefig(‘test.png’, dpi=1024/15)

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s