kdiagram.utils.savefig¶
- kdiagram.utils.savefig(savefig, fig_or_ax=None, *, dpi=300, bbox_inches='tight', pad_inches=0.2, facecolor=None, edgecolor=None, overwrite=False, error='warn', close='auto', **kwargs)[source]¶
Save a Matplotlib figure robustly.
This helper wraps
Figure.savefigwith safe path handling, directory creation, unique file naming, and optional smart figure closing. It can also save the current active figure when noFigureorAxesis provided.- Parameters:
- savefig
strorPathorNone Target path. If
None, nothing is saved andNoneis returned. If a directory is given (or the string ends with'/'or'\\'), a default filename'figure.png'is used inside that directory. If no extension is present,.pngis assumed.- fig_or_ax
FigureorAxesorNone,optional A Matplotlib
FigureorAxesto save. If anAxesis passed, its parent figure is used. IfNone, the helper tries to resolve the most recently active figure (see Notes). If no figure is active, a warning is issued andNoneis returned.- dpi
int, default=300 Resolution passed to
Figure.savefig.- bbox_inches
str, default=’tight’ Bounding box option forwarded to
Figure.savefig.- pad_inches
float, default=0.2 Padding when
bbox_inches='tight'.- facecolor, edgecolor
Any,optional Colors forwarded to
Figure.savefig.- overwritebool, default=False
If
True, overwrite an existing file. IfFalse, create a unique name by appending' (1)',' (2)', … before the extension.- error{‘warn’, ‘raise’, ‘ignore’}, default=’warn’
How to handle I/O errors (directory creation or disk write).
'warn'emits aUserWarningand returnsNoneon failure;'raise're-raises;'ignore'quietly returnsNone.- close{‘auto’,
True,False}, default=’auto’ Figure closing policy after a successful save.
'auto': close only if the figure was auto-fetched (i.e.,fig_or_axwasNoneand an existing active figure was used). This is convenient when callingkd.savefig(...)at top level.True: always close the figure that was saved, regardless of how it was obtained (explicit or auto-fetched).False: never close the figure; the caller manages figure lifecycle.
- **kwargs
Additional keyword arguments are forwarded to
Figure.savefig.
- savefig
- Returns:
PathorNoneThe final saved path as a
pathlib.Pathwhen successful; otherwiseNone(e.g.,savefig is Noneor no active figure was found).
- Parameters:
- Return type:
Path | None
Notes
If
fig_or_axisNone, the helper resolves the last active figure usingmatplotlib.pyplot.get_fignumsandmatplotlib.pyplot.figure. If no figures exist, a warning is emitted andNoneis returned.When
overwriteisFalseand the target exists, the helper creates a unique filename by appending a space and a counter in parentheses before the extension.If the figure uses constrained layout, the helper will not call
tight_layout; otherwise it appliestight_layoutbefore saving to reduce label overlap.To avoid external labels being cropped when using
bbox_inches='tight', prefer placing labels inside axes, or use figure-level labels (e.g.,Figure.suptitle,Figure.supylabel).This function does not create an empty figure; it only saves an existing one.
References
[1]Matplotlib Figure.savefig documentation.
[2]Matplotlib tight_layout and constrained_layout guides.
[3]Python pathlib documentation for path handling.
Examples
Save the current active figure and auto-close it:
import matplotlib.pyplot as plt import kdiagram as kd plt.plot([0, 1], [0, 1]) kd.savefig("out/line.png") # auto-fetched, then closed
Save an explicit figure and keep it open:
fig, ax = plt.subplots() ax.plot([0, 1], [1, 0]) kd.savefig("results/plot.png", fig, close=False)
Ensure overwrite and force close:
kd.savefig("results/plot.png", fig, overwrite=True, close=True)
Save from an Axes object (parent figure is used):
kd.savefig("results/axes_plot.png", ax)
Let the helper pick a default filename in a directory path:
kd.savefig("results/") # creates results/figure.png (or figure (1).png)