Plotting and saving the training and validation curve

BeginnerCharts and data visualisationScientific reports

Goal: Producing a publication-quality figure of the two loss curves.

Python — example.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

epochs = range(1, 11)
train = [0.9, 0.7, 0.55, 0.46, 0.40, 0.36, 0.33, 0.31, 0.30, 0.29]
val = [0.95, 0.76, 0.62, 0.55, 0.51, 0.50, 0.50, 0.51, 0.53, 0.55]

fig, ax = plt.subplots(figsize=(6, 3.5))
ax.plot(epochs, train, marker="o", label="train")
ax.plot(epochs, val, marker="s", label="validation")
ax.set_xlabel("epoch"); ax.set_ylabel("loss"); ax.legend(); ax.grid(alpha=.3)
fig.tight_layout()
fig.savefig("loss.png", dpi=200)
best = min(range(len(val)), key=val.__getitem__) + 1
print("Figure saved to loss.png; best epoch on validation:", best)

Code explanation

We use the Agg backend because it needs no display, plot two curves with a legend, then save the figure as PNG at 200 dots per inch. You can save as PDF or SVG for scientific papers.

Requirements

Shell
pip install matplotlib

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Figure saved to loss.png; best epoch on validation: 6

This example was actually run and tested on 21 November 2026 on a CPU — matplotlib 3.11.2, python 3.13.18

Libraries used

Related examples

BeginnerSeabornRun and tested

A distribution plot by category

Comparing a variable's distribution between two groups in one line.

Charts and data visualisation · Data analysis