Skip to content

LegendTracker

yohou.plotting.LegendTracker

Track which legend entries have been shown to avoid duplicates.

In panel / faceted figures the same logical trace (e.g. a member named "sales") appears in multiple subplots. Only the first occurrence should carry showlegend=True; subsequent ones must set showlegend=False while sharing the same legendgroup.

Parameters

Name Type Description Default
show_legend bool

Global override. When False, should_show always returns False regardless of whether the name has been seen.

True

Examples

>>> tracker = LegendTracker()
>>> tracker.should_show("sales")
True
>>> tracker.should_show("sales")
False
>>> tracker.should_show("demand")
True
>>> tracker_off = LegendTracker(show_legend=False)
>>> tracker_off.should_show("sales")
False

Source Code

Source code in src/yohou/plotting/_utils.py
class LegendTracker:
    """Track which legend entries have been shown to avoid duplicates.

    In panel / faceted figures the same logical trace (e.g. a member
    named ``"sales"``) appears in multiple subplots.  Only the first
    occurrence should carry ``showlegend=True``; subsequent ones must
    set ``showlegend=False`` while sharing the same ``legendgroup``.

    Parameters
    ----------
    show_legend : bool, default=True
        Global override.  When ``False``, `should_show` always
        returns ``False`` regardless of whether the name has been seen.

    Examples
    --------
    >>> tracker = LegendTracker()
    >>> tracker.should_show("sales")
    True
    >>> tracker.should_show("sales")
    False
    >>> tracker.should_show("demand")
    True

    >>> tracker_off = LegendTracker(show_legend=False)
    >>> tracker_off.should_show("sales")
    False
    """

    def __init__(self, show_legend: bool = True) -> None:
        self._seen: set[str] = set()
        self._show_legend = show_legend

    def should_show(self, name: str) -> bool:
        """Return ``True`` the first time *name* is passed (and legend is on)."""
        if not self._show_legend:
            return False
        first_seen = name not in self._seen
        self._seen.add(name)
        return first_seen

Methods

should_show(name)

Return True the first time name is passed (and legend is on).

Source Code
Source code in src/yohou/plotting/_utils.py
def should_show(self, name: str) -> bool:
    """Return ``True`` the first time *name* is passed (and legend is on)."""
    if not self._show_legend:
        return False
    first_seen = name not in self._seen
    self._seen.add(name)
    return first_seen