Home >Backend Development >Python Tutorial >How Can I Save Matplotlib Plots as Image Files?
Saving Plots to Image Files in Matplotlib
When creating visualizations using Matplotlib, displaying them in a graphical user interface (GUI) is the default behavior. However, there are situations where saving the plot as an image file is desirable.
Saving Plots to Files
To save the plot to an image file, use Matplotlib's savefig function. By specifying the file extension, the output format can be customized. For example:
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [1, 4, 9]) plt.savefig('foo.png') # Saves as a PNG image plt.savefig('foo.pdf') # Saves as a PDF file
Controlling Whitespace
Sometimes, there may be undesired whitespace around the saved image. To remove this, specify bbox_inches='tight' as an argument to savefig:
plt.savefig('foo.png', bbox_inches='tight')
Note: If you intend to display the plot after saving it, ensure that plt.show() is called after plt.savefig(). Otherwise, the saved image file will be empty.
The above is the detailed content of How Can I Save Matplotlib Plots as Image Files?. For more information, please follow other related articles on the PHP Chinese website!