Saving Plots to File
Sometimes, you’ll want to save your plots for later — maybe to include in a report or share with a colleague.
Matplotlib makes this easy using the savefig()
function.
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’s Next?
Now that you can save your plots, the next lesson will explore how to apply themes and styles to match your branding or presentation format.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.