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:
- Normalize backward-compatible names (
row_widthtorow_heights,column_widthtocolumn_widths) and reject unknown kwargs. - Validate grid dimensions,
start_cell,specs,insets, shared-axis modes, spacing, row/column sizing, and title lists. - Convert each spec cell into a normalized domain.
start_cellselectsrow_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. - For each non-empty spec cell, call
_init_subplotto create subplot-specific layout containers and a tuple ofSubplotRefvalues. Cartesian subplots createlayout.xaxis*andlayout.yaxis*; secondary-y cartesian cells add a second overlaid right-side y-axis. Single-container subplot types (scene,geo,polar,ternary,map) create alayout.<type>*object with a domain.domaintraces do not create layout keys; theirSubplotRef.trace_kwargscarries the trace-leveldomaininstead. - Apply shared axes through
_configure_shared_axes, which setsmatchesand hides redundant tick labels only on one-cell cartesian spans. Secondary-y axes get a separate pass when any spec requests them. - Build inset subplots from the parent cell domain and add their subplot refs separately for display in the grid string.
- Generate title annotations with
_build_subplot_title_annotationsfor subplot, column, row, x, and y titles. These are stored inlayout.annotationsbefore updating the figure. - Store private figure bookkeeping in
figure.__dict__["_grid_ref"]andfigure.__dict__["_grid_str"]. The grid reference is a rectangular 2D list matching requested rows and columns, where each populated cell contains one or moreSubplotRefobjects and blanks/spanned cells areNone.
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:
- plotly/subplots.py
- plotly/_subplots.py
- plotly/animation.py
- plotly/callbacks.py
- plotly/shapeannotation.py
- plotly/tools.py
tests/test_core/test_subplots/**tests/test_core/test_update_objects/**
Coupling
- If
plotly/_subplots.py::SubplotRefor_grid_refshape changes, updateplotly.basedatatypes.BaseFigure._set_trace_grid_position,_validate_get_grid_ref,_select_subplot_coordinates,get_subplot, and the row/column selection tests intests/test_core/test_update_objects/. Those methods index_grid_refdirectly and assume a rectangular grid whose populated entries are tuples ofSubplotRefobjects. - If a new subplot type is added in plotly/_subplots.py, update
_single_subplot_types,_subplot_prop_named_subplotif its trace reference property issubplot,_subplot_type_for_trace_type,_init_subplot,_get_grid_subplot, and_get_subplot_ref_for_tracetogether. Otherwise traces may be assigned correctly during construction but fail later in selection, update, orget_subplotpaths. - If
plotly/_subplots.py::_configure_shared_axeschanges axis matching or tick-label hiding, verify tests/…/test_make_subplots.py shared-axis expectations for bothtop-leftandbottom-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_annotationschanges, verify subplot title, column title, row title,x_title, andy_titletests because all of them write to the samelayout.annotationstuple produced during subplot construction. - If plotly/shapeannotation.py changes annotation defaults or
annotation_kwarg splitting, verifyplotly.basedatatypes.BaseFigure._process_multiple_axis_spanning_shapesand tests/…/test_update_annotations.py. That base figure method expects annotation-prefixed kwargs to be separated beforeadd_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
BaseFigureinitialization path that constructs_animation_duration_validatorand_animation_easing_validator. - Keep
plotly/tools.py::make_subplotsforwarding semantics aligned withplotly/subplots.py::make_subplots; compatibility callers still enter throughplotly.tools, and many core subplot tests exercise that deprecated path.
Risks
plotly/_subplots.py::make_subplotsand_configure_shared_axesrely 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 byrow/colwill target the wrong axes.plotly/_subplots.py::_set_trace_grid_referencemutates the trace after only checking required reference keys. If_init_subplotproduces incorrecttrace_kwargs, incompatible trace/subplot combinations fail late when adding traces, and compatible traces can be bound to the wrong subplot.plotly/shapeannotation.py::_meanhas custom date handling without importing pandas or numpy. If date parsing changes, date-valuedadd_vline/add_hrectannotations may compute invalid midpoint strings even though shape creation succeeds.