anyplotlib.Figure#
- class anyplotlib.Figure(**kwargs)[source]#
Bases:
AnyWidget,_EventMixinMulti-panel interactive figure widget.
The top-level container for all plots and the only
anywidget.AnyWidgetsubclass in anyplotlib. It owns all traitlets and acts as the Python ↔ JavaScript bridge via thefigure_esm.jscanvas renderer.Create via
subplots()(recommended) or directly:fig = Figure(2, 2, figsize=(800, 600)) ax = fig.add_subplot((0, 0)) v2d = ax.imshow(data)
- Parameters:
nrows (int, optional) – Grid dimensions. Default 1 row, 1 column.
ncols (int, optional) – Grid dimensions. Default 1 row, 1 column.
figsize ((width, height), optional) – Figure size in CSS pixels. Default
(640, 480).width_ratios (list of float, optional) – Relative column widths. Length must equal ncols.
height_ratios (list of float, optional) – Relative row heights. Length must equal nrows.
sharex (bool, optional) – Link pan/zoom across all panels on the respective axis. Default False (independent pan/zoom per panel).
sharey (bool, optional) – Link pan/zoom across all panels on the respective axis. Default False (independent pan/zoom per panel).
See also
subplotsRecommended factory for creating Figure and Axes grid.
- layout_json#
A trait for unicode strings.
- event_json#
A trait for unicode strings.
- edit_chrome#
A boolean (True, False) trait.
- selected_panel#
A trait for unicode strings.
- figure_markers_json#
A trait for unicode strings.
- callbacks: CallbackRegistry#
- fig_width#
An int trait.
- fig_height#
An int trait.
- display_stats#
A boolean (True, False) trait.
- help_text#
A trait for unicode strings.
- set_help(text)[source]#
Set (or clear) the figure-level help text shown in the ? badge.
- Parameters:
text (str) – Help string displayed when the user clicks the ? badge. Pass an empty string (or
"") to remove the badge entirely. Newlines (\n) are respected in the card.- Return type:
None
Examples
>>> fig.set_help("Drag peak: move μ/A\nPress f: least-squares fit") >>> fig.set_help("") # hide the badge
- subplots_adjust(hspace=None, wspace=None)[source]#
Set the spacing between subplot panels.
Only the arguments that are explicitly provided are updated; omitting an argument leaves the current value unchanged.
- Parameters:
hspace (float, optional) – Fraction of the average row height to use as vertical gap between panels.
0.1adds a gap of 10 % of the mean row height.None(default) leaves the current hspace unchanged.wspace (float, optional) – Fraction of the average column width to use as horizontal gap.
None(default) leaves the current wspace unchanged.
- Return type:
None
- add_subplot(spec)[source]#
Add a subplot cell and return its
Axes.- Parameters:
spec (SubplotSpec or int or tuple of (row, col)) – Which grid cell(s) to occupy. A
SubplotSpecis used directly (e.g. fromGridSpec[r, c]). Anintis converted viadivmod(spec, ncols), matchingmatplotlib.Figure.add_subplotnumbering. A(row, col)tuple selects a single cell.- Returns:
The subplot axes object. Call plotting methods like
.imshow(),.plot(),.bar()to attach data.- Return type:
- Raises:
TypeError – If spec is not a SubplotSpec, int, or tuple.
Examples
>>> fig = Figure(2, 2) >>> ax1 = fig.add_subplot(0) # top-left (via numbering) >>> ax2 = fig.add_subplot((0, 1)) # top-right (via tuple)
- batch()[source]#
Coalesce all panel pushes within the block into one push per panel.
Use around multi-panel updates (e.g. a linked-view crosshair handler) so a single mouse event produces one serialise + transfer per panel instead of one per mutation — a large win under Pyodide / remote kernels where every push crosses a comm boundary.
with fig.batch(): v_xz.set_data(slice_xz) v_yz.set_data(slice_yz) cross.set(cx=..., cy=...)
- add_inset(w_frac, h_frac, *, corner='top-right', anchor=None, title='')[source]#
Create and return a floating inset axes.
The inset overlays the figure at the specified corner (default) or at an arbitrary anchor position. Call plot-factory methods on the returned
InsetAxesto attach data:inset = fig.add_inset(0.3, 0.25, corner="top-right", title="Zoom") inset.imshow(data) # returns Plot2D inset.plot(profile) # returns Plot1D # arbitrary placement (top-left corner at 55% across, 10% down): free = fig.add_inset(0.3, 0.25, anchor=(0.55, 0.10)) free.imshow(data)
- Parameters:
w_frac (float) – Width and height as fractions of the figure size (0–1).
h_frac (float) – Width and height as fractions of the figure size (0–1).
corner (str, optional) – Positioning corner:
"top-right"(default),"top-left","bottom-right", or"bottom-left". Mutually exclusive with anchor.anchor ((x_frac, y_frac), optional) – Position of the inset’s TOP-LEFT corner as fractions of the figure size (0–1), from the figure’s top-left. When given, the inset floats at that anchor and corner is ignored. Use this for free placement (e.g. a callout panel next to the region it marks).
title (str, optional) – Text displayed in the inset title bar.
- Return type:
InsetAxes
- set_figure_markers(markers)[source]#
Set the figure-level annotation layer.
- Parameters:
Each dict is
{"id"?, "kind", ...}with positions/sizes in FIGURE FRACTIONS (0..1, origin top-left).kindis one of:"text"—x, y, text; optionalcolor,fontsize"circle"—x, y, r(ras a fraction ofmin(fig_width, fig_height)); optionalcolor,linewidth"rect"—x, y(centre),w, h; optionalcolor,linewidth"arrow"—x, y(tail),u, v(vector); optionalcolor,linewidth
Any dict missing an
idis assigned a fresh one.- Raises:
ValueError – If a marker has an unrecognised
kind.- Return type:
None
- property figure_markers: list#
The current figure-level annotation list (list of dicts, fractions).
Returns a shallow copy so external mutation doesn’t desync the trait; call
set_figure_markers()to change it.
- get_axes()[source]#
Return a list of all grid Axes, sorted by grid position.
Includes axes that have no plot attached yet (as matplotlib does), so
fig, ax = apl.subplots(1, 1); fig.get_axes()[0] is ax. Floating insets fromadd_inset()are not listed.
- to_html(*, resizable=True)[source]#
Return a self-contained HTML page rendering this figure.
The page inlines the JS renderer and all data — no Jupyter kernel or network needed at view time. Load it in any browser context, e.g. an Electron
BrowserWindowor<webview>. Seeanyplotlib.embedfor the full embedding guide (including live Python sync viaFigureBridge).
- save_html(path, *, resizable=True)[source]#
Write
to_html()output to path; returns thePath.- Parameters:
resizable (bool)
- savefig(path, *, source='view', theme='current', scale=1, include_widgets=True, panel=None, timeout_ms=30000)[source]#
Write this figure to path as a PNG; returns the
Path.Rendering happens in a headless browser, because the renderer is the JavaScript one — so the output is pixel-for-pixel what the figure looks like on screen, including the viewer’s current zoom, pan and contrast. Requires Playwright (
pip install "anyplotlib[docs]"thenplaywright install chromium).- Parameters:
path (str or pathlib.Path) – Destination file. Written as PNG regardless of the suffix.
source (
"view"|"full"|"native", optional) –"view"(default) captures the figure as displayed."full"resets the zoom so the whole data extent is shown, at the panel’s on-screen resolution."native"renders ONE image panel at one output pixel per data pixel, with its axes, colorbar, title, markers and widgets redrawn at that size — for a tiled plot the full array is re-encoded from the backend for the export only.theme (
"current"|"light"|"dark", optional) – Palette to render with, independent of the ambient theme.scale (float, optional) – Extra resolution multiplier for
"view"/"full". Ignored by"native", which is already 1:1 with the data.include_widgets (bool, optional) – Draw interactive overlay widgets (without their drag handles). Default
True.panel (Plot or str, optional) – Export just this panel (a plot object or its panel id) instead of the whole figure. Required for
source="native"unless the figure has exactly one 2-D panel.timeout_ms (int, optional) – How long to wait for the page to render. Default 30 s.
- Returns:
The path written.
- Return type:
See also
save_htmlinteractive, self-contained HTML instead of a raster.
- property displayed: bool#
Trueonce the figure has been handed to a display front-end.Set by
display(), and also when the figure is shown any other way that goes through its rich repr — the last expression of a notebook cell,IPython.display.display(fig), or the HTML repr Sphinx Gallery uses.
- display(*, force=False)[source]#
Show the figure in the current IPython front-end, at most once.
Safe to call from several code paths that each want the figure on screen: only the first call (or a figure not yet shown by any other means, see
displayed) actually displays it, so the output is never duplicated.
- on_close(callback)[source]#
Register callback to run when the figure is closed.
Shorthand for
fig.add_event_handler(callback, "close"); the callback receives thecloseEvent. Figure level close handlers run before the per-panel ones.- Parameters:
callback (callable) –
callback(event); a bound method is fine.- Returns:
Connection id; pass it to
remove_handler()to unregister.- Return type:
Examples
>>> import anyplotlib as apl >>> fig, ax = apl.subplots() >>> cid = fig.on_close(lambda event: print("bye")) >>> fig.close() bye
- close()[source]#
Close the figure.
Fires a
"close"event on the figure’s owncallbacks(seeon_close()), then on every panel’s, then hides the widget by setting its CSSdisplayto"none".closedbecomesTrue. Subsequent calls are no-ops.Finally the underlying ipywidgets comm is closed (front-end views are removed) and the widget is released, so a closed figure that is no longer referenced can be garbage collected. The Python objects stay usable — plots can still be read, exported or saved.
The figure-level handlers and each panel’s handlers run independently: if one of them raises, the others still run, the figure is still marked closed and hidden, and the first exception is re-raised at the end.
- Return type:
None