Labeling and Saving Figures
A figure should carry enough context to be read later.
At minimum, add labels when the axes have meaning:
Labels are part of the result
Label a curve
Ready to run.
The labels say what the numbers mean. The title states the main thing to notice.
Save a figure
Use savefig when you want a file:
plt.savefig("loss.png", dpi=150, bbox_inches="tight")
Save before calling plt.show() or plt.close(). Showing behavior differs by
environment, and closing discards the current figure.
In the browser runner, saved files live in the temporary Python file system for the current page session. The runner also captures open figures and displays them below the output.
Close figures in longer scripts
For small examples, the runner closes figures after collecting them. In longer local scripts, close figures when you create many of them:
plt.close()
That prevents old figures from accidentally carrying into later plots.
Which function saves the current Matplotlib figure to a file?
Answer it first, then check.
Hint
The function name joins the words “save” and “figure.”
Solution
Use savefig:
plt.savefig("loss.png", dpi=150, bbox_inches="tight")
Call it after constructing the figure and before showing or closing it.