When saving a Matplotlib figure from a Jupyter notebook, how do I override the default transparent border so it will be opaque?
Looking at the savefig documentation, there are several parameters that seem like they would affect this but actually do not seem to do anything. Here is an example.
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = np.linspace(-6, 6, 100)
ax.plot(x, np.sinc(x))
plt.savefig(
'test.png',
transparent=False, # no change
frameon=True, # no change
edgecolor='blue', # no change (want 'white' but 'blue' should be noticeable)
facecolor='red', # no change (want 'white' but 'red' should be noticeable)
alpha=1, # no change
)
Here is the result. StackOverflow does not illustrate the transparency, but note that the edge is not 'blue' and the face is not 'red'.
This post mentions setting fig.patch.set_alpha(1) which turns out to work, regardless of the savefig parameters. Adding this command to the example code resolves the problem.
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.patch.set_alpha(1) # solution
x = np.linspace(-6, 6, 100)
ax.plot(x, np.sinc(x))
fig.savefig('solved.png')
It turns out this is specific to Jupyter notebooks, and is probably a bug (I only have version 4.4.0). When I run the following code above from the command line, I instead get the desired behavior (change 'red' to 'white' to get the opaque white border).
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = np.linspace(-6, 6, 100)
ax.plot(x, np.sinc(x))
plt.savefig(
'test.png',
# transparent=False, # no change
# frameon=True, # no change
# edgecolor='blue', # no change
facecolor='red', # no change
# alpha=1, # no change
)
I am trying to create axesless contour plot of my raster data. I managed to create the contour plot however I can't remove the axes completely. I can turn them off with plt.axis('off') but axes whitespaces are still there.
What I do:
cnt = plt.contour(my_data)
plt.clabel(cnt, inline=1, fontsize=10)
plt.axis('off')
Edit
My output method
plt.savefig(image_path, transparent=False, bbox_inches='tight', pad_inches=0)
Results:
Before plt.axis('off')
After plt.axis('off')
I had the same issue with the imshow but I've managed to solve it here, however the same technique can't be used with contours.
So how can I plot contours without axes and any whitespaces they leave behind?
Edit
So I managed to determine that the problem is not in 'plt.axis('off')' part of the code. The line does in fact completely remove the axes and it is visible when I call plt.show() however when I try to save the plot with 'plt.savefig()' I get that undesirable whitespaces. Why is that?
My code with output:
cnt = plt.contour(my_data)
plt.clabel(cnt, inline=1, fontsize=10)
plt.axis('off')
# no whitespaces
plt.show()
# whitespaces are present
plt.savefig(image_path, transparent=False, bbox_inches='tight', pad_inches=0)
Possible solution!?
I did find the way to make my images almost what I wanted with:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.contour(data)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.axis('off')
plt.savefig(image_path, transparent=False, bbox_inches=extent, pad_inches=0)
However I cant change the aspect ratio of the plot. I think that I do not understand this solution to the fullest.
This is actually due to savefig's defaults. The figure can have a transparent background (e.g. try fig.patch.set(facecolor='none'); fig.canvas.print_png), but it's being overridden when you call plt.savefig.
If you want a transparent background, you'll need to specify transparent=True in your call to savefig. Otherwise, it will override the figure's current background color and set it to opaque white.
Have a look at the documentation for savefig for more details.
As an example:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((5, 5))
fig, ax = plt.subplots()
cnt = ax.contour(data)
ax.clabel(cnt)
ax.axis('off')
fig.savefig('test.png', bbox_inches='tight', transparent=True)
Of course, this looks identical on this page, but if you open it up in an image viewer you'll notice that it has a proper transparent background:
Edit:
I may have misunderstood what you're asking. If you want the contour plot to take up the entire figure with no room left for tick labels, etc on the side, it's easiest to define the plot that way to begin with.
For example (note that this applies to any type of plot, not just contouring):
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((5, 5))
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
cnt = ax.contour(data)
ax.clabel(cnt)
ax.axis('off')
plt.show()
If you're still having issues, it's probably because you're using fig.savefig(..., bbox_inches='tight'). That specifically requires the tick labels to be included in the saved image, even if they're invisible and outside of the bounds of the figure.
Try something similar to:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((5, 5))
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
cnt = ax.contour(data)
ax.clabel(cnt)
ax.axis('off')
fig.savefig('test.png')
I am plotting an image in matplotlib, and it keeps giving me some padding. This is what I have tried:
def field_plot():
x = [i[0] for i in path]
y = [i[1] for i in path]
plt.clf()
plt.axis([0, 560, 0, 820])
im = plt.imread('field.jpg')
field = plt.imshow(im)
for i in range(len(r)):
plt.plot(r[i][0],r[i][1],c=(rgb_number(speeds[i]),0,1-rgb_number(speeds[i])),linewidth=1)
plt.axis('off')
plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True")
plt.clf()
Try using pad_inches=0, i.e.
plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True", pad_inches=0)
From the documentation:
pad_inches: Amount of padding around the figure when bbox_inches is
‘tight’.
I think the default is pad_inches=0.1
Just add plt.tight_layout() before plt.savefig() !!
plt.figure(figsize=(16, 10))
# ... Doing Something ...
plt.tight_layout()
plt.savefig('wethers.png')
plt.show()
This worked for me. After plotting, get the Axes object from plt using ax = plt.gca(). Then set the xlim, and ylim of ax object to match image width and image height. Matplotlib seems to automatically increase xlim and ylim of viewing area when you plot. Note that while setting y_lim you have to invert the order of coordinates.
for i in range(len(r)):
plt.plot(r[i][0],r[i][1],c=(rgb_number(speeds[i]),0,1-rgb_number(speeds[i])),linewidth=1)
plt.axis('off')
ax = plt.gca();
ax.set_xlim(0.0, width_of_im);
ax.set_ylim(height_of_im, 0.0);
plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True")
All previous approaches didn't quite work for me, they all left some padding around the figure.
The following lines successfully removed the white or transparent padding that was left:
plt.axis('off')
ax = plt.gca()
ax.xaxis.set_major_locator(matplotlib.ticker.NullLocator())
ax.yaxis.set_major_locator(matplotlib.ticker.NullLocator())
plt.savefig(IMG_DIR + 'match.png', pad_inches=0, bbox_inches='tight', transparent=True)
Use plt.gca().set_position((0, 0, 1, 1)) to let the axes span the whole figure, see reference.
If plt.imshow is used, this requires that the figure has the correct aspect ratio.
import matplotlib as mpl
import matplotlib.pyplot as plt
# set the correct aspect ratio
dpi = mpl.rcParams["figure.dpi"]
plt.figure(figsize=(560/dpi, 820/dpi))
plt.axis('off')
plt.gca().set_position((0, 0, 1, 1))
im = plt.imread('field.jpg')
plt.imshow(im)
plt.savefig("test.png")
plt.close()
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)?
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')
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
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 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.
plt.axis('off')
plt.savefig('example.png',bbox_inches='tight',pad_inches = 0)
gets me the borderless image.
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()
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)
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)
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:
A much simpler thing to do is to use pyplot.imsave. For details, see luator's answer bellow
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)
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):
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()
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)
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
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.
This works:
plot.axis('off')
ax = plot.gca()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
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([])
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.