How can you save a matplotlib figure to a file?
How can you save a matplotlib figure to a file?
Solution
✅ Correct Option: 2
plt.savefig(filename) is the function in matplotlib's pyplot module that writes the current figure to a file. The file format is taken from the extension in the filename, for example plt.savefig("plot.png") or plt.savefig("plot.pdf").
Call it before plt.show(). In many setups plt.show() clears the figure, so the saved file can come out blank.
Options 1, 3 and 4: savefile, storefig and save look natural, but none of them exists in pyplot. They raise an AttributeError.
Related questions:
2026: 24 May Shift 1
2026: 11 May Shift 2
2026: 29 May Shift 2
2025: 30 May Shift 2