Delete space around saved image in matplotlib

I need to take an image and save it after some process. The shape looks good when I display it, but after saving the shape, I got free space around the saved image. I tried the 'tight' option for the savefig method, it didn't work either. The code:

  import matplotlib.image as mpimg import matplotlib.pyplot as plt fig = plt.figure(1) img = mpimg.imread(path) plt.imshow(img) ax=fig.add_subplot(1,1,1) extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) plt.savefig('1.png', bbox_inches=extent) plt.axis('off') plt.show() 

I am trying to draw a basic graph using NetworkX in the drawing and save it. I realized that without a graph, this works, but when I add a graph, I get a space around the saved image;

 import matplotlib.image as mpimg import matplotlib.pyplot as plt import networkx as nx G = nx.Graph() G.add_node(1) G.add_node(2) G.add_node(3) G.add_edge(1,3) G.add_edge(1,2) pos = {1:[100,120], 2:[200,300], 3:[50,75]} fig = plt.figure(1) img = mpimg.imread("C:\\images\\1.jpg") plt.imshow(img) ax=fig.add_subplot(1,1,1) nx.draw(G, pos=pos) extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) plt.savefig('1.png', bbox_inches = extent) plt.axis('off') plt.show() 
+130
python matplotlib
Aug 07 2018-12-12T00:
source share
11 answers

I canโ€™t say that I know exactly why and how my โ€œsolutionโ€ works, but this is what I had to do when I wanted to chart several sections of aerial photographs; without white margins; to a pdf file. (Note that I used matplotlib inside an IPython laptop with the -pylab flag.)

 gca().set_axis_off() subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0) margins(0,0) gca().xaxis.set_major_locator(NullLocator()) gca().yaxis.set_major_locator(NullLocator()) savefig("filename.pdf", bbox_inches = 'tight', pad_inches = 0) 

I tried to deactivate different parts of this, but this always results in a white field. Perhaps you are even modifying this to maintain live lines close to the limits of the shape from shaving due to lack of margins.

+118
Dec 01 '14 at 11:45
source share

You can remove the space by setting bbox_inches="tight" in savefig :

 plt.savefig("test.png",bbox_inches='tight') 

You need to put the argument in bbox_inches as a string, which is probably why it did not work before for you.




Possible duplicates:

Matplotlib graphs: removing axis, legends and spaces

How to set margins for matplotlib shape?

Reduce left and right margins in matplotlib graphics

+159
Aug 07 2018-12-12T00:
source share

I found something from Arvind Pereira ( http://robotics.usc.edu/~ampereir/wordpress/?p=626 ) and it seemed to work for me:

 plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0) 
+14
Sep 11 '17 at 15:05
source share

The next feature includes Johannes answer above. I checked this with plt.figure and plt.subplots() with multiple axes and this works great.

 def save(filepath, fig=None): '''Save the current image with no whitespace Example filepath: "myfig.png" or r"C:\myfig.pdf" ''' import matplotlib.pyplot as plt if not fig: fig = plt.gcf() plt.subplots_adjust(0,0,1,1,0,0) for ax in fig.axes: ax.axis('off') ax.margins(0,0) ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) fig.savefig(filepath, pad_inches = 0, bbox_inches='tight') 
+12
Nov 28 '18 at 9:23
source share

I found that the following codes work fine for this to work.

 fig = plt.figure(figsize=[6,6]) ax = fig.add_subplot(111) ax.imshow(data) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) ax.set_frame_on(False) plt.savefig('data.png', dpi=400, bbox_inches='tight',pad_inches=0) 
+9
May 24 '18 at 15:16
source share

After unsuccessful attempts to get answers to these questions (and many other messages on the stack), I finally succeeded

 plt.gca().set_axis_off() plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0) plt.margins(0,0) plt.savefig("myfig.pdf") 

Importantly, this does not include bbox or padding arguments. For unknown reasons, when the bbox argument was included in my save file, my figure was shifted to the right and up from the center.

+9
Nov 15 '18 at 0:19
source share

I followed this sequence and it worked like a charm.

 plt.axis("off") fig=plt.imshow(image array,interpolation='nearest') fig.axes.get_xaxis().set_visible(False) fig.axes.get_yaxis().set_visible(False) plt.savefig('destination_path.pdf', bbox_inches='tight', pad_inches=0, format='pdf', dpi=1200) 
+3
Nov 27 '18 at 13:06
source share

I found a much simpler approach - use plt.imsave :

  import matplotlib.pyplot as plt arr = plt.imread(path) plt.imsave('test.png', arr) 
+1
Jun 28 '19 at 9:18
source share

For anyone who wants to work in pixels, not inches, this is fine.

Plus, you will also need

 from matplotlib.transforms import Bbox 

Then you can use the following:

 my_dpi = 100 # Good default - does not really matter # Size of output in pixels h = 224 w = 224 fig, ax = plt.subplots(1, figsize=(w/my_dpi, h/my_dpi), dpi=my_dpi) ax.set_position([0, 0, 1, 1]) # Critical! # Do some stuff ax.imshow(img) ax.imshow(heatmap) # 4-channel RGBA ax.plot([50, 100, 150], [50, 100, 150], color="red") ax.axis("off") fig.savefig("saved_img.png", bbox_inches=Bbox([[0, 0], [w/my_dpi, h/my_dpi]]), dpi=my_dpi) 

enter image description here

+1
Sep 20 '19 at 2:05
source share

If you want to display what needs to be saved, I recommend using the plt.tight_layout transform, which is actually preferable since when using plt.savefig

Unnecessary cropping is not performed.
 import matplotlib as plt plt.plot([1,2,3], [1,2,3]) plt.tight_layout(pad=0) plt.savefig('plot.png') 

Unfortunately, this solution still leaves a small margin on the right and top.

-one
Aug 14 '19 at 15:59
source share

This works for me, saving the numpy array built with imshow to a file

 import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,10)) plt.imshow(img) # your image here plt.axis("off") plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0) plt.savefig("example2.png", box_inches='tight', dpi=100) plt.show() 
-3
May 2 '18 at 1:52
source share



All Articles