Clear, Comparable, and Saved Figures
Make figures understandable without reconstructing their meaning from code. Label quantities and units, keep comparison scales consistent, distinguish series accessibly, choose an appropriate export format, and retain the data and settings required to reproduce the image.
A figure should carry enough information for another reader to identify the quantities, units, groups, scales, and numerical question without reconstructing them from the source code. When figures are compared, equal visual positions, distances, and colors should have equal numerical meanings.
Saving the image is only the final step. A reproducible result also retains the data, code, settings, and environment needed to construct the same figure again.
Distinguish the figure from its plotting area
Matplotlib separates the complete figure from an Axes object inside it:
figure, axes = plt.subplots()
The figure is the complete canvas that can contain one or more plotting areas.
The Axes object contains the coordinate system, plotted data, labels, ticks,
and title for one plotting area. The class name Axes is plural even when it
refers to one object.
Using these objects makes it explicit which plot receives each setting:
The shorter plt.plot, plt.xlabel, and related calls remain useful for small
examples. Figure and Axes objects become clearer when a program creates
multiple panels or saves a specific figure.
Label quantities and units
An axis label should name the represented quantity and include its unit when the quantity has one:
response time (milliseconds)
temperature (degrees Celsius)
distance (metres)
An index or unitless quantity can be labeled without a unit:
epoch
standardized residual
class index
Avoid labels such as x, value, or result when a more specific name is
known. Mathematical symbols can be useful when they have already been defined,
but the figure or surrounding text should still connect the symbol with its
meaning.
Write titles that identify rather than conclude
A title should identify the figure, comparison, or question:
Training and validation loss by epoch
Prediction compared with target
Residuals before and after feature scaling
A title such as “The improved model is better” makes a conclusion that may depend on an unstated metric or selected range. Put interpretation in nearby prose where the evidence and limits can be explained.
Titles are not required when a surrounding caption already identifies the figure clearly. Do not repeat the same sentence in the title, caption, and paragraph.
Identify multiple series without relying on color alone
Give each curve a label and then display a legend:
Markers and line styles help readers distinguish series when colors are hard to perceive, a figure is printed without color, or curves overlap. A legend should use the same names as the text and should not cover important data. If many series make the legend or plot difficult to read, select the relevant series or use aligned panels.
Keep visual comparisons numerically consistent
Two figures can mislead when they use unrelated scales. For comparable line or scatter plots, check:
- the same horizontal and vertical quantities;
- matching units;
- the same linear or logarithmic scale;
- compatible axis limits;
- equal aspect when geometric distance from a reference line matters.
For heatmaps and surfaces, also share the colormap and numerical color limits. For histograms, share bin edges and horizontal ranges.
The next example constructs two aligned loss panels. Edit one axis limit or change one curve and inspect how the comparison changes.
Create aligned and labeled loss panels
Both panels share epoch positions and vertical limits. The line styles and markers identify datasets in addition to color.
Ready to run.
Shared axes make one vertical distance represent the same loss change in both panels. This does not make the models directly comparable if they were trained or evaluated on different data. Visual consistency is necessary, but the experimental conditions must also match.
Use layout tools instead of manual spacing guesses
Labels, legends, and colorbars can overlap or be clipped. Matplotlib can manage common layouts:
constrained_layout=True allocates space while the figure is constructed.
For a completed figure, figure.tight_layout() can adjust ordinary subplot
spacing. Complex figures may still need inspection at their final display
size.
Do not reduce text until it is unreadable merely to fit more panels. A second figure is often clearer than one crowded figure.
Choose a file format from the output
savefig chooses the format from the filename extension:
- PNG stores pixels. It is widely supported and works well for web pages, screenshots, and image-like arrays.
- SVG stores vector shapes and text. Lines and labels remain sharp when resized, though very dense figures can produce large files.
- PDF is useful for documents and printing and can preserve vector elements.
For a raster output such as PNG, dpi controls how many pixels are produced
for each inch of figure size:
bbox_inches="tight" trims excess outer space and helps retain labels near the
edge. More DPI increases pixel dimensions and file size; it does not add
information absent from the plotted data.
Save the intended figure before closing it
Call savefig after labels and layout are complete:
plt.close(figure) releases that figure and prevents later plotting calls from
accidentally adding to it. A retained figure object may still be writable after
it is removed from pyplot's active figures, but saving first is the clearer and
safer lifecycle. In particular, a later plt.savefig(...) call acts on
whichever figure is then current and may save an unintended or empty figure.
In Browser Python, Matplotlib figures that remain open are collected and shown
below the program output. Files written by savefig live in the temporary
browser-side Python file system for that page session. In a local program, the
path refers to the active file system and working directory.
When a program creates many figures, close each one after saving or inspecting it:
The comment states where figure construction belongs; a real program must add the plot and labels before saving.
Retain the ingredients needed to reproduce the image
An image file does not contain every decision that produced it. Keep:
- the plotting code;
- the source data or a stable reference to it;
- preprocessing steps;
- axis limits, scales, bins, levels, and color limits;
- relevant package versions;
- the output filename and format;
- the experiment or model configuration being visualized.
If a figure supports an important result, another reader should be able to recreate it and verify the underlying numbers rather than inspect only the exported image.
Which Matplotlib method saves a specific figure object named figure to a
file?
Answer it first, then check.
HintCall the method on the figure
Complete figure.________("result.png").
SolutionUse figure.savefig
figure.savefig("result.png") saves the named figure. The .png extension
selects PNG output.
A vertical axis measures elapsed time in seconds. Which label gives a reader the clearest information?
Select one choice, then check.
HintName what was measured
Include the quantity first and its unit in parentheses.
SolutionUse elapsed time (seconds)
The label identifies the measurement and the numerical unit represented by vertical distance.
Two curves were plotted with label="training" and label="validation".
Which call displays those names in the plotting area?
Answer it first, then check.
HintShow the figure key
The displayed key is called a legend.
SolutionCall legend
Use axes.legend() for the named Axes object, or plt.legend() when using
the pyplot interface.
Two panels show loss for models evaluated under the same conditions. Which visual setup supports a fair comparison?
Select one choice, then check.
HintKeep visual distance meaningful
Check both what each axis contains and how its numbers are scaled.
SolutionShare quantities, scales, and limits
Matching quantities, units, scale types, and limits make corresponding visual distances numerically comparable.
Which order follows the clearest lifecycle: export the completed figure, then release it from pyplot?
Select one choice, then check.
HintExport before releasing
The complete labeled figure must still be available when savefig runs.
SolutionSave, then close
Call figure.savefig(...) after construction and layout are complete, then
call plt.close(figure) to release it.
Make the figure verifiable after export
Before exporting, verify labels, units, scales, limits, legends, color mappings, and layout at the intended display size. Save the correct figure in a suitable format, close it when finished, and retain the data and code so the image can be reproduced rather than merely viewed.