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
Release: 2024-12-05 01:35:10
Original
1026 people have browsed it

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')
Copy after login

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

plt.savefig('foo.pdf')
Copy after login

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

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

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template