Save & Export¶
Thin wrappers around matplotlib.Figure.savefig for common workflows:
export multiple formats in one call, or save-and-display SVGs sized for
notebooks/reports.
Example¶
import dartwork_mpl as dm
# Multi-format export with validation
dm.save_formats(fig, "report/figures/example",
formats=("png", "svg", "pdf"), dpi=300)
# Save and preview
dm.save_and_show(fig, size=720)
# Display an existing SVG
dm.show("output/forecast.svg", size=540)
API¶
- dartwork_mpl.save_formats(fig: Figure, image_stem: str, formats: tuple[str, ...] = ('png', 'pdf'), bbox_inches: str | None = None, validate: bool = True, *, validate_quiet: bool = False, adopt_orphan_tick_font: bool | None = None, **kwargs: Any) None[source]¶
Save a figure in multiple specified formats at once.
- Parameters:
fig (matplotlib.figure.Figure) – The Matplotlib figure to save.
image_stem (str) – Base path and filename without extension. If the value accidentally ends with a known image suffix (
.png,.pdf,.svg, …) it is stripped automatically and aUserWarningis emitted — prevents double-extension output likechart.png.png.formats (tuple[str, ...], optional) – Tuple of format extensions to save. Default is (“png”, “pdf”).
bbox_inches (str | None, optional) – Bounding box setting for the saved figure. Commonly “tight” to minimize whitespace. Default is None.
validate (bool, optional) – If True, performs visual validation before saving and prints
[VISUAL]warnings to stdout on issues. Default is True. Pair withvalidate_quiet=Trueto keep the check but suppress the stdout output.validate_quiet (bool, optional) – If
Trueandvalidate=True, runs the visual checks but does not print[VISUAL]warnings to stdout. The returned warning list insidevalidate_figure()is unchanged; this only silences the print side-effect for automated pipelines that don’t want noise but still want the check to run. Default isFalse(print as before).adopt_orphan_tick_font (bool | None, optional) – If
True, tick labels (and offset text) on any axis that has no axis label adopt that axis’s label font before saving, viaadopt_axis_label_font(). This guarantees the saved output reflects the adoption even whensimple_layout()was not called (it already applies the same step by default). Default isNone— the value is read fromdartwork_mpl.config.adopt_orphan_tick_font(itself defaulting toTrue), so setdm.config.adopt_orphan_tick_font = Falseonce to flip every call site at once. PassTrue/Falseexplicitly to override per call.**kwargs – Additional keyword arguments passed to
savefig. Ametadatadict is honoured (see the Reproducibility note).
Notes
Reproducibility. SVG and PDF output is deterministic by default: the SVG element ids are pinned with a fixed
svg.hashsaltderived from the output basename, and the wall-clock timestamp each backend would otherwise embed (SVG<dc:date>, PDF/CreationDate) is dropped, so re-rendering an unchanged figure yields a byte-identical file instead of churning version control. PNG is left untouched. To override: pass your ownmetadata={"Date": ...}/metadata={"CreationDate": ...}to keep a timestamp (the caller always wins; other metadata keys are preserved), or setmatplotlib.rcParams["svg.hashsalt"]globally to keep your own salt (a non-Noneambient salt is never overridden). No global rcParams state is mutated — the salt is applied via a scopedrc_context.When the adoption is on (whether via this keyword or the
dartwork_mpl.configdefault), this call mutates the figure: it restyles the tick-label fonts of any unlabeled axis, and the change persists after the call. This is the one mutationsave_formatsperforms (it otherwise only reads and writes). It is idempotent and matches whatsimple_layoutalready applies. It does not re-fit margins — callsimple_layoutfor layouts that must grow to fit enlarged orphan ticks. On figures using matplotlibconstrained_layout, the font change can trigger a re-layout on the next draw (expected matplotlib behavior). Passadopt_orphan_tick_font=Falseto keep the figure untouched.
- dartwork_mpl.save_and_show(fig: Figure, image_path: str | None = None, size: int = 600, unit: str = 'pt', *, adopt_orphan_tick_font: bool | None = None, close_figure: bool = True, **kwargs: Any) None[source]¶
Save a figure to disk, then display it in a Jupyter or web environment.
- Parameters:
fig (matplotlib.figure.Figure) – The Matplotlib figure to save and display.
image_path (str | None, optional) – Path to save the image. If None, a system temporary file is used.
size (int, optional) – Display width. Default is 600.
unit (str, optional) – Unit for the size (‘pt’, ‘px’, etc.). Default is ‘pt’.
adopt_orphan_tick_font (bool | None, optional) – If
True, applyadopt_axis_label_font()before saving so unlabeled axes’ tick labels take the axis-label font, matchingsave_formats(). Mutates the figure (see that function’s Notes). Default isNone— the value is read fromdartwork_mpl.config.adopt_orphan_tick_font(itself defaulting toTrue). PassTrue/Falseexplicitly to override per call.close_figure (bool, optional) – If
True(default), the figure is closed viaplt.close()after saving — matching the historical behaviour, where the function was intended for one-shot “render-then-display” use in notebooks. PassFalseto keep the figure open so you can keep editing it (e.g. add an annotation and resave withsave_formats()).save_formatsitself never closes; this keyword brings parity.**kwargs – Additional keyword arguments passed to
savefig.
- dartwork_mpl.show(image_path: str, size: int = 600, unit: str = 'pt') None[source]¶
Load an SVG image and display it at the specified size in a browser or Jupyter.
- Parameters:
image_path (str) – Path to the SVG image to display.
size (int, optional) – Desired output width. Default is 600.
unit (str, optional) – Unit for the width (‘pt’, ‘px’, etc.). Default is ‘pt’.
- Raises:
ImportError – If IPython is not installed.
showrenders inline in Jupyter via IPython, which is an optional extra — install it withpip install "dartwork-mpl[notebook]".