Save plot to image file instead of displaying it using Matplotlib
To save a plot to an image file using Matplotlib, you can use the savefig
function. Here is an example of how you can use it:
import matplotlib.pyplot as plt
# Generate some data to plot
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
# Create a figure and a subplot
fig, ax = plt.subplots()
# Plot the data
ax.plot(x, y)
# Save the figure to an image file
fig.savefig('plot.png')
This will save the plot as a PNG image file with the name plot.png
. The format of the image file can be specified using the format
parameter. For example, you can use fig.savefig('plot.jpg', format='jpg')
to save the plot as a JPEG image file.
You can also specify the resolution of the image using the dpi
parameter. For example, fig.savefig('plot.png', dpi=300)
will save the plot at a high resolution of 300 DPI (dots per inch).
You can find more information about the savefig
function in the Matplotlib documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html