Skip to main contentSkip to solution

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.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question