How to Save Matplotlib Plot to a File Instead of Displaying It?
To save a Matplotlib plot to a file instead of displaying it, you can use the savefig()
function. The savefig()
function allows you to save the current figure to a file in a variety of formats, including PNG, PDF, SVG, and more.
Here's a simple example of how to save a Matplotlib plot to a PNG file:
import matplotlib.pyplot as plt
# Create a plot
x = [1, 2, 3, 4]
y = [1, 4, 2, 3]
plt.plot(x, y)
# Save the plot to a file
plt.savefig('my_plot.png')
In this example, we first create a simple plot using the plot()
function. Then, we use the savefig()
function to save the plot to a file named my_plot.png
.
You can also specify various options when saving the plot, such as the file format, the resolution, and more. Here's an example:
import matplotlib.pyplot as plt
# Create a plot
x = [1, 2, 3, 4]
y = [1, 4, 2, 3]
plt.plot(x, y)
# Save the plot to a file
plt.savefig('my_plot.pdf', dpi=300, bbox_inches='tight')
In this example, we save the plot to a PDF file with a resolution of 300 DPI and use the bbox_inches
parameter to ensure that the plot is saved with minimal whitespace around the edges.
Note that you should call savefig()
before calling show()
or close()
to avoid saving a blank image.