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

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

While the question has been answered, Id 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 plt

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

Will give a rasterized or vectorized output respectively, both which could be useful. In addition, theres often an 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.

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

However Ive 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 dont have a million open figures during the loop:

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() (didnt test myself).

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

The solution is:

pylab.savefig(foo.png)

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *