alphapepttools.pl.add_legend_to_axes

alphapepttools.pl.add_legend_to_axes#

alphapepttools.pl.add_legend_to_axes(ax, levels=None, legend='auto', palette=None, **legend_kwargs)#

Flexibly add a legend to axes with automatic color assignment

Handles multiple legend creation patterns: from a list with palette, from a color dictionary, or using an existing legend object. Automatically switches from qualitative to sequential palette when the number of levels exceeds available colors.

Parameters:
  • ax (Axes) – Matplotlib axes to add the legend to

  • levels (list[str] | dict[str, str | tuple] | None (default: None)) – Either a list of labels (colors assigned from palette) or a dict mapping labels to specific colors

  • legend (str | Legend | None (default: 'auto')) – "auto" creates legend from levels, or pass existing Legend object

  • palette (list[str | tuple] | None (default: None)) – Custom color palette for list-based levels. If None, uses qualitative palette (or sequential if too many levels)

  • **legend_kwargs – Additional arguments for legend (title, loc, fontsize, etc.)

Return type:

None

Examples

List with automatic colors from palette:

# Automatic qualitative palette
levels = ["Control", "Treatment", "Recovery"]
add_legend_to_axes(ax, levels=levels, title="Condition")

# Custom palette
levels = ["WT", "Het", "KO"]
palette = ["blue", "lightblue", "red"]
add_legend_to_axes(ax, levels=levels, palette=palette)

# Many levels trigger sequential palette
levels = [f"Sample_{i}" for i in range(20)]
add_legend_to_axes(ax, levels=levels)  # Switches to sequential

Dict with explicit color mapping:

# Direct color specification
color_dict = {"Significant": "red", "Not significant": "gray", "Borderline": "orange"}
add_legend_to_axes(ax, levels=color_dict, title="Status")

Using existing matplotlib legend:

# Pass pre-created legend
existing_legend = ax.legend(["A", "B"], loc="upper left")
add_legend_to_axes(other_ax, legend=existing_legend)