Save plot to image file instead of displaying it using Matplotlib Save plot to image file instead of displaying it using Matplotlib python python

Save plot to image file instead of displaying it using Matplotlib


While the question has been answered, I'd like to add some useful tips when using matplotlib.pyplot.savefig. The file format can be specified by the extension:

from matplotlib import pyplot as pltplt.savefig('foo.png')plt.savefig('foo.pdf')

Will give a rasterized or vectorized output respectively, both which could be useful. In addition, you'll find that pylab leaves a generous, often undesirable, whitespace around the image. You can remove the whitespace using:

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


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 closing of the figure window in my giant loop with plt.close(figure_object) (see documentation), so I don't have a million open figures during the loop:

import matplotlib.pyplot as pltfig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axisax.plot([0,1,2], [10,20,3])fig.savefig('path/to/save/image/to.png')   # save the figure to fileplt.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).


The solution is:

pylab.savefig('foo.png')