Saving Plots to File
Sometimes, you'll want to save your plots for later, such as to include them in a report or share with a colleague.
Matplotlib makes this easy using the savefig()
function.
Note: In this notebook, the
savefig()
function is used for demonstration purposes only, so you cannot download the PNG file. If you run the code in your local environment, you can download the image file.
Saving the Current Plot
Use plt.savefig("filename.ext")
to export the current plot.
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [10, 20, 25, 30] plt.plot(x, y) plt.title("Trend Line") plt.savefig("plot.png") # Saves the image file
You can use various formats: "png"
, "jpg"
, "svg"
, "pdf"
, etc.
Make sure to call
savefig()
beforeplt.show()
— otherwise, the saved image might be empty.
Controlling Image Quality
You can adjust image resolution using the dpi
(dots per inch) parameter.
plt.savefig("plot_high_res.png", dpi=300)
This is useful when preparing plots for printing or publishing.
Saving Without Displaying
You can save a plot without calling plt.show()
. This is helpful when generating many charts automatically.
plt.plot(x, y) plt.title("Autosave Example") plt.savefig("autosave.png")
No plot will display, but the file will be saved.
What function in Matplotlib is used to save plots directly to an image file?
plt.show()
plt.plot()
plt.savefig()
plt.title()
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help