Removing white space around a saved image
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle
--
Chapters
00:00 Question
01:16 Accepted answer (Score 290)
02:10 Answer 2 (Score 346)
02:56 Answer 3 (Score 38)
03:22 Answer 4 (Score 29)
03:38 Thank you
--
Full question
https://stackoverflow.com/questions/1183...
Answer 1 links:
[Matplotlib plots: removing axis, legends and white spaces]: https://stackoverflow.com/questions/9295...
[How to set the margins for a matplotlib figure?]: https://stackoverflow.com/questions/1089...
[Reduce left and right margins in matplotlib plot]: https://stackoverflow.com/questions/4042...
Answer 3 links:
[http://robotics.usc.edu/~ampereir/wordpr...]: http://robotics.usc.edu/~ampereir/wordpr.../?
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #matplotlib #imshow #savefig
#avk47
ANSWER 1
Score 392
You can remove the white space padding by setting bbox_inches="tight" in savefig:
plt.savefig("test.png",bbox_inches='tight')
You'll have to put the argument to bbox_inches as a string, perhaps this is why it didn't work earlier for you.
Possible duplicates:
Matplotlib plots: removing axis, legends and white spaces
ACCEPTED ANSWER
Score 306
I cannot claim I know exactly why or how my “solution” works, but this is what I had to do when I wanted to plot the outline of a couple of aerofoil sections — without white margins — to a PDF file. (Note that I used matplotlib inside an IPython notebook, with the -pylab flag.)
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.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig("filename.pdf", bbox_inches = 'tight',
pad_inches = 0)
I have tried to deactivate different parts of this, but this always lead to a white margin somewhere. You may even have modify this to keep fat lines near the limits of the figure from being shaved by the lack of margins.
ANSWER 3
Score 41
After trying the above answers with no success (and a slew of other stack posts) what finally worked for me was just
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 the bbox or padding arguments.
ANSWER 4
Score 32
I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:
plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)