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.savefig with safe path handling, directory creation, unique file naming, and optional smart figure closing. It can also save the current active figure when no Figure or Axes is provided.

Parameters:
savefigstr or Path or None

Target path. If None, nothing is saved and None is 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, .png is assumed.

fig_or_axFigure or Axes or None, optional

A Matplotlib Figure or Axes to save. If an Axes is passed, its parent figure is used. If None, the helper tries to resolve the most recently active figure (see Notes). If no figure is active, a warning is issued and None is returned.

dpiint, default=300

Resolution passed to Figure.savefig.

bbox_inchesstr, default=’tight’

Bounding box option forwarded to Figure.savefig.

pad_inchesfloat, default=0.2

Padding when bbox_inches='tight'.

facecolor, edgecolorAny, optional

Colors forwarded to Figure.savefig.

overwritebool, default=False

If True, overwrite an existing file. If False, 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 a UserWarning and returns None on failure; 'raise' re-raises; 'ignore' quietly returns None.

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_ax was None and an existing active figure was used). This is convenient when calling kd.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.

Returns:
Path or None

The final saved path as a pathlib.Path when successful; otherwise None (e.g., savefig is None or no active figure was found).

Parameters:
Return type:

Path | None

Notes

  • If fig_or_ax is None, the helper resolves the last active figure using matplotlib.pyplot.get_fignums and matplotlib.pyplot.figure. If no figures exist, a warning is emitted and None is returned.

  • When overwrite is False and 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 applies tight_layout before 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)