Plotting to Image Files
When using Matplotlib's pyplot interface, the plt.show() function displays a figure in a graphical user interface (GUI) window. However, there may be instances when you need to save the figure as an image file for later use or sharing.
Method:
To save the plot to an image file, use the plt.savefig() function. This function takes the file name as its first argument. The second argument, bbox_inches='tight', ensures there is no unwanted whitespace around the saved image.
import matplotlib.pyplot as plt # Plot data plt.plot([1, 2, 3], [1, 4, 9]) # Save plot to file plt.savefig('foo.png', bbox_inches='tight') # Show plot (optional) plt.show()
File Format:
You can specify the file format by using the file extension. For instance, .png will save the plot as a Portable Network Graphic, while .pdf will save it as a Portable Document Format vector image.
Note:
If you wish to display the plot in a GUI window in addition to saving it to a file, remember to call plt.show() after calling plt.savefig(). Otherwise, the saved image will be empty.
The above is the detailed content of How Can I Save a Matplotlib Plot to an Image File?. For more information, please follow other related articles on the PHP Chinese website!