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 tolevels (
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 colorslegend (
str|Legend|None(default:'auto')) –"auto"creates legend from levels, or pass existing Legend objectpalette (
list[str|tuple] |None(default:None)) – Custom color palette for list-based levels. IfNone, uses qualitative palette (or sequential if too many levels)**legend_kwargs – Additional arguments for legend (title, loc, fontsize, etc.)
- Return type:
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)