Introducing a new way to review your PRs.

Read the announcement

plotly / plotly.py

The interactive graphing library for Python :sparkles:

View on GitHub

13 documents · Updated Nov 16, 2026

docs / figure-subplots-callbacks

Figure Subplots and Interactive Figure Helpers

Overview

This area owns the helpers that prepare figure subplot layouts, attach row/column bookkeeping to figures, support callback payload objects, validate animation batch options, place annotations for axis-spanning shapes, and preserve legacy compatibility entrypoints.

The public subplot entrypoint is plotly/subplots.py::make_subplots. It is intentionally a thin wrapper around plotly/_subplots.py::make_subplots, re-exporting SubplotXY, SubplotDomain, and SubplotRef so callers can import the namedtuple return types from plotly.subplots. plotly/tools.py::make_subplots is the deprecated compatibility path; it warns and forwards to plotly.subplots.make_subplots. plotly/tools.py::get_subplots is older still: it computes evenly spaced cartesian axes itself, warns, and returns a validated graph_objs.Figure rather than using the _grid_ref machinery.

plotly/_subplots.py::make_subplots builds a go.Layout and mutates either a supplied go.Figure or a new figure with that layout. Its flow is:

  1. Normalize backward-compatible names (row_width to row_heights, column_width to column_widths) and reject unknown kwargs.
  2. Validate grid dimensions, start_cell, specs, insets, shared-axis modes, spacing, row/column sizing, and title lists.
  3. Convert each spec cell into a normalized domain. start_cell selects row_dir, which controls whether row domains are generated top-to-bottom or bottom-to-top. Column widths and row heights are normalized after subtracting global spacing, with extra horizontal room reserved when secondary y-axes or row titles are requested.
  4. For each non-empty spec cell, call _init_subplot to create subplot-specific layout containers and a tuple of SubplotRef values. Cartesian subplots create layout.xaxis* and layout.yaxis*; secondary-y cartesian cells add a second overlaid right-side y-axis. Single-container subplot types (scene, geo, polar, ternary, map) create a layout.<type>* object with a domain. domain traces do not create layout keys; their SubplotRef.trace_kwargs carries the trace-level domain instead.
  5. Apply shared axes through _configure_shared_axes, which sets matches and hides redundant tick labels only on one-cell cartesian spans. Secondary-y axes get a separate pass when any spec requests them.
  6. Build inset subplots from the parent cell domain and add their subplot refs separately for display in the grid string.
  7. Generate title annotations with _build_subplot_title_annotations for subplot, column, row, x, and y titles. These are stored in layout.annotations before updating the figure.
  8. Store private figure bookkeeping in figure.__dict__["_grid_ref"] and figure.__dict__["_grid_str"]. The grid reference is a rectangular 2D list matching requested rows and columns, where each populated cell contains one or more SubplotRef objects and blanks/spanned cells are None.

The same grid reference drives later graph-object mutation. plotly.basedatatypes.BaseFigure._set_trace_grid_position imports plotly._subplots._set_trace_grid_reference, validates _grid_ref, selects the requested SubplotRef by row, col, and optional secondary_y, verifies the trace supports the required reference keys, and updates the trace with xaxis/yaxis, scene, subplot, geo, or domain kwargs. BaseFigure.get_subplot calls plotly/_subplots.py::_get_grid_subplot, which returns a SubplotXY pair, a SubplotDomain, a layout subplot object such as layout.scene, or None for an empty grid cell.

plotly/_subplots.py::_get_subplot_ref_for_trace performs the inverse mapping for existing traces by inspecting trace properties (domain, xaxis/yaxis, geo, scene, or subplot). It is used by selection/update code outside this module to determine which subplot a trace belongs to when row/column filtering is requested.

Interactive callback payloads are simple containers in plotly/callbacks.py. InputDeviceState stores modifier-key and mouse-button state; Points stores selected point indexes, x/y values, and trace identity; BoxSelector and LassoSelector store selection geometry. They expose read-only properties and readable reprs. plotly/basewidget.py consumes these classes when the frontend sends _js2py_pointsCallback: it groups point data by trace, builds an InputDeviceState, creates one Points object per trace, optionally creates a selector object, and dispatches to the trace's click, hover, unhover, selection, or deselect callback hooks.

Animation support in this owned area is limited to validators in plotly/animation.py. DurationValidator accepts non-negative numbers for batch animation duration, and EasingValidator enumerates the easing strings accepted by batch_animate. plotly.basedatatypes.BaseFigure constructs these validators during figure initialization for later batch animation contexts.

Axis-spanning shape annotation placement lives in plotly/shapeannotation.py. axis_spanning_shape_annotation accepts an optional annotation, the shape type (vline, hline, vrect, or hrect), the shape arguments, and annotation-prefixed kwargs. It splits annotation kwargs, computes default x, y, xanchor, and yanchor from the shape geometry and annotation_position, and preserves explicit annotation values when present. It is called by BaseFigure._process_multiple_axis_spanning_shapes before add_vline, add_hline, add_vrect, or add_hrect add shapes and annotations. The helper handles numeric values and date/datetime-like values when averaging rectangle or line endpoints.

Tests under tests/test_core/test_subplots/ lock down subplot construction, grid lookup, and empty-subplot discovery. test_make_subplots.py asserts exact layout JSON for spacing, spans, padding, shared axes, insets, titles, 3D specs, and start_cell ordering. test_get_subplot.py covers mixed subplot types, secondary-y lookup, and domain subplot return values. test_find_nonempty_subplots.py checks that non-empty subplot detection accounts for traces, shapes, annotations, and images. Tests under tests/test_core/test_update_objects/ cover selector and row/column behavior for traces, subplot containers, annotations, shapes, and layout images, plus update/overwrite behavior and selector matching semantics.

Coverage / routing

This document owns:

Coupling

  • If plotly/_subplots.py::SubplotRef or _grid_ref shape changes, update plotly.basedatatypes.BaseFigure._set_trace_grid_position, _validate_get_grid_ref, _select_subplot_coordinates, get_subplot, and the row/column selection tests in tests/test_core/test_update_objects/. Those methods index _grid_ref directly and assume a rectangular grid whose populated entries are tuples of SubplotRef objects.
  • If a new subplot type is added in plotly/_subplots.py, update _single_subplot_types, _subplot_prop_named_subplot if its trace reference property is subplot, _subplot_type_for_trace_type, _init_subplot, _get_grid_subplot, and _get_subplot_ref_for_trace together. Otherwise traces may be assigned correctly during construction but fail later in selection, update, or get_subplot paths.
  • If plotly/_subplots.py::_configure_shared_axes changes axis matching or tick-label hiding, verify tests/…/test_make_subplots.py shared-axis expectations for both top-left and bottom-left. The code chooses the first axis differently depending on row direction and secondary-y handling.
  • If title annotation placement in plotly/_subplots.py::_build_subplot_title_annotations changes, verify subplot title, column title, row title, x_title, and y_title tests because all of them write to the same layout.annotations tuple produced during subplot construction.
  • If plotly/shapeannotation.py changes annotation defaults or annotation_ kwarg splitting, verify plotly.basedatatypes.BaseFigure._process_multiple_axis_spanning_shapes and tests/…/test_update_annotations.py. That base figure method expects annotation-prefixed kwargs to be separated before add_shape, and it later rewrites refs to axis-domain refs for axis-spanning shapes.
  • If the frontend callback payload schema changes, update plotly/callbacks.py together with plotly/basewidget.py::_handler_js2py_pointsCallback. The widget instantiates these containers by keyword from frontend dictionaries and silently passes unused keys through **_ only for some classes.
  • If animation batch options add accepted easing names or duration constraints, update both validators in plotly/animation.py and the BaseFigure initialization path that constructs _animation_duration_validator and _animation_easing_validator.
  • Keep plotly/tools.py::make_subplots forwarding semantics aligned with plotly/subplots.py::make_subplots; compatibility callers still enter through plotly.tools, and many core subplot tests exercise that deprecated path.

Risks

  • plotly/_subplots.py::make_subplots and _configure_shared_axes rely on row direction, spans, and secondary-y axis indices lining up with _grid_ref. If row/column iteration changes without updating shared-axis selection, figures can still render but traces, annotations, or updates addressed by row/col will target the wrong axes.
  • plotly/_subplots.py::_set_trace_grid_reference mutates the trace after only checking required reference keys. If _init_subplot produces incorrect trace_kwargs, incompatible trace/subplot combinations fail late when adding traces, and compatible traces can be bound to the wrong subplot.
  • plotly/shapeannotation.py::_mean has custom date handling without importing pandas or numpy. If date parsing changes, date-valued add_vline/add_hrect annotations may compute invalid midpoint strings even though shape creation succeeds.