How to remove axis, legends, and white padding


I would like to apply colormap to an image, and write the resulting image, without using axes, labels, titles, or anything automatically added by matplotlib. Here is what I did:

def make_image(inputname,outputname):
    data = mpimg.imread(inputname)[:,:,0]
    fig = plt.imshow(data)

It successfully removes the axis of the figure, but the figure saved, presents a white padding, and a frame around the actual image.

How can I remove them (at least the white padding)?

Asked By: sunmat



I learned this trick from matehat, here:

import matplotlib.pyplot as plt
import numpy as np

def make_image(data, outputname, size=(1, 1), dpi=80):
    fig = plt.figure()
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.imshow(data, aspect='equal')
    plt.savefig(outputname, dpi=dpi)

# data = mpimg.imread(inputname)[:,:,0]
data = np.arange(1,10).reshape((3, 3))

make_image(data, '/tmp/out.png')


enter image description here

Answered By: unutbu

The axis('off') method resolves one of the problems more succinctly than separately changing each axis and border. It still leaves the white space around the border however. Adding bbox_inches='tight' to the savefig command almost gets you there; you can see in the example below that the white space left is much smaller, but still present.

Newer versions of matplotlib may require bbox_inches=0 instead of the string 'tight' (via @episodeyang and @kadrach)

from numpy import random
import matplotlib.pyplot as plt

data = random.random((5,5))
img = plt.imshow(data, interpolation='nearest')
plt.savefig("test.png", bbox_inches='tight')

enter image description here

Answered By: Hooked

You can also specify the extent of the figure to the bbox_inches argument. This would get rid of the white padding around the figure.

def make_image(inputname,outputname):
    data = mpimg.imread(inputname)[:,:,0]
    fig = plt.imshow(data)
    ax = fig.gca()
    extent = ax.get_window_extent().transformed(plt.gcf().dpi_scale_trans.inverted())
    plt.savefig(outputname, bbox_inches=extent)
Answered By: gypaetus

Possible simplest solution:

I simply combined the method described in the question and the method from the answer by Hooked.

fig = plt.imshow(my_data)
plt.savefig('pict.png', bbox_inches='tight', pad_inches = 0)

After this code there is no whitespaces and no frame.

No whitespaces, axes or frame

Answered By: Domagoj

No one mentioned imsave yet, which makes this a one-liner:

import matplotlib.pyplot as plt
import numpy as np

data = np.arange(10000).reshape((100, 100))
plt.imsave("/tmp/foo.png", data, format="png", cmap="hot")

It directly stores the image as it is, i.e. does not add any axes or border/padding.

enter image description here

Answered By: luator

First, for certain image formats (i.e. TIFF) you can actually save the colormap in the header and most viewers will show your data with the colormap.

For saving an actual matplotlib image, which can be useful for adding annotations or other data to images, I’ve used the following solution:

fig, ax = plt.subplots(figsize=inches)
ax.matshow(data)  # or you can use also imshow
# add annotations or anything else
# The code below essentially moves your plot so that the upper
# left hand corner coincides with the upper left hand corner
# of the artist
fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
# now generate a Bbox instance that is the same size as your
# single axis size (this bbox will only encompass your figure)
bbox = matplotlib.transforms.Bbox(((0, 0), inches))
# now you can save only the part of the figure with data
fig.savefig(savename, bbox_inches=bbox, **kwargs)
Answered By: David Hoffman

I liked ubuntu’s answer, but it was not showing explicitly how to set the size for non-square images out-of-the-box, so I modified it for easy copy-paste:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

def save_image_fix_dpi(data, dpi=100):
    size = [float(i)/dpi for i in shape]

    fig = plt.figure()
    ax = plt.Axes(fig,[0,0,1,1])
    fig.savefig('out.png', dpi=dpi)

Saving images without border is easy whatever dpi you choose if pixel_size/dpi=size is kept.

data = mpimg.imread('test.png')
save_image_fix_dpi(data, dpi=100)

enter image description here

However displaying is spooky. If you choose small dpi, your image size can be larger than your screen and you get border during display. Nevertheless, this does not affect saving.

So for

save_image_fix_dpi(data, dpi=20)

The display becomes bordered (but saving works):
enter image description here

Answered By: csnemes

This should remove all padding and borders:

from matplotlib import pyplot as plt

fig = plt.figure()

ax = fig.add_subplot(111)


extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig("../images/test.png", bbox_inches=extent)
Answered By: Vlady Veselinov

The upvoted answer does not work anymore. To get it to work you need
to manually add an axis set to [0, 0, 1, 1], or remove the patch under figure.

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5, 5), dpi=20)
ax = plt.Axes(fig, [0., 0., 1., 1.])
plt.imshow([[0, 1], [0.5, 0]], interpolation="nearest")
plt.axis('off')                                # same as: ax.set_axis_off()


Alternatively, you could just remove the patch. You don’t need to add a subplot in order to remove the paddings. This is simplified from Vlady’s answer below

fig = plt.figure(figsize=(5, 5))
fig.patch.set_visible(False)                   # turn off the patch

plt.imshow([[0, 1], [0.5, 0]], interpolation="nearest")

plt.savefig("test.png", cmap='hot')

This is tested with version 3.0.3 on 2019/06/19. Image see bellow:

enter image description here

A much simpler thing to do is to use pyplot.imsave. For details, see luator’s answer bellow

Answered By: episodeyang

Thanks for the awesome answers from everyone …I had exactly the same problem with wanting to plot just an image with no extra padding/space etc, so was super happy to find everyone’s ideas here.

Apart from image with no padding, I also wanted to be able to easily add annotations etc, beyond just a simple image plot.

So what I ended up doing was combining David’s answer with csnemes’ to make a simple wrapper at the figure creation time. When you use that, you don’t need any changes later with imsave() or anything else:

def get_img_figure(image, dpi):
    Create a matplotlib (figure,axes) for an image (numpy array) setup so that
        a) axes will span the entire figure (when saved no whitespace)
        b) when saved the figure will have the same x/y resolution as the array, 
           with the dpi value you pass in.

        image -- numpy 2d array
        dpi -- dpi value that the figure should use

    Returns: (figure, ax) tuple from plt.subplots

    # get required figure size in inches (reversed row/column order)
    inches = image.shape[1]/dpi, image.shape[0]/dpi

    # make figure with that size and a single axes
    fig, ax = plt.subplots(figsize=inches, dpi=dpi)

    # move axes to span entire figure area
    fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)

    return fig, ax
Answered By: Richard

I found that it is all documented…

My code…. “bcK” is a 512×512 image

plt.axis("off")   # turns off axes
plt.axis("tight")  # gets rid of white border
plt.axis("image")  # square up the image instead of filling the "figure" space
Answered By: paulj

I have been looking for several codes to solve this problem and the verified answer to this question is the only code that helped me.

This is useful for scatter plots and triplots. All you have to do is change the margins to zero and you are all done.

Answered By: Hulya

plt.savefig('example.png',bbox_inches='tight',pad_inches = 0)

gets me the borderless image.

Answered By: Nazmus Sakib Akash

This is what finally worked for me:

ax.margins(x=0, y=0, tight=True) was the key line.

    fig = plt.figure(figsize=(8, 8))
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.margins(x=0, y=0, tight=True)
    for triangle in list_of_triangles:
        x_points = [point[0] for point in triangle]
        y_points = [point[1] for point in triangle]
        plt.fill(x_points, y_points, 'k', edgecolor='k')
    plt.savefig("test.png", bbox_inches=0, pad_inches=0)
Answered By: Dgomn D

This worked for me to remove the ticks:

fig, axes = plt.subplots(2, figsize=(15, 20))

for ax in axes:
Answered By: Ben

I tried

plt.rcParams['axes.spines.left'] = False
plt.rcParams['axes.spines.right'] = False
plt.rcParams[''] = False
plt.rcParams['axes.spines.bottom'] = False
plt.rcParams['ytick.major.left'] = False
plt.rcParams['ytick.major.right'] = False
plt.rcParams['ytick.minor.left'] = False
plt.rcParams['ytick.minor.left'] = False
plt.rcParams[''] = False
plt.rcParams['xtick.major.bottom'] = False
plt.rcParams[''] = False
plt.rcParams['xtick.minor.bottom'] = False
fig = plt.figure()

And it removes all border and axes.

I get this from another question on Stack Overflow.

Answered By: Sirius Koan

This works:

    ax = plot.gca()
Answered By: leenremm
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.