Introducing a new way to review your PRs.

Read the announcement

reflex-dev / xy

Ultra-fast and customizable Python charts

View on GitHub

20 documents · Updated Nov 18, 2026

docs / matplotlib-backends-and-canvas

Matplotlib backends and canvas integration

The xy Matplotlib backend lets genuine Matplotlib figures render through one XY display model. It supports static files, notebook widgets, and a live browser host while keeping drawing, raster output, and browser updates aligned. It is the backend and canvas layer beneath the Matplotlib pyplot compatibility layer.

Backend boundary

The backend is selected through Matplotlib's module-backend system and targets Matplotlib 3.11. The base xy.backends package stays light and exposes the Matplotlib classes only when the optional Matplotlib integration is requested. This keeps the backend separate from xy's dependency-free native pyplot mode. References: python/…/__init__.py• L1-48, python/…/backend_xy.py• L1-10, python/…/backend_xy.py• L58-94

The backend owns the canvas, renderer, figure manager, navigation toolbar, and timer boundary. Matplotlib still supplies the figure and artist semantics. The backend turns the resulting draw into XY-owned output and rejects three-dimensional axes instead of sending them through an unrelated renderer. References: python/…/backend_xy.py• L949-1006, python/…/backend_xy.py• L1735-1762, python/…/backend_xy.py• L1905-1915

Display-list handoff

The display list is the shared handoff between Matplotlib drawing and every XY output. It is an ordered set of device-space commands with checked resources for paths, arrays, images, and fonts. It uses Matplotlib's bottom-left pixel coordinates so the SVG and raster consumers can apply their own final coordinate conversion. References: python/…/display_list.py• L1-7, python/…/display_list.py• L24-122, python/…/display_list.py• L234-316

When a canvas draws, RendererXY records paths, text, collections, images, clips, meshes, and groups in that list. The canvas then publishes the completed list to a widget or host, or passes it to an export serializer. This makes the draw order and geometry common across interactive and static views.

flowchart LR
    A[Matplotlib figure draw] --> B[XY renderer]
    B --> C[Device-space display list]
    C --> D[SVG or HTML]
    C --> E[XY rasterizer and PNG]
    C --> F[Notebook widget or loopback host]

The list records fallback state as part of its contract. A consumer can therefore tell whether output stayed on the XY path rather than silently accepting output from another renderer. References: python/…/backend_xy.py• L150-219, python/…/backend_xy.py• L352-431, python/…/display_list.py• L318-369

Output paths

Static output consumes the same display list as live output. SVG serializes the commands as vector elements. HTML embeds the SVG and a script-safe JSON copy of the list. JSON exposes the list itself for transport or inspection. References: python/…/display_list.py• L371-410, python/…/backend_xy.py• L1522-1559

PNG output uses XY's raster consumer and native PNG encoder. The path does not call Matplotlib Agg, Cairo, or a browser renderer. The raster consumer handles paths, clips, images, meshes, text outlines, hatches, and color interpolation from the shared list, so static raster output keeps the same drawing source as SVG. References: python/…/display_list.py• L406-416, python/…/raster.py• L1-5, python/…/backend_xy.py• L1561-1575

The canvas also uses the XY raster path for region snapshots used by Matplotlib blitting. A saved region belongs to the canvas geometry that created it. A resize or incompatible renderer state causes a redraw rather than restoring pixels into the wrong surface. This lets animated or interactive foreground content update without replacing the full figure on every step. References: python/…/backend_xy.py• L1283-1338, python/…/backend_xy.py• L1340-1499

Canvas modes

The canvas has two browser-facing modes with one rendering contract. The widget mode is kernel-connected and fits notebooks. The host mode serves a live page from an authenticated loopback server for ordinary Python scripts. Both receive SVG snapshots and send browser input back to the same Python canvas.

ModeDisplay targetState pathTypical use
Widget canvasAnyWidget viewSynchronized widget traits and comm messagesIPython and notebook sessions
Host canvasLocal browser pageCached HTTP state and queued HTTP eventsStandalone scripts
Static canvasFile or stringDirect serializer or raster consumerHTML, SVG, JSON, and PNG output

The figure manager selects the widget when an IPython shell is active. Outside IPython it creates a loopback host and opens its unguessable URL. The host serves cached frames; it does not mutate Matplotlib state from its server thread. flush_events() pumps queued messages on the Matplotlib calling thread. References: python/…/backend_xy.py• L1792-1842, python/…/backend_xy_host.py• L136-155, python/…/backend_xy_host.py• L335-369

Browser assets

The browser view uses the bundled module at python/…/backend_xy_widget.js. The widget exposes that module as its ESM asset. The loopback host serves the same file from a same-origin route, so notebook and script views share one browser event and display surface rather than two separate clients. References: python/…/backend_xy_widget.py• L38-71, python/…/backend_xy_widget.py• L107-152, python/…/backend_xy_host.py• L28-29, python/…/backend_xy_host.py• L39-117

The asset builds a small canvas shell around the SVG frame. It sets the logical size, replaces the SVG when a new generation arrives, tracks the cursor and toolbar state, and observes browser resize. Pointer, wheel, keyboard, close, and timer messages travel back through the active browser connection. References: python/…/backend_xy_widget.js• L82-157, python/…/backend_xy_widget.js• L178-247, python/…/backend_xy_widget.js• L274-389

Live toolbar and events

Live toolbar behavior keeps Matplotlib's navigation state in Python while showing the current state in the browser. The toolbar reports its mode, status message, history availability, and cursor through the canvas. Browser buttons send only named actions back to Python, where the real Matplotlib toolbar applies them. References: python/…/backend_xy.py• L1248-1281, python/…/backend_xy.py• L1642-1687, python/…/backend_xy_widget.py• L343-367

Browser input becomes genuine Matplotlib event objects before callbacks run. This preserves the normal callback boundary for mouse, location, key, resize, close, picking, and widget behavior. Active Matplotlib timers use browser heartbeats only to wake the Python event loop; Python remains the owner of timer deadlines and callback execution. References: python/…/backend_xy_widget.py• L102-114, python/…/backend_xy_widget.py• L217-327, python/…/backend_xy.py• L787-865

The browser toolbar is a view of live state, not a second navigation system. Changes to history, pan or zoom mode, status text, and cursor state are pushed to every active view after the Python toolbar changes. The browser stops polling after repeated host failures and cleans up timers and connections when the view closes. References: python/…/backend_xy_widget.js• L168-237, python/…/backend_xy_host.py• L77-117, python/…/backend_xy.py• L1892-1902

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep display-list command and resource changes compatible with the SVG serializer, raster consumer, widget, and loopback host.
  • Keep bottom-left device coordinates aligned with the SVG and raster coordinate conversions.
  • Keep widget trait names, host state keys, and browser asset update handlers synchronized.
  • Keep toolbar actions and toolbar state updates aligned between the Python toolbar, host or widget transport, and browser buttons.
  • Keep timer heartbeats as wake-up signals only. Do not move timer ownership or callback execution into browser code.
  • Keep fallback metadata visible on every output and region snapshot so acceptance checks cannot hide a foreign renderer.

Important failure modes

TriggerConsequenceGuard
A display-list resource is missing or has a bad checksumSVG or raster output cannot resolve shared geometry or image data.DisplayList validates resource type, shape, byte count, and checksum before consumption.
A non-XY renderer supplies outputStatic and live paths can disagree, and the result can pass while violating the backend contract.The list records fallback_used and its reason; acceptance checks reject fallback output.
A browser view sends an unknown or malformed eventInvalid data could enter Matplotlib callbacks or corrupt canvas state.Widget and host boundaries validate event names and numeric fields before dispatch.
A canvas region is restored after a resizeOld device pixels can overwrite the new geometry.Region metadata tracks renderer geometry and forces a redraw when it no longer matches.
The host server thread changes figure stateMatplotlib callbacks can run off the calling thread and race with drawing.The host queues events; flush_events() dispatches them on the Matplotlib thread.
The browser asset and Python state keys driftThe figure may display an old frame or toolbar state without a clear Python error.Widget traits, host state, and the ESM change handlers form one synchronized contract.

Key files

FileWhy to read it
python/…/backend_xy.pyMain Matplotlib canvas, renderer, exports, manager, toolbar, timers, and live-view lifecycle.
python/…/display_list.pyShared rendering contract, resource model, and SVG, HTML, JSON, and raster entry points.
python/…/raster.pyXY-owned RGBA and PNG consumer for display-list output.
python/…/backend_xy_widget.pyNotebook widget state, event conversion, toolbar actions, and timer wake-up path.
python/…/backend_xy_host.pyAuthenticated loopback page, browser asset serving, state polling, and event queue.
python/…/backend_xy_widget.jsBrowser canvas shell, SVG updates, input capture, toolbar controls, resize, and timer heartbeats.
tests/…/test_backend_xy.pyRenderer, export, live manager, and blit behavior checks.
tests/…/test_backend_xy_widget.pyWidget events, host polling, browser assets, and live-toolbar behavior checks.
tests/…/test_display_list.pyDisplay-list validation and cross-consumer SVG, HTML, raster, and resource checks.