485

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)
    fig.set_cmap('hot')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.savefig(outputname)

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)?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
sunmat
  • 6,976
  • 3
  • 28
  • 44
  • 2
    All the solutions on this question are focussed on `imshow`. If you have a scatterplot instead the following answer might help you: http://stackoverflow.com/a/40727744/4124317 – ImportanceOfBeingErnest Nov 21 '16 at 19:21

17 Answers17

627

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')
img.set_cmap('hot')
plt.axis('off')
plt.savefig("test.png", bbox_inches='tight')

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Hooked
  • 84,485
  • 43
  • 192
  • 261
192

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()
    fig.set_size_inches(size)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    plt.set_cmap('hot')
    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')

yields

enter image description here

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 2
    `ax.set_axis_off()` is what I was looking for. `plt.axis('off')` was making my whole plot go blank. – Antoine Jan 23 '23 at 16:38
89

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.axis('off')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
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

Domagoj
  • 1,674
  • 2
  • 16
  • 27
48

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

luator
  • 4,769
  • 3
  • 30
  • 51
  • This tip is exactly what I was looking for! I'd still be curious to know what exactly is stored, i.e the file size isn't exactly 100*100=10000 bytes. Rather, it is about 983 bytes. Interesting. – Donna Jan 26 '23 at 22:55
  • 1
    @Donna The image is saved in PNG format, which compresses the data. Hence, the resulting file size is typically less than what you would expect from just counting the pixels. – luator Jan 27 '23 at 07:23
18
plt.axis('off')

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

gets me the borderless image.

13

I found that it is all documented...

https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.axis.html#matplotlib.axes.Axes.axis

My code…. "bcK" is a 512x512 image

plt.figure()
plt.imshow(bck)
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
plt.show()
paulj
  • 141
  • 1
  • 4
12

This should remove all padding and borders:

from matplotlib import pyplot as plt

fig = plt.figure()
fig.patch.set_visible(False)

ax = fig.add_subplot(111)

plt.axis('off')
plt.imshow(data)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig("../images/test.png", bbox_inches=extent)
Vlady Veselinov
  • 4,678
  • 5
  • 23
  • 49
9

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)
    fig.set_cmap('hot')
    ax = fig.gca()
    ax.set_axis_off()
    ax.autoscale(False)
    extent = ax.get_window_extent().transformed(plt.gcf().dpi_scale_trans.inverted())
    plt.savefig(outputname, bbox_inches=extent)
gypaetus
  • 6,873
  • 3
  • 35
  • 45
9

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.])
fig.add_axes(ax)
plt.imshow([[0, 1], [0.5, 0]], interpolation="nearest")
plt.axis('off')                                # same as: ax.set_axis_off()

plt.savefig("test.png")

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.axis('off')

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

episodeyang
  • 642
  • 8
  • 15
6

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):
    shape=np.shape(data)[0:2][::-1]
    size = [float(i)/dpi for i in shape]

    fig = plt.figure()
    fig.set_size_inches(size)
    ax = plt.Axes(fig,[0,0,1,1])
    ax.set_axis_off()
    fig.add_axes(ax)
    ax.imshow(data)
    fig.savefig('out.png', dpi=dpi)
    plt.show()

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

csnemes
  • 71
  • 1
  • 1
3

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.set_axis_off()
    ax.margins(x=0, y=0, tight=True)
    fig.add_axes(ax)
    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)
    plt.show()
Dgomn D
  • 71
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 22 '22 at 14:51
2

This works:

    plot.axis('off')
    ax = plot.gca()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
leenremm
  • 1,083
  • 13
  • 19
1

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)
David Hoffman
  • 2,205
  • 1
  • 16
  • 30
1

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.

    Arguments:
        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
Richard
  • 3,024
  • 2
  • 17
  • 40
1

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.

Hulya
  • 11
  • 4
0

This worked for me to remove the ticks:

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

for ax in axes:
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
Ben
  • 51
  • 1
  • 2
0

I tried

plt.rcParams['axes.spines.left'] = False
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = 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['xtick.major.top'] = False
plt.rcParams['xtick.major.bottom'] = False
plt.rcParams['xtick.minor.top'] = 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.

Sirius Koan
  • 51
  • 2
  • 4