FigRecipe API Reference

figrecipe - Record and reproduce matplotlib figures.

A lightweight library for capturing matplotlib plotting calls and reproducing figures from saved recipes.

Usage

>>> import figrecipe as fr
>>> fig, ax = fr.subplots()
>>> ax.plot(x, y, id='my_data')
>>> fr.save(fig, 'recipe.yaml')

Examples

Recording a figure:

>>> import figrecipe as fr
>>> import numpy as np
>>>
>>> x = np.linspace(0, 10, 100)
>>> y = np.sin(x)
>>>
>>> fig, ax = fr.subplots()
>>> ax.plot(x, y, color='red', linewidth=2, id='sine_wave')
>>> ax.set_xlabel('Time')
>>> ax.set_ylabel('Amplitude')
>>> fr.save(fig, 'my_figure.yaml')

Reproducing a figure:

>>> fig, ax = fr.reproduce('my_figure.yaml')
>>> plt.show()
  • fr.utils: Unit conversions, font checks, low-level recipe access

  • fr.styles: Axis helpers, spine management, plot styling functions

  • fr.viz: Diagram and graph visualization utilities

>>> from figrecipe import utils
>>> utils.mm_to_inch(25.4)  # Unit conversions
>>> from figrecipe import styles
>>> styles.hide_spines(ax)  # Spine management
class figrecipe.Figz(path)[source]

Bases: object

Multi-panel figure bundle (.fig.zip).

Manages a ZIP file containing:

manifest.json - bundle type declaration spec.json - figure spec with panel list style.json - figure dimensions and theme panels/ - .plt.zip panel bundles

Example

>>> figz = Figz.create("Figure1.fig.zip", "Figure1")
>>> figz.add_panel("A", pltz_path)
>>> figz.add_panel("B", pltz_bytes)
__init__(path)[source]
classmethod create(path, name, size_mm=None)[source]

Create a new empty .fig.zip bundle.

Parameters:
  • path (str or Path) – Output path (should end in .fig.zip).

  • name (str) – Figure name / ID.

  • size_mm (dict, optional) – Canvas size e.g. {“width_mm”: 170, “height_mm”: 120}.

Returns:

Loaded Figz instance.

Return type:

Figz

save()[source]

Save spec/style changes back to bundle.

Return type:

None

add_panel(label, pltz_source, position=None, size=None)[source]

Add a .plt.zip panel to this figure.

Parameters:
  • label (str) – Panel label (e.g., “A”, “B”).

  • pltz_source (bytes, str, or Path) – Panel bytes or path to a .plt.zip file.

  • position (dict, optional) – Panel position e.g. {“x_mm”: 5, “y_mm”: 5}.

  • size (dict, optional) – Panel size e.g. {“width_mm”: 80, “height_mm”: 68}.

Return type:

None

add_panel_from_png(label, png_bytes, plot_type='image', position=None, size=None, hitmap_bytes=None, hitmap_color_map=None, data_csv=None)[source]

Create a .plt.zip bundle from PNG bytes and embed it as a panel.

Convenience wrapper around add_panel() for the common case of adding a pre-rendered PNG image as a panel.

Parameters:
  • label (str) – Panel label (e.g., “A”, “B”).

  • png_bytes (bytes) – PNG image data.

  • plot_type (str, optional) – Plot type label stored in the panel’s spec.json (default: “image”).

  • position (dict, optional) – Panel position e.g. {“x_mm”: 5, “y_mm”: 5}.

  • size (dict, optional) – Panel size e.g. {“width_mm”: 80, “height_mm”: 68}.

Return type:

None

remove_panel(label)[source]

Remove a panel (rebuilds ZIP).

Parameters:

label (str) – Panel label to remove.

Return type:

None

get_panel(label)[source]

Extract panel as Pltz instance (via temp file).

Note: The caller is responsible for cleaning up the temp file (accessible via the returned Pltz instance’s .path attribute).

Parameters:

label (str) – Panel label.

Returns:

Loaded Pltz instance for the panel.

Return type:

Pltz

get_panel_pltz(panel_id)[source]

Get panel as raw bytes.

Parameters:

panel_id (str) – Panel label.

Returns:

Raw .plt.zip bytes, or None if panel not found.

Return type:

bytes or None

list_panel_ids()[source]

List panel labels in order.

Returns:

Panel labels.

Return type:

list of str

get_panel_data(panel_id)[source]

Get panel’s CSV data as DataFrame.

Parameters:

panel_id (str) – Panel label.

Return type:

DataFrame or None

render_preview()[source]

Return preview of first panel as PNG bytes.

Return type:

bytes or None

class figrecipe.Pltz(path)[source]

Bases: object

Single-plot bundle (.plt.zip).

Thin wrapper around figrecipe’s existing bundle functions: - load_bundle() - save_bundle() - reproduce_bundle()

Bundle structure (inside ZIP):
{stem}/

spec.json # WHAT to plot (semantic specification) style.json # HOW it looks (appearance settings) data.csv # Raw data recipe.yaml # Reproducible recipe exports/

figure.png

__init__(path)[source]
classmethod from_png(png_bytes, path, plot_type='image', spec=None, style=None, hitmap_bytes=None, hitmap_color_map=None, data_csv=None)[source]

Create a .plt.zip bundle wrapping a pre-rendered PNG image.

Useful when a figure is rendered externally (e.g., from a gallery template) and needs to be stored as a figrecipe bundle.

Parameters:
  • png_bytes (bytes) – PNG image data.

  • path (str or Path) – Output path for the .plt.zip file.

  • plot_type (str, optional) – Plot type label stored in spec.json (default: “image”).

  • spec (dict, optional) – Additional spec entries (default: {}).

  • style (dict, optional) – Style entries (default: {}).

Returns:

Loaded Pltz instance wrapping the saved bundle.

Return type:

Pltz

classmethod create(path, fig)[source]

Save a RecordingFigure as a .plt.zip bundle.

Parameters:
  • path (str or Path) – Output path. If it doesn’t end in .zip, .zip is appended.

  • fig (RecordingFigure) – Figure created with figrecipe.subplots().

Returns:

Loaded Pltz instance wrapping the saved bundle.

Return type:

Pltz

get_preview()[source]

Read pre-rendered preview PNG from bundle.

Returns:

PNG bytes, or None if no preview image is stored.

Return type:

bytes or None

render_preview()[source]

Reproduce figure and render to PNG bytes.

Returns:

PNG bytes, or None on failure.

Return type:

bytes or None

save()[source]

Save spec/style changes back to bundle in-place.

Updates spec.json and style.json inside the ZIP without re-rendering the figure.

Return type:

None

update_preview()[source]

Re-render and update preview PNG in bundle.

Return type:

None

reproduce()[source]

Reproduce figure from bundle.

Returns:

(fig, axes) reproduced from bundle.

Return type:

tuple

figrecipe.save_bundle(fig, path, dpi=None, image_formats=None, save_hitmap=False, verbose=True)[source]

Save figure as a layered bundle (ZIP format).

Bundle structure inside ZIP:

spec.json # WHAT (semantic specification) style.json # HOW (appearance settings) data.csv # DATA (immutable source data) recipe.yaml # Reproducible recipe (for fr.reproduce()) exports/

figure.png figure_hitmap.png # only if save_hitmap=True

Parameters:
  • fig (RecordingFigure) – The figure to save.

  • path (str or Path) – Output path (.zip will be added if not present).

  • dpi (int, optional) – DPI for exports (default from style or 300).

  • image_formats (list, optional) – Image formats to export (default: [‘png’]).

  • save_hitmap (bool) – Whether to save the per-pixel hitmap PNG used by the GUI editor for diff visualisation (default: False). Hitmap rendering is expensive and the typical save() caller doesn’t need it; opt in with save_hitmap=True when persisting bundles for the editor.

  • verbose (bool) – Whether to print status (default: True).

Returns:

Path to saved ZIP bundle.

Return type:

Path

figrecipe.load_bundle(path)[source]

Load bundle components from ZIP file.

Parameters:

path (str or Path) – Path to bundle ZIP file.

Returns:

(spec, style, data) where data is DataFrame or None.

Return type:

tuple

figrecipe.reproduce_bundle(path, apply_style=True)[source]

Reproduce figure from bundle.

Parameters:
  • path (str or Path) – Path to bundle (ZIP file or directory).

  • apply_style (bool) – Whether to apply saved style (default: True).

Returns:

(fig, axes) reproduced from bundle.

Return type:

tuple

class figrecipe.Diagram(title=None, width_mm=170.0, height_mm=120.0, padding_mm=10.0, gap_mm=None)[source]

Bases: object

Builder for rich box-and-arrow diagrams with mm-based coordinates.

__init__(title=None, width_mm=170.0, height_mm=120.0, padding_mm=10.0, gap_mm=None)[source]
add_box(id, title, subtitle=None, content=None, emphasis='normal', shape='rounded', x_mm=None, y_mm=None, width_mm=None, height_mm=None, fill_color=None, border_color=None, title_color=None, padding_mm=5.0, margin_mm=0.0, node_class=None, state=None, language=None, bullet=None)[source]

Add a rich text box. See BoxSpec for node_class/state/language/bullet.

Return type:

Diagram

add_container(id, title=None, children=None, emphasis='muted', x_mm=None, y_mm=None, width_mm=None, height_mm=None, fill_color=None, border_color=None, title_loc='upper center', direction='row', container_gap_mm=8.0, container_padding_mm=8.0, equalize_heights=True, equalize_widths=True)[source]

Add a container. equalize_heights/widths: match children in row/column.

Return type:

Diagram

add_arrow(source, target, source_anchor='auto', target_anchor='auto', source_dx=0.0, source_dy=0.0, target_dx=0.0, target_dy=0.0, label=None, style='solid', color=None, curve=0.0, linewidth_mm=0.5, label_offset_mm=None, margin_mm=None)[source]

Add an arrow connecting two boxes.

Return type:

Diagram

add_icon(id, source, x_mm, y_mm, width_mm=8.0, height_mm=8.0, color=None, opacity=1.0)[source]

Add an icon (SVG/PNG or built-in: warning/check/cross/info/lock).

Return type:

Diagram

validate_containers()[source]

Check every container fully encloses its declared children.

Return type:

None

validate_no_overlap()[source]

Check that no two boxes overlap each other.

Return type:

None

auto_layout(layout='lr', margin_mm=15.0, box_size_mm=None, gap_mm=10.0, avoid_overlap=True, justify='space-between', align_items='center')[source]

Automatically position boxes. See _layout for details.

Return type:

Diagram

_auto_box_height(box)[source]

Compute box height from content when height_mm is not specified.

Return type:

float

_finalize_canvas_size()[source]

Compute canvas height from element positions when height_mm=None.

Return type:

None

_get_anchor(pos, anchor)[source]

Get absolute position of an anchor point on the visual box edge.

Return type:

Tuple[float, float]

_auto_anchor(src, tgt)[source]

Determine best anchor points automatically.

Return type:

Tuple[str, str]

render(ax=None, auto_fix=False, auto_curve=True)[source]

Render. auto_fix=True resolves violations; auto_curve=False skips R7.

Return type:

Tuple[Figure, Axes]

save(path, dpi=200, save_recipe=True, save_hitmap=False, save_debug=True, watermark=False)[source]

Render, crop, and save. watermark=True adds ‘Plotted by scitex.ai’.

Return type:

Path

render_to_file(path, dpi=200, save_recipe=True, save_hitmap=False, save_debug=True, watermark=False)

Render, crop, and save. watermark=True adds ‘Plotted by scitex.ai’.

Return type:

Path

to_dict()[source]

Convert diagram to dictionary for serialization.

Return type:

Dict[str, Any]

classmethod from_dict(data)[source]

Create Diagram from dictionary (recipe reproduction).

Return type:

Diagram

figrecipe.signature(image_path=None, recipe_path=None)[source]

Compute verification signature for a saved figure.

Parameters:
  • image_path (str or Path, optional) – Path to the saved image file.

  • recipe_path (str or Path, optional) – Path to the saved recipe YAML file.

Returns:

Signature with keys: image_hash, recipe_hash, image_path, recipe_path.

Return type:

dict

Core Functions

Recording Classes

These classes are available via from figrecipe import utils or from figrecipe._wrappers import RecordingFigure, RecordingAxes.

Style Management

Alignment Functions

GUI Editor

Diagram Class

class figrecipe.Diagram(title=None, width_mm=170.0, height_mm=120.0, padding_mm=10.0, gap_mm=None)[source]

Builder for rich box-and-arrow diagrams with mm-based coordinates.

__init__(title=None, width_mm=170.0, height_mm=120.0, padding_mm=10.0, gap_mm=None)[source]
add_box(id, title, subtitle=None, content=None, emphasis='normal', shape='rounded', x_mm=None, y_mm=None, width_mm=None, height_mm=None, fill_color=None, border_color=None, title_color=None, padding_mm=5.0, margin_mm=0.0, node_class=None, state=None, language=None, bullet=None)[source]

Add a rich text box. See BoxSpec for node_class/state/language/bullet.

Return type:

Diagram

add_container(id, title=None, children=None, emphasis='muted', x_mm=None, y_mm=None, width_mm=None, height_mm=None, fill_color=None, border_color=None, title_loc='upper center', direction='row', container_gap_mm=8.0, container_padding_mm=8.0, equalize_heights=True, equalize_widths=True)[source]

Add a container. equalize_heights/widths: match children in row/column.

Return type:

Diagram

add_arrow(source, target, source_anchor='auto', target_anchor='auto', source_dx=0.0, source_dy=0.0, target_dx=0.0, target_dy=0.0, label=None, style='solid', color=None, curve=0.0, linewidth_mm=0.5, label_offset_mm=None, margin_mm=None)[source]

Add an arrow connecting two boxes.

Return type:

Diagram

add_icon(id, source, x_mm, y_mm, width_mm=8.0, height_mm=8.0, color=None, opacity=1.0)[source]

Add an icon (SVG/PNG or built-in: warning/check/cross/info/lock).

Return type:

Diagram

validate_containers()[source]

Check every container fully encloses its declared children.

Return type:

None

validate_no_overlap()[source]

Check that no two boxes overlap each other.

Return type:

None

auto_layout(layout='lr', margin_mm=15.0, box_size_mm=None, gap_mm=10.0, avoid_overlap=True, justify='space-between', align_items='center')[source]

Automatically position boxes. See _layout for details.

Return type:

Diagram

_auto_box_height(box)[source]

Compute box height from content when height_mm is not specified.

Return type:

float

_finalize_canvas_size()[source]

Compute canvas height from element positions when height_mm=None.

Return type:

None

_get_anchor(pos, anchor)[source]

Get absolute position of an anchor point on the visual box edge.

Return type:

Tuple[float, float]

_auto_anchor(src, tgt)[source]

Determine best anchor points automatically.

Return type:

Tuple[str, str]

render(ax=None, auto_fix=False, auto_curve=True)[source]

Render. auto_fix=True resolves violations; auto_curve=False skips R7.

Return type:

Tuple[Figure, Axes]

save(path, dpi=200, save_recipe=True, save_hitmap=False, save_debug=True, watermark=False)[source]

Render, crop, and save. watermark=True adds ‘Plotted by scitex.ai’.

Return type:

Path

render_to_file(path, dpi=200, save_recipe=True, save_hitmap=False, save_debug=True, watermark=False)

Render, crop, and save. watermark=True adds ‘Plotted by scitex.ai’.

Return type:

Path

to_dict()[source]

Convert diagram to dictionary for serialization.

Return type:

Dict[str, Any]

classmethod from_dict(data)[source]

Create Diagram from dictionary (recipe reproduction).

Return type:

Diagram