Search code examples
pythonmatplotlibsavefig

Save plot to image file instead of displaying it


This displays the figure in a GUI:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()

But how do I instead save the figure to a file (e.g. foo.png)?


Solution

  • 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.