Skip to main content
Practice

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.

Saving as PNG
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() before plt.show() — otherwise, the saved image might be empty.


Controlling Image Quality

You can adjust image resolution using the dpi (dots per inch) parameter.

High Resolution Export
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.

Save Without Showing
plt.plot(x, y)
plt.title("Autosave Example")
plt.savefig("autosave.png")

No plot will display, but the file will be saved.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.