corems.encapsulation.plot_utils

Shared plotting helpers for CoreMS figure lifecycle management.

 1"""Shared plotting helpers for CoreMS figure lifecycle management."""
 2
 3from __future__ import annotations
 4
 5import matplotlib.pyplot as plt
 6
 7
 8def _finalize_plot(fig, return_fig=False, path=None, **savefig_kwargs):
 9    """Shared exit path for CoreMS plot methods that support ``return_fig``.
10
11    Parameters
12    ----------
13    fig : matplotlib.figure.Figure
14        Figure to finalize.
15    return_fig : bool, optional
16        If True, leave the figure open and return it. The caller owns the
17        figure lifecycle (e.g. further customization or ``plt.close(fig)``).
18        Default is False.
19    path : str or path-like, optional
20        If set, save the figure to this path via ``fig.savefig`` before
21        showing or returning.
22    **savefig_kwargs
23        Forwarded to ``fig.savefig`` when ``path`` is set.
24
25    Returns
26    -------
27    matplotlib.figure.Figure or None
28        The open figure if ``return_fig`` is True; otherwise None.
29
30    Notes
31    -----
32    Behavior matrix:
33
34    - ``return_fig=False``, ``path=None``: call ``plt.show()`` (interactive /
35      notebook default).
36    - ``return_fig=False``, ``path`` set: save, close the figure, do **not**
37      call ``plt.show()`` (batch / headless friendly).
38    - ``return_fig=True``: optionally save if ``path`` is set; return the open
39      figure without showing or closing it.
40    """
41    if path is not None:
42        fig.savefig(path, **savefig_kwargs)
43
44    if return_fig:
45        return fig
46
47    if path is None:
48        plt.show()
49    else:
50        plt.close(fig)
51    return None