matplotlib allows users to visualize data through plots, which can be displayed within a graphical user interface (GUI). However, there may be instances where one prefers to save the plot as an image file rather than displaying it directly. This article provides a walkthrough of how to achieve this in Python using matplotlib.
Problem: How can I save a matplotlib plot as an image file (e.g., foo.png) instead of displaying it?
Solution:
To save a plot as an image file, utilize matplotlib's savefig function. The desired file format can be specified by adding the desired extension to the filename:
from matplotlib import pyplot as plt plt.plot([1, 2, 3], [1, 4, 9]) plt.savefig('foo.png') # Saves the plot as a PNG file plt.savefig('foo.pdf') # Saves the plot as a PDF file
By default, savefig may result in whitespace around the image. To eliminate this, use the bbox_inches='tight' argument:
plt.savefig('foo.png', bbox_inches='tight')
Note: Ensure that you call plt.show() after plt.savefig() to avoid blank image files.
The above is the detailed content of How Can I Save a Matplotlib Plot as an Image File Instead of Displaying It?. For more information, please follow other related articles on the PHP Chinese website!