publiplots.legend

publiplots.legend(ax=None, handles=None, labels=None, auto=True, x_offset=2, gap=2, column_spacing=5, vpad=5, **kwargs)[source]

Create publication-ready legends with automatic positioning.

All dimensions in millimeters for precise control in publication plots. Returns LegendBuilder for adding multiple legends with automatic column overflow handling.

This is the primary interface for legend creation in publiplots.

Parameters:
  • ax (Axes, optional) – Axes to create legend for. If None, uses plt.gca() (current axes).

  • handles (list, optional) – Manual legend handles. If provided, auto is ignored.

  • labels (list, optional) – Manual legend labels (used with handles).

  • auto (bool, default=True) – If True, auto-creates all legends from metadata stored on plot objects. If False, returns empty builder for manual control.

  • x_offset (float, default=2) – Horizontal distance from right edge of axes (millimeters).

  • gap (float, default=2) – Vertical spacing between legend elements (millimeters).

  • column_spacing (float, default=5) – Horizontal spacing between columns (millimeters).

  • vpad (float, default=5) – Top padding from axes edge (millimeters).

  • **kwargs – Additional kwargs passed to add_legend() if handles provided, or legend customization options.

Returns:

Builder object for adding more legends.

Return type:

LegendBuilder

Examples

Auto mode (no axes needed, uses current axes): >>> fig, ax = pp.scatterplot(df, x=’x’, y=’y’, hue=’group’, legend=False) >>> builder = pp.legend() # Auto-creates legends on current axes

Auto mode with explicit axes: >>> builder = pp.legend(ax) # Auto-creates legends

Manual sequential mode: >>> builder = pp.legend(auto=False, x_offset=3, gap=3) >>> builder.add_legend(hue_handles, label=”Treatment”) >>> builder.add_colorbar(cmap=’RdBu_r’, vmin=-2, vmax=2, center=0, … label=”Log2 FC”, height=20) >>> builder.add_legend(marker_handles, label=”Cell Type”)

Manual handles mode: >>> builder = pp.legend(handles=custom_handles, labels=custom_labels, … label=’My Legend’)

Notes

All dimensions are in millimeters. New columns are created automatically when vertical space is exhausted. This ensures legends never overlap with the plot area and maintains consistent spacing for publication-quality figures.

Multiple calls to legend() on the same axes will reuse the same LegendBuilder, allowing legends to stack properly without overriding each other.