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

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

DDD
Release: 2024-12-12 18:08:17
Original
559 people have browsed it

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

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

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template