publiplots.LegendBuilder#
- class publiplots.LegendBuilder(ax, x_offset=2, y_offset=None, gap=2, column_spacing=5, vpad=None, max_width=None, anchor_ax=None, external_to_axis=False, side='right', orientation='vertical')[source]#
Publication-ready legend builder with automatic column overflow.
All dimensions are in millimeters for precise positioning in publication-quality plots. The builder automatically creates new columns when vertical space is exhausted.
This is the primary interface for creating legends in publiplots.
- Parameters:
ax (Axes) – Main plot axes to attach legends to.
x_offset (float, default=2) – Horizontal distance from the right edge of axes (millimeters).
y_offset (float, optional) – Vertical position from top of axes (millimeters). If None, starts at axes height minus vpad.
gap (float, default=2) – Vertical spacing between legend elements (millimeters).
column_spacing (float, default=5) – Horizontal spacing between columns (millimeters).
vpad (float, default=5) – Padding from top of axes (millimeters).
max_width (float, optional) – Maximum width for legends (millimeters). If None, auto-estimated from content.
Examples
>>> ax = pp.scatterplot(df, x='x', y='y', hue='group', legend=False) >>> builder = pp.legend(ax, auto=False, x_offset=2, gap=2) >>> builder.add_legend(handles, label="Treatment") >>> builder.add_colorbar(mappable, label="Expression", height=15)
Notes
All dimensions are in millimeters. New columns are created automatically when vertical space is exhausted.
- __init__(ax, x_offset=2, y_offset=None, gap=2, column_spacing=5, vpad=None, max_width=None, anchor_ax=None, external_to_axis=False, side='right', orientation='vertical')[source]#
Initialize legend builder. All dimensions in millimeters.
- Parameters:
ax (Axes) – Axes the legend/colorbar artist is attached to (for picking,
ax.legend_association, etc.).anchor_ax (Axes, optional) – Axes whose chosen edge is used as the origin for mm-based placement math and for reactor registration. Defaults to
ax. Used by MultiAxesLegendGroup to attach artists to one axes while positioning them relative to another (or to a virtual grid anchor for figure-anchored groups).side ({'right', 'left', 'bottom', 'top'}, default 'right') – Which edge of
anchor_axthe legend grows outward from. ‘right’ matches the historical placement (columns fill rightward, rows downward).orientation ({'vertical', 'horizontal'}, default 'vertical') – Primary stacking direction of successive legends and of entries within each legend.
'vertical'stacks entries downward and advances successive legends downward; overflow (exhausted along-edge length) starts a new band outward.'horizontal'lays entries along the edge (defaultncol = len(handles)) and advances successive legends rightward; overflow starts a new band further outward.
Methods
__init__(ax[, x_offset, y_offset, gap, ...])Initialize legend builder.
add_colorbar([mappable, cmap, vmin, vmax, ...])Add a colorbar with automatic overflow handling.
add_legend(handles[, label, frameon, max_height])Add a legend with automatic overflow handling.
add_legend_for(type[, label])Add legend by auto-detecting from self.ax stored metadata.
Get remaining vertical space.
Attributes
- MM2INCH = 0.03937007874015748#
- PT2MM = 0.35277777777777775#
- add_legend(handles, label='', frameon=False, max_height=None, **kwargs)[source]#
Add a legend with automatic overflow handling.
Creates a new column automatically if the legend doesn’t fit in the current vertical space.
- Parameters:
handles (list) – Legend handles (from create_legend_handles or plot objects).
label (str) – Legend title.
frameon (bool) – Whether to show frame around legend.
max_height (float, optional) – Maximum height in millimeters. If legend exceeds this, increase ncol to fit (PyComplexHeatmap behavior).
**kwargs – Additional kwargs for legend customization.
inside(bool, defaultFalse) bypasses the mm-based outside-axes column and renders the legend inside the axes using matplotlib’s native axes-relative placement; pair withloc='upper right'etc. to pick the corner. The rest (ncol,labelspacing,handletextpad,columnspacing, etc.) are forwarded toax.legend().
- Returns:
The created legend object.
- Return type:
Legend
Notes
All dimensions in millimeters. Columns created automatically on overflow.
- add_colorbar(mappable=None, cmap=None, vmin=None, vmax=None, center=None, label='', height=None, width=None, title_position='top', orientation=None, ticks=None, **kwargs)[source]#
Add a colorbar with automatic overflow handling.
Supports both ScalarMappable input (standard matplotlib) and direct colormap specification (PyComplexHeatmap style).
- Parameters:
mappable (ScalarMappable, optional) – Existing ScalarMappable object (standard matplotlib usage).
cmap (str, optional) – Colormap name (alternative to mappable, PyComplexHeatmap style). If provided, creates ScalarMappable internally.
vmin (float, optional) – Value range for colormap (used with cmap parameter).
vmax (float, optional) – Value range for colormap (used with cmap parameter).
center (float, optional) – Center value for divergent colormaps. Uses TwoSlopeNorm for proper centering (e.g., 0 for red-white-blue).
label (str) – Colorbar label/title.
height (float, optional) – Colorbar height (the vertical extent) in millimeters. The meaning is literal at every orientation; only the default follows it — 15 for a vertical strip, 4.5 for a horizontal one.
width (float, optional) – Colorbar width (the horizontal extent) in millimeters. Literal at every orientation, like
height; defaults to 4.5 for a vertical strip and 15 for a horizontal one.title_position ({'top', 'right'}, default='top') – Position of title. ‘top’ places label above colorbar (horizontal), ‘right’ uses matplotlib default (vertical).
orientation ({'vertical', 'horizontal'}, optional) – Colorbar orientation.
None(default) derives it from the band it lands in: horizontal on aside='top'/'bottom'band, vertical on'left'/'right'. An explicit value always wins.ticks (list of float, optional) – Custom tick positions. If None and center is provided, automatically sets ticks at [vmin, center, vmax].
**kwargs – Additional kwargs passed to fig.colorbar().
inside(bool, defaultFalse) bypasses the mm-based outside-axes band and renders the strip inside the axes rectangle, mirroringadd_legend(inside=True); pair withloc='upper right'etc. to pick the corner.loctakes the nine position stringsax.legend()accepts, the bare'right'alias, and matplotlib’s integer codes 0-10, and resolves each to the corner the categorical legend would use.'best'/0has no meaning for a strip and resolves to'upper right'.height/widthkeep their mm meaning there, and the strip is excluded from layout math.
- Returns:
The created colorbar object.
- Return type:
Colorbar
Notes
All dimensions in millimeters. Columns created automatically on overflow.
Examples
Standard matplotlib style: >>> builder.add_colorbar(sm, label=”Values”, height=20)
PyComplexHeatmap style with divergent colormap: >>> builder.add_colorbar( … cmap=’RdBu_r’, vmin=-2, vmax=2, center=0, … label=”Log2 FC”, ticks=[-2, 0, 2] … )
- add_legend_for(type, label=None, **kwargs)[source]#
Add legend by auto-detecting from self.ax stored metadata.
- Parameters:
Examples
>>> builder = pp.legend(ax, auto=False) >>> builder.add_legend_for('hue', label='Groups') >>> builder.add_legend_for('size', label='Magnitude') >>> builder.add_legend_for('hue', label='Score') # Works for colorbar too