The Python Oracle

Save plot to image file instead of displaying it using Matplotlib

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Isolated

--

Chapters
00:00 Question
00:25 Accepted answer (Score 2048)
01:07 Answer 2 (Score 281)
02:04 Answer 3 (Score 175)
02:16 Answer 4 (Score 115)
03:34 Thank you

--

Full question
https://stackoverflow.com/questions/9622...

Accepted answer links:
[matplotlib.pyplot.savefig]: https://matplotlib.org/stable/api/_as_ge...

Answer 2 links:
[documentation]: https://matplotlib.org/3.1.1/api/_as_gen...

Answer 4 links:
http://matplotlib.org/faq/howto_faq.html...
[one]: https://stackoverflow.com/questions/4408...
[two]: https://stackoverflow.com/questions/5361...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib #plot

#avk47



ACCEPTED ANSWER

Score 2278


When using matplotlib.pyplot.savefig, the file format can be specified by the extension:

from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

That gives a rasterized or vectorized output respectively. In addition, there is sometimes undesirable whitespace around the image, which can be removed with:

plt.savefig('foo.png', bbox_inches='tight')

Note that if showing the plot, plt.show() should follow plt.savefig(); otherwise, the file image will be blank.




ANSWER 2

Score 327


As others have said, plt.savefig() or fig1.savefig() is indeed the way to save an image.

However I've found that in certain cases the figure is always shown. (eg. with Spyder having plt.ion(): interactive mode = On.) I work around this by forcing the the figure window to close with:

plt.close(figure_object)

(see documentation). This way I don't have a million open figures during a large loop. Example usage:

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png')   # save the figure to file
plt.close(fig)    # close the figure window

You should be able to re-open the figure later if needed to with fig.show() (didn't test myself).




ANSWER 3

Score 191


The solution is:

import matplotlib.pyplot as plt

... # your way of creating the graph
plt.savefig('foo.png')



ANSWER 4

Score 61


If you don't like the concept of the "current" figure, do:

import matplotlib.image as mpimg

img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)