Save plot to image file instead of displaying it using Matplotlib

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

from matplotlib import pyplot as plt


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, should follow plt.savefig(); otherwise, the file image will be blank.

Leave a Comment