Save Plot to Image File Instead of Displaying It?
Better Stack Team
Updated on June 19, 2024
To save a plot to an image file instead of displaying it, you can use the savefig()
function provided by the matplotlib.pyplot
module. Here's how you can do it:
import matplotlib.pyplot as plt
# Generate some sample data and create a plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
# Save the plot to an image file (e.g., PNG format)
plt.savefig('plot.png')
In this example:
- We create a simple line plot using
plt.plot()
. - We use
plt.savefig('plot.png')
to save the plot to an image file namedplot.png
in the current working directory. - You can specify the filename along with the desired file format (e.g.,
'plot.png'
for PNG format,'plot.jpg'
for JPEG format, etc.). - You can also specify additional parameters to control the size, resolution, and other properties of the saved image. For example,
plt.savefig('plot.png', dpi=300)
sets the resolution to 300 dots per inch (DPI).
After executing this code, the plot will be saved as an image file (plot.png
in this example) in the current working directory.