HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

Save plot to image file instead of displaying it

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
savedisplayingplotimagefileinstead

Problem

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.

Code Snippets

from matplotlib import pyplot as plt

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

Context

Stack Overflow Q#9622163, score: 2296

Revisions (0)

No revisions yet.