Home >Backend Development >Python Tutorial >How Can I Save a Matplotlib Plot as an Image File?

How Can I Save a Matplotlib Plot as an Image File?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 01:35:101025browse

How Can I Save a Matplotlib Plot as an Image File?

Saving Plot to Image File

In matplotlib, the plt.show() function displays figures in a GUI. However, it is possible to save the plot as an image file instead.

To do this, use the plt.savefig() function. Specify the desired file format in the extension. For example:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig('foo.png')

This will save the plot as a PNG image. Similarly, you can save it in other formats, such as PDF:

plt.savefig('foo.pdf')

To remove any undesirable whitespace around the image, use the bbox_inches='tight' argument:

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

Note that the function plt.show() should be called after plt.savefig() to plot on screen. Leaving out plt.show() will result in an empty saved figure.

The above is the detailed content of How Can I Save a Matplotlib Plot as an Image File?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn