How can I save a plot created with Matplotlib to an image file instead of displaying it?
We can do this using the
from matplotlib import pyplot pyplot.savefig("myPlot.png", bbox_inches="tight")
This function will save the current plot as a PNG image file. By specifying a different file extension, we could instead save it as an SVG (
.svg), PostScript file (
.ps), or PDF (
bbox_inches="tight" ensures that the image is saved without surrounding whitespace. Additional arguments can be specified to change the colors and transparency of the saved image.
pyplot.show clears the current plot, and should therefore only be called after
pyplot.savefig, to avoid saving a blank image.