Skip to content

Label facets

daspi.plotlib.facets.LabelFacets(axes, *, fig_title='', sub_title='', xlabel='', ylabel='', xlabel_formatter=None, ylabel_formatter=None, xlabel_angle=0, ylabel_angle=0, xlabel_align='center', ylabel_align='center', info=False, rows=(), cols=(), row_title='', col_title='', axes_titles=(), legend_data={})

A class for adding labels and titles to facets of a figure with advanced formatting.

This class provides comprehensive labeling and formatting capabilities for matplotlib figures, including support for custom formatters, label rotation, alignment control, and automatic margin adjustment for optimal layout.

PARAMETER DESCRIPTION
axes

A AxesFacets instance containing the subplots' Axes and their arrangement.

TYPE: AxesFacets

fig_title

Main title that should be displayed at the top of the chart, by default ''.

TYPE: str DEFAULT: ''

sub_title

Subtitle, which should appear directly below the main title and slightly smaller than it, by default ''.

TYPE: str DEFAULT: ''

xlabel

The axis label(s) of the figure. To label multiple axes with different names, provide a tuple; otherwise, provide a string, by default ''.

TYPE: str | Tuple[str, ...] DEFAULT: ''

ylabel

The axis label(s) of the figure. To label multiple axes with different names, provide a tuple; otherwise, provide a string, by default ''.

TYPE: str | Tuple[str, ...] DEFAULT: ''

xlabel_formatter

Advanced formatters for axis tick labels with multiple input types:

  • String format templates: Simple format strings using Python's string formatting syntax (e.g., '{:.2f}', '{:.1e}', '${:.0f}', '{:.1%}') for quick and intuitive formatting
  • Callable functions: Custom functions that take one argument (value) or two arguments (value, position) and return formatted strings for complete control
  • Matplotlib Formatters: Any matplotlib.ticker.Formatter instance for advanced formatting scenarios
  • None: Use matplotlib's default formatting

The formatter automatically handles matplotlib compatibility by wrapping simple callables in FuncFormatter and converting string templates to appropriate formatter types. By default, None.

TYPE: Formatter | Callable | str | None DEFAULT: None

ylabel_formatter

Advanced formatters for axis tick labels with multiple input types:

  • String format templates: Simple format strings using Python's string formatting syntax (e.g., '{:.2f}', '{:.1e}', '${:.0f}', '{:.1%}') for quick and intuitive formatting
  • Callable functions: Custom functions that take one argument (value) or two arguments (value, position) and return formatted strings for complete control
  • Matplotlib Formatters: Any matplotlib.ticker.Formatter instance for advanced formatting scenarios
  • None: Use matplotlib's default formatting

The formatter automatically handles matplotlib compatibility by wrapping simple callables in FuncFormatter and converting string templates to appropriate formatter types. By default, None.

TYPE: Formatter | Callable | str | None DEFAULT: None

xlabel_angle

Rotation angle for x and y axis tick labels in degrees. Positive values rotate counter-clockwise, negative values rotate clockwise. The chart automatically adjusts margins to accommodate rotated labels and prevent clipping. Common values: 0 (horizontal), 45 (diagonal), 90 (vertical). By default, 0.

TYPE: float DEFAULT: 0

ylabel_angle

Rotation angle for x and y axis tick labels in degrees. Positive values rotate counter-clockwise, negative values rotate clockwise. The chart automatically adjusts margins to accommodate rotated labels and prevent clipping. Common values: 0 (horizontal), 45 (diagonal), 90 (vertical). By default, 0.

TYPE: float DEFAULT: 0

xlabel_align

Alignment for x and y axis tick labels relative to their tick marks:

  • For x-axis: 'left', 'center', 'right' control horizontal alignment of the label text relative to the tick position
  • For y-axis: 'bottom', 'center', 'top' control vertical alignment, where the string values map to vertical alignment for better API consistency

Alignment is particularly useful with rotated labels to achieve optimal positioning and readability. By default, 'center'.

TYPE: str DEFAULT: 'center'

ylabel_align

Alignment for x and y axis tick labels relative to their tick marks:

  • For x-axis: 'left', 'center', 'right' control horizontal alignment of the label text relative to the tick position
  • For y-axis: 'bottom', 'center', 'top' control vertical alignment, where the string values map to vertical alignment for better API consistency

Alignment is particularly useful with rotated labels to achieve optimal positioning and readability. By default, 'center'.

TYPE: str DEFAULT: 'center'

info

Indicates whether to include an info text at the lower left corner in the figure. If True, the date and user are automatically added. If a string is provided, it's appended to the automatic date/user information, separated by a comma. By default, False.

TYPE: bool or str DEFAULT: False

rows

The row labels of the figure for faceted plots, by default ().

TYPE: Tuple[str, ...] DEFAULT: ()

cols

The column labels of the figure for faceted plots, by default ().

TYPE: Tuple[str, ...] DEFAULT: ()

row_title

The title of the rows for faceted plots, by default ''.

TYPE: str DEFAULT: ''

col_title

The title of the columns for faceted plots, by default ''.

TYPE: str DEFAULT: ''

axes_titles

Title for each Axes, useful for JointCharts with multiple subplots, by default ().

TYPE: Tuple[str, ...] DEFAULT: ()

legend_data

The legends to be added to the figure. The key is used as the legend title, and the values must be a tuple of tuples, where the inner tuple contains a handle as a Patch or Line2D artist and a label as a string, by default {}.

TYPE: Dict[str, LegendHandlesLabels] DEFAULT: {}

Examples:

Basic usage with string formatters:

axes = AxesFacets(nrows=1, ncols=1)
label_facets = LabelFacets(
    axes=axes,
    fig_title='Temperature Analysis',
    xlabel='Time (hours)',
    ylabel='Temperature',
    ylabel_formatter='{:.1f}°C',  # String template
    xlabel_formatter='{:.0f}h'    # String template
)
label_facets.draw()

Custom callable formatters:

def scientific_formatter(value):
    if abs(value) >= 1000:
        return f'{value:.1e}'
    return f'{value:.2f}'

label_facets = LabelFacets(
    axes=axes,
    ylabel_formatter=scientific_formatter,
    xlabel_formatter=lambda x: f'${x:,.0f}'  # Lambda formatter
)

Rotation and alignment for readability:

label_facets = LabelFacets(
    axes=axes,
    xlabel='Product Categories',
    xlabel_angle=45,      # Diagonal rotation
    xlabel_align='right', # Right-align for better rotation appearance
    ylabel_formatter='{:.1%}'  # Percentage format
)

Advanced faceted plot labeling:

label_facets = LabelFacets(
    axes=multi_axes,
    fig_title='Sales Analysis by Region',
    sub_title='Q3 2024 Performance',
    row_title='Geographic Region',
    col_title='Product Category',
    rows=('North', 'South', 'East', 'West'),
    cols=('Electronics', 'Clothing', 'Books'),
    xlabel_formatter='${:,.0f}',
    ylabel_formatter='{:.1f}%',
    info='Source: Sales database'
)
Notes
  • String formatters are automatically converted to matplotlib-compatible formatters using intelligent type detection.
  • Margins are automatically adjusted when using rotated labels to prevent clipping and ensure optimal layout.
  • The class handles both single axes and complex multi-axes layouts.
  • All formatting options work consistently across different matplotlib backends and figure configurations.
  • Legend positioning is automatically calculated to avoid overlapping with other chart elements.

axes = axes instance-attribute

A AxesFacets instance containing the subplots' Axes and their arrangement.

figure = self.axes.figure instance-attribute

The figure instance to label.

fig_title = fig_title instance-attribute

The title to display at the top of the chart.

sub_title = sub_title instance-attribute

The subtitle to display directly below the title of the chart.

xlabel = xlabel instance-attribute

The x-axis label(s) of the figure.

ylabel = ylabel instance-attribute

The y-axis label(s) of the figure.

xlabel_formatter = self._prepare_formatter(xlabel_formatter) instance-attribute

Function to format the x-axis tick labels.

ylabel_formatter = self._prepare_formatter(ylabel_formatter) instance-attribute

Function to format the y-axis tick labels.

xlabel_angle = xlabel_angle instance-attribute

Rotation angle for x-axis tick labels in degrees.

ylabel_angle = ylabel_angle instance-attribute

Rotation angle for y-axis tick labels in degrees.

xlabel_align = xlabel_align instance-attribute

Alignment for x-axis tick labels.

ylabel_align = ylabel_align instance-attribute

Alignment for y-axis tick labels.

rows = rows instance-attribute

The row labels of the figure.

cols = cols instance-attribute

The column labels of the figure.

row_title = row_title instance-attribute

The title of the rows.

col_title = col_title instance-attribute

The title of the columns.

axes_titles = axes_titles instance-attribute

The titles of each axes.

info = info instance-attribute

Indicates whether to include an info text in the figure.

legend_data = legend_data instance-attribute

The legend_data to be added to the figure.

labels = {} instance-attribute

The labels that were added to the image as text objects.

x_aligned property

Get aligned x position as fraction of figure width. This is used for title, subtitle and info (read-only).

margin_rectangle property

Get rectangle of margins around the subplots used for the additional labels as fraction of figure size (read-only).

legend_fraction property

Get fraction of figure size for legend (read-only).

legend property

Get legend added to figure (read-only).

legend_artists property

Get legend artists (read-only).

legend_width property

Get width of legend in pixels (read-only).

estimate_height(text) staticmethod

Get the estimated size of the text in the figure in pixels.

This method estimates the height of a text object in pixels based on its font size, the number of lines it contains, and the figure's DPI. It calculates the line height using the font size and a constant PPI (pixels per inch), then multiplies by the number of lines to get the total height, and adds padding to account for spacing between lines and around the text.

PARAMETER DESCRIPTION
text

The text object for which to estimate the height.

TYPE: Text

RETURNS DESCRIPTION
int

The estimated height of the text in pixels.

estimate_rotation_margin(angle_degrees, base_margin=25) staticmethod

Estimate additional margin needed for rotated tick labels.

PARAMETER DESCRIPTION
angle_degrees

Rotation angle in degrees

TYPE: float

base_margin

Base margin for calculating rotated label space, by default 25

TYPE: int DEFAULT: 25

RETURNS DESCRIPTION
int

Additional margin in pixels needed for the rotation

get_legend_artists(legend) staticmethod

Get the inner children of a legend.

PARAMETER DESCRIPTION
legend

The legend object.

TYPE: Legend

RETURNS DESCRIPTION
List[Artist]:

The artists representing the inner children of the legend.

not_shared(axis) staticmethod

Check if an axis is not shared.

clear()

Remove all the label facets.

draw()

Draw all the label facets to the figure.