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-pyplot-compatibility

Matplotlib pyplot compatibility layer

xy.pyplot lets common Matplotlib-style plotting code produce XY charts with a small import change. It keeps the familiar pyplot state model and figure or axes calls, then translates those calls into XY chart descriptions for interactive or static output. The target is the supported two-dimensional plotting surface, not a replacement for every Matplotlib renderer, artist, or transform graph. See the Python chart API for the underlying chart model.

Output and integration boundaries

The pyplot layer turns plotting intent into an XY chart description. Backend choice, canvas modes, widget and host integration, and display-list rendering are separate output concerns. See Matplotlib backends and canvas for those boundaries and their related child topics.

References: spec/…/compat.md• L148-152

Pyplot translation model

The compatibility layer presents two related entry points: stateful functions such as plt.plot and object methods such as ax.plot. Both describe marks and chart settings on an XY figure. The translation preserves the plotting intent and returns XY-owned handles that support the common update and removal patterns.

The broad call path is:

flowchart LR
    A[Matplotlib-style call] --> B[Current figure and axes]
    B --> C[Mark, axis, and style description]
    C --> D[XY chart model]
    D --> E[Interactive HTML or static export]

The layer covers the Matplotlib 3.11 two-dimensional plotting-method target. It includes line, scatter, bar, histogram, image, contour, triangle, statistical, text, annotation, and vector-field families. It also supports polar axes as a bounded non-Cartesian case. The compatibility matrix describes the intended level for each family: exact geometry, equivalent meaning, visual approximation, accepted no-op, optional interop, or unsupported. References: python/…/__init__.py• L1-14, spec/…/compat.md• L7-19, spec/…/compat-matrix.md• L9-20

Stateful figure and axes model

The pyplot state model tracks a current figure and current axes so scripts can use plt.figure(), plt.gca(), plt.plot(), and plt.show() without passing objects through every call. A figure owns its axes and the current axes pointer. Creating or activating a figure updates that state, while close() removes it from the open-figure set.

Figure factories map familiar layout requests into XY panels:

Pyplot conceptXY compatibility behavior
figure(num)Creates or activates a numbered or named figure.
gcf() and gca()Return the current figure or axes and create them when needed.
subplots()Creates a panel grid with optional sharing, size, DPI, and ratios.
subplot() and subplot_mosaic()Select panels by grid position or label.
twinx() and twiny()Add a second data axis that shares one dimension.
clf(), cla(), and delaxes()Clear or remove the active figure or axes.

The figure also owns figure-level text, legends, colorbars, layout settings, and export actions. A multi-panel figure is composed as one output while each axes keeps its own chart content and axis state. Shared axes use linked domains, so a view change on one shared panel can affect the others. References: python/…/_state.py• L20-127, python/…/__init__.py• L247-454, python/…/_mplfig.py• L282-327, python/…/_mplfig.py• L350-360

Artist handle updates

Returned plot objects act as focused handles over the translated chart description. A change such as line.set_ydata(), artist.set_color(), artist.set_label(), or artist.remove() updates the handle state and invalidates the cached chart. The next display or export rebuilds the affected result. This supports common Matplotlib mutation idioms without reproducing the full Matplotlib artist graph.

The boundary is intentional: XY exposes its own line, collection, patch, text, container, and legend views. Arbitrary third-party artist graphs are outside the compatibility target. References: python/…/_artists.py• L1-7, python/…/_artists.py• L80-142, python/…/_artists.py• L232-251, python/…/_artists.py• L360-386

Coordinate transforms

Transforms define how plotted positions are interpreted before they reach the chart. The compatibility layer supports bounded affine transforms in data coordinates and named coordinate-space tokens for figure, axes, and data placement. This covers common translation, scale, rotation, and Affine2D + ax.transData uses.

The supported transform path applies a coordinate conversion to the data before the mark is recorded. It requires an invertible transform when a returned artist is later assigned one. Axes-fraction or figure-fraction placement is supported for the text and span forms that own those semantics. A general Matplotlib transform graph, arbitrary clipping graph, and non-affine artist transform composition are not supported.

flowchart LR
    A[Input coordinates] --> B[Affine data transform]
    B --> C[XY data mark]
    C --> D[Axes scale and view]
    D --> E[Rendered position]

This separation keeps the transform contract clear: data transforms alter mark coordinates, while axes and figure coordinate spaces place decoration relative to the panel or canvas. References: python/…/_transforms.py• L1-10, python/…/_transforms.py• L45-111, python/…/_axes.py• L1889-1901, python/…/_artists.py• L176-230, spec/…/compat.md• L99-106

Axes scales and tick formatters

Axes state combines a data domain, a scale, tick locations, and tick labels. Linear and logarithmic scales are native. Symlog, logit, and asinh use monotone XY-owned conversions with matching limit and tick semantics. Date, time-span, and common string coordinates use the chart engine's date or categorical conventions rather than a general Matplotlib units registry.

Locators choose tick positions over the live view interval. Formatters turn those positions into label text. The axes resolves both at chart-build time, so labels refresh when data or limits change. Fixed, multiple, linear, null, and MaxN-style locators have the strongest positional compatibility. Log locators are approximate. Custom locator objects can participate when they provide tick_values(vmin, vmax).

Compatibility surfaceMain boundary
Major locator and formatterResolved against current limits during chart construction.
Minor locator and formatterRetained for round-tripping; minor ticks usually do not draw.
Date locator and formatterOperate on XY canonical milliseconds since epoch.
Explicit xticks() and yticks()Preserve requested positions and labels.
Secondary axesConvert the primary domain with forward and inverse callables.

Secondary axes are linked, tick-focused views of a primary axis. They render in interactive HTML, while static secondary-axis drawing remains outside the current export boundary. References: python/…/_ticker.py• L1-9, python/…/_ticker.py• L82-124, python/…/_ticker.py• L127-225, python/…/dates.py• L1-9, python/…/_axes.py• L642-692, python/…/_axes.py• L5389-5419, spec/…/compat.md• L73-78

Format strings and markers

Line format strings compress color, line style, and marker choices into one short value. The parser accepts the common interleaved grammar, including forms such as "r--o", "C1-.s", marker-only strings, and named colors. The resulting parts feed the line or scatter translation instead of being treated as a renderer-specific string.

Markers map to a bounded XY symbol set. Common circles, triangles, squares, diamonds, stars, crosses, line markers, regular polygons, and supported math-text glyphs retain their basic meaning. Bounded custom marker vertices can be compiled into a renderer-neutral path. Unknown markers and unsupported marker forms fail rather than silently become another symbol.

For a line with markers, the compatibility layer represents the line and marker paint as one logical returned handle. Marker face, edge, size, and visibility changes therefore follow the same handle. markevery controls the marker positions without changing the line path. References: python/…/_fmt.py• L1-6, python/…/_fmt.py• L21-57, python/…/_markers.py• L1-7, python/…/_markers.py• L25-74, python/…/_translate.py• L44-70, python/…/_axes.py• L1800-1872, python/…/_axes.py• L2052-2084

Color and colormap translation

Color translation converts Matplotlib-style color values into the CSS and RGBA forms accepted by XY. It supports single-letter colors, C0–C9 cycle references, tab:* names, gray strings from "0.0" to "1.0", CSS names, hex, rgb() values, RGB(A) tuples, and color-alpha pairs. Per-item color arrays remain per-item arrays when a mark supports them.

Numeric color data is distinct from a literal color array. A one-dimensional numeric c value is mapped through a named colormap and its value range. An N×3 or N×4 array is treated as explicit face or edge RGBA data. The alpha argument replaces intrinsic RGBA alpha when supplied, which keeps scalar and vector color behavior aligned with Matplotlib's common use.

Named colormaps are available through plt.cm, plt.colormaps, and cmap=. Reversed names use the *_r form. Python-created ListedColormap and LinearSegmentedColormap objects can produce RGBA values for scripts that inspect or pass those values onward, but they are not renderable engine colormap tables when passed directly as a plotting colormap. Colorbars track the current color-mapped artist and its color limits.

References: python/…/_colors.py• L1-7 python/…/_colors.py• L28-41 python/…/_colors.py• L114-167 python/…/_colors.py• L340-462 python/…/__init__.py• L720-727 python/…/_mplfig.py• L1168-1200 spec/…/compat.md• L88-92

Style and compatibility boundaries

The layer carries a focused subset of rcParams, style sheets, and pyplot chrome into the XY chart description. Figure size, DPI, color cycles, line and marker defaults, image defaults, axis colors, grid settings, spine visibility, text weights, legend defaults, and figure backgrounds are the main shared style contract. rc_context() restores the prior style after a scoped change.

Supported calls reject unknown material keywords instead of accepting them and dropping their effect. Some options are documented visual approximations or validated no-ops. The layer does not claim full Matplotlib parity.

BoundaryResult
Supported two-dimensional plotting callsTranslate to XY marks and guides.
Visual differences caused by browser, native PNG, or SVG outputAccepted where the compatibility contract marks them as approximations.
Material option with no safe XY meaningRaises an actionable NotImplementedError.
Unknown keyword or invalid valueRaises TypeError or ValueError at the compatibility boundary.
Three-dimensional, ternary, geographic, and custom projection graphsOutside the target.
Animation, blitting, arbitrary artists, and non-affine transform graphsOutside the target.
Real Matplotlib objectsOptional interoperation only where the dedicated reference path supports it.

Importing xy does not load the pyplot layer. Importing xy.pyplot does not require the real Matplotlib package, widget stack, or browser machinery. This boundary lets ordinary pyplot-shaped code use XY without making Matplotlib a runtime dependency. References: python/…/_rc.py• L1-3, python/…/_rc.py• L119-166, python/…/_rc.py• L246-259, python/…/_translate.py• L73-144, spec/…/compat.md• L99-115, spec/…/compat.md• L148-152

Change checklist

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

  • Update the pyplot method inventory and compatibility matrix when a plotting family or method changes.
  • Keep format-string tokens, color aliases, marker symbols, and their renderer-facing mappings aligned. A token that parses but maps to the wrong XY symbol can fail silently in visual output.
  • Keep locator and formatter behavior aligned with the axis value unit. Date changes must preserve the milliseconds-since-epoch contract.
  • Keep figure state, axes ownership, shared domains, and artist invalidation aligned. A mutation that updates a handle but not the owning figure can leave stale exports.
  • Recheck every output path when changing figure layout, style, transforms, or chrome. Interactive HTML and static PNG or SVG can have different compatibility limits.
  • Preserve loud rejection for material unsupported options. Do not turn an unsupported Matplotlib argument into an unnoticed no-op.

Important failure modes

TriggerConsequenceGuard
A material keyword remains after translationThe call could appear to work while changing the requested chart.The translation boundary checks leftover keywords and raises TypeError.
A transform is non-invertible or uses a non-data coordinate space on a data artistThe mark cannot be mapped safely back to XY data coordinates.Transform assignment validates the coordinate space and inverse.
A custom or unknown marker is passedThe chart could draw the wrong symbol.Marker normalization rejects unknown forms and bounds custom paths.
A user colormap object is passed as an engine colormapXY has no named render table for that Python callable.Colormap resolution rejects non-renderable custom colormap objects.
A locator or formatter uses Matplotlib's unit-registry date valuesTick positions or labels can be shifted from the data domain.Date adapters use XY epoch milliseconds; incompatible pandas tickers are treated as scoped compatibility no-ops.
A static export relies on a secondary axisThe secondary ticks may be present in HTML but absent from PNG or SVG.Treat secondary-axis static rendering as outside the current contract.

Key files

FileWhy to read it
python/…/__init__.pyPublic pyplot namespace and stateful entry points.
python/…/_state.pyCurrent figure and axes lifecycle.
python/…/_mplfig.pyFigure ownership, panel composition, layout, colorbars, and exports.
python/…/_axes.pyPer-axes translation of marks, scales, axes, and shared views.
python/…/_artists.pyReturned handle and mutation contract.
python/…/_transforms.pySupported affine and coordinate-space model.
python/…/_ticker.py and python/…/dates.pyTick location, label formatting, and date-axis contracts.
python/…/_colors.pyMatplotlib color and colormap vocabulary.
python/…/_markers.py and python/…/_fmt.pyMarker normalization and compact line format strings.
python/…/_translate.pyShared keyword, line-style, marker, and error-boundary rules.
spec/…/compat.mdSupported surface, approximation levels, and explicit exclusions.