Figure Creation

Enhanced figure and subplot creation functions that integrate with dartwork-mpl’s style system and Zero-Resize Policy.

Overview

The figure creation functions in dartwork-mpl provide drop-in replacements for matplotlib’s plt.figure() and plt.subplots() with additional features:

  • Style Integration: Apply styles directly during figure creation

  • Zero-Resize Policy: Figure size and DPI are determined by the active style

  • GridSpec Support: Built-in support for complex layouts with ratio control

  • Consistent Defaults: Sensible defaults for publication-quality figures

Zero-Resize Policy

When using dartwork-mpl’s figure creation functions with a style parameter, the figure size and DPI are determined by the style unless explicitly overridden. This ensures consistency across all figures using the same style.

import dartwork_mpl as dm

# Size determined by 'scientific' style
fig, ax = dm.subplots(style='scientific')

# Override style's figsize while keeping other style settings
fig, ax = dm.subplots(style='scientific', figsize=(10, 6))

API Reference

dartwork_mpl.subplots(nrows: int = 1, ncols: int = 1, *, style: str | list[str] | None = None, figsize: tuple[float, float] | None = None, dpi: int | None = None, sharex: bool | Literal['none', 'all', 'row', 'col'] = False, sharey: bool | Literal['none', 'all', 'row', 'col'] = False, squeeze: bool = True, width_ratios: list[float] | None = None, height_ratios: list[float] | None = None, subplot_kw: dict[str, Any] | None = None, gridspec_kw: dict[str, Any] | None = None, **fig_kw: Any) tuple[Figure, Axes | ndarray][source]

Create a figure and a set of subplots with optional style application.

This is a wrapper around matplotlib.pyplot.subplots that integrates with dartwork-mpl’s style system. It allows applying styles directly when creating the figure, following the “Zero-Resize Policy” where figsize and dpi can be determined by the style.

Parameters:
  • nrows (int, optional) – Number of rows of the subplot grid.

  • ncols (int, optional) – Number of columns of the subplot grid.

  • style (str | list[str] | None, optional) – Style preset(s) to apply. Can be a single style name or a list of styles to stack. If None, uses current matplotlib style. Examples: ‘scientific’, ‘report-kr’, [‘font-libertine’, ‘color-pro’]

  • figsize (tuple[float, float] | None, optional) – Figure dimension (width, height) in inches. If None and a style is specified, uses the style’s default figsize.

  • dpi (int | None, optional) – Dots per inch. If None and a style is specified, uses the style’s default dpi.

  • sharex (bool | str, optional) – Controls sharing of x-axis among subplots.

  • sharey (bool | str, optional) – Controls sharing of y-axis among subplots.

  • squeeze (bool, optional) – If True, single Axes object is returned if nrows=ncols=1. If False, always returns 2D array of Axes.

  • width_ratios (list[float] | None, optional) – Width ratios of the columns. Length must equal ncols.

  • height_ratios (list[float] | None, optional) – Height ratios of the rows. Length must equal nrows.

  • subplot_kw (dict | None, optional) – Dict with keywords passed to add_subplot for each subplot.

  • gridspec_kw (dict | None, optional) – Dict with keywords passed to GridSpec constructor.

  • **fig_kw (Any) – Additional keyword arguments passed to plt.figure().

Returns:

  • fig (Figure) – The created figure.

  • ax (Axes or array of Axes) – Single Axes object or array of Axes objects. The shape depends on nrows, ncols, and squeeze parameters.

Examples

Create a simple figure with scientific style:

>>> fig, ax = dm.subplots(style='scientific')
>>> ax.plot(x, y)

Create a 2x2 grid with custom style stack:

>>> fig, axes = dm.subplots(2, 2, style=['font-libertine', 'color-pro'])
>>> for ax in axes.flat:
...     ax.plot(x, y)

Create with specific size overriding style defaults:

>>> fig, ax = dm.subplots(style='report', figsize=(8, 6), dpi=150)

Create with shared axes:

>>> fig, axes = dm.subplots(3, 1, style='scientific', sharex=True)

Notes

This function follows dartwork-mpl’s “Zero-Resize Policy”: when a style is provided, you don’t need to specify figsize or dpi unless you want to override the style’s defaults. This ensures consistent sizing across your visualizations.

The style is applied before creating the figure, so all matplotlib elements created within the figure will inherit the style properties.

dartwork_mpl.figure(*, style: str | list[str] | None = None, figsize: tuple[float, float] | None = None, dpi: int | None = None, **kwargs: Any) Figure[source]

Create a figure with optional style application.

This is a wrapper around matplotlib.pyplot.figure that integrates with dartwork-mpl’s style system.

Parameters:
  • style (str | list[str] | None, optional) – Style preset(s) to apply.

  • figsize (tuple[float, float] | None, optional) – Figure dimension (width, height) in inches.

  • dpi (int | None, optional) – Dots per inch.

  • **kwargs (Any) – Additional keyword arguments passed to plt.figure().

Returns:

The created figure.

Return type:

Figure

Examples

>>> fig = dm.figure(style='report')
>>> ax = fig.add_subplot(111)
>>> ax.plot(x, y)

Examples

Basic Usage

import dartwork_mpl as dm
import numpy as np

# Create figure with scientific style
fig, ax = dm.subplots(style='scientific')

# Plot data
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x))
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')

dm.simple_layout(fig)
plt.show()

Multiple Subplots

# Create 2x2 grid with shared axes
fig, axes = dm.subplots(2, 2,
                        style='report',
                        sharex=True,
                        sharey=True)

for i, ax in enumerate(axes.flat):
    ax.plot(np.random.randn(100))
    ax.set_title(f'Panel {i+1}')

dm.simple_layout(fig)

Complex Layouts with Ratios

# Create subplots with custom width and height ratios
fig, axes = dm.subplots(2, 3,
                        style='presentation',
                        width_ratios=[1, 2, 1],
                        height_ratios=[2, 1])

# axes is a 2x3 array
# First row has twice the height of second row
# Middle column has twice the width of side columns

Stacking Multiple Styles

# Apply multiple styles in sequence
fig, ax = dm.subplots(style=['font-libertine', 'theme-dark', 'preset-slides'])

# Equivalent to:
# dm.style.use(['font-libertine', 'theme-dark', 'preset-slides'])
# fig, ax = plt.subplots()

Style-Specific Figure Sizes

Different styles define different default figure sizes:

# Scientific papers (typically 3.5" single column)
fig, ax = dm.subplots(style='scientific')  # ~3.5" wide

# Reports (typically 6" wide)
fig, ax = dm.subplots(style='report')  # ~6" wide

# Web graphics (typically 8" wide)
fig, ax = dm.subplots(style='web')  # ~8" wide

# Presentations (typically 10" wide)
fig, ax = dm.subplots(style='presentation')  # ~10" wide

Integration with Layout Functions

The figure creation functions work seamlessly with dartwork-mpl’s layout utilities:

fig, axes = dm.subplots(2, 2, style='scientific')

for ax in axes.flat:
    ax.plot(np.random.randn(100))
    ax.set_xlabel('Time')
    ax.set_ylabel('Value')

# Apply consistent layout
dm.simple_layout(fig)

# Or use auto-layout for content-aware margins
dm.auto_layout(fig)

GridSpec Integration

For advanced layouts, GridSpec parameters are fully supported:

fig, axes = dm.subplots(3, 3,
                        style='report',
                        gridspec_kw={
                            'hspace': 0.3,
                            'wspace': 0.4,
                            'left': 0.1,
                            'right': 0.95
                        })

Figure-Only Creation

Use dm.figure() when you need a figure without subplots:

# Create empty figure with style
fig = dm.figure(style='scientific')

# Add custom axes manually
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)

# Or use add_axes for precise control
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

Best Practices

  1. Always use style parameter for consistency:

    # Good: style applied at creation
    fig, ax = dm.subplots(style='scientific')
    
    # Less ideal: style applied separately
    dm.style.use('scientific')
    fig, ax = plt.subplots()
    
  2. Let styles control figure size unless you have specific requirements:

    # Good: use style's default size
    fig, ax = dm.subplots(style='report')
    
    # Only override when necessary
    fig, ax = dm.subplots(style='report', figsize=(8, 4))  # Custom aspect ratio
    
  3. Use width/height ratios instead of manual GridSpec for simple cases:

    # Simple and clear
    fig, axes = dm.subplots(1, 3, width_ratios=[1, 2, 1])
    
    # More complex, only when needed
    gs = fig.add_gridspec(1, 3, width_ratios=[1, 2, 1])
    axes = [fig.add_subplot(gs[0, i]) for i in range(3)]
    

Differences from Matplotlib

The main differences from matplotlib’s figure creation functions:

  1. Style parameter: Apply styles directly during creation

  2. Zero-Resize Policy: Style determines size unless overridden

  3. Enhanced defaults: Better default spacing and margins

  4. Automatic imports: No need to import matplotlib.pyplot

Migration from Matplotlib

Migrating from matplotlib is straightforward:

# Matplotlib approach
import matplotlib.pyplot as plt

plt.style.use('seaborn')
fig, ax = plt.subplots(figsize=(8, 6), dpi=100)

# dartwork-mpl approach
import dartwork_mpl as dm

fig, ax = dm.subplots(style='scientific', figsize=(8, 6), dpi=100)

See Also