Graph Objects Data Model
Overview
Plotly graph objects are the schema-backed Python object model behind plotly.graph_objects and plotly.graph_objs. The handwritten runtime lives mostly in plotly/basedatatypes.py, while schema-derived classes live under plotly/graph_objs/**; plotly/…/__init__.py is a public alias layer that lazy-imports the same classes from plotly.graph_objs.
The primary entrypoints are generated plotly.graph_objs._figure.Figure, plotly.graph_objs._figurewidget.FigureWidget, trace classes such as plotly.graph_objs._scatter.Scatter, the generated layout class plotly.graph_objs._layout.Layout, and generated plotly.graph_objs._frame.Frame. Figure subclasses BaseFigure from plotly/basedatatypes.py; FigureWidget subclasses BaseFigureWidget from plotly/basewidget.py; traces subclass BaseTraceType; layout subclasses BaseLayoutType; and frames subclass BaseFrameHierarchyType. Generated files mostly provide public constructor signatures, docstrings, _valid_props, property descriptors that delegate to self[...], and convenience methods like Figure.add_bar(...) that instantiate a trace and call shared figure logic.
BaseFigure.__init__ in plotly/basedatatypes.py normalizes the top-level figure specification. It accepts a sequence of traces, another BaseFigure, or a dict with data, layout, and frames; then obtains the top-level data, layout, and frames validators through ValidatorCache.get_validator("", ...). Validated trace objects are stored in _data_objs, while the user-specified JSON-style trace dictionaries are deep-copied into _data; layout follows the same pattern with _layout_obj and _layout; frames are validated into _frame_objs but are not reparented for widget-style incremental updates. _data_defaults and _layout_defaults hold Plotly.js-computed defaults in widget contexts and are deliberately separate from user-specified _data/_layout.
Each graph object stores explicit properties in a dict returned by BasePlotlyType._props. Orphan objects use their own _orphan_props; once a trace or layout object is attached to a figure, its _parent points at the figure and _props is retrieved from BaseFigure._get_child_props. Nested compound objects are lazy: BasePlotlyType.__getitem__ constructs compound children from validator data_class on first access, caches them in _compound_props or _compound_array_props, and presents arrays as tuples. Property writes go through BasePlotlyType.__setitem__, which uses validators for validation/coercion, updates _props, reparents compound children, and calls _send_prop_set; trace descendants route this to restyle messages, while layout descendants route it to relayout messages.
Validation metadata is centralized in plotly/…/_validators.json. plotly/validator_cache.py loads that JSON lazily into ValidatorCache._json_cache and memoizes validator instances by (parent_path, prop_name). It instantiates classes from _plotly_utils.basevalidators, handles trace type as a LiteralValidator, resolves dynamic layout subplot IDs by mapping layout.xaxis2-style properties to the base xaxis validator, and folds derived JSON entries such as DataValidator/LayoutValidator into their base validator definitions. Compound validators in _plotly_utils/basevalidators.py import generated graph object classes lazily from plotly.graph_objs and coerce dicts or existing graph objects into new generated instances; BaseDataValidator chooses a trace class from the dict type field, defaulting missing type to scatter.
Generated trace classes, for example plotly/…/_scatter.py, declare _path_str ("scatter"), _valid_props, generated property descriptors, and a constructor that accepts either a dict/instance arg plus explicit keyword parameters. The constructor calls super().__init__("scatter"), copies arg, sets _skip_invalid and _validate, applies each known parameter via _set_property, writes the literal type field directly into _props, removes incoming type, then sends leftovers to _process_kwargs so underscore-path kwargs like marker_line_color are parsed by the shared path machinery. plotly/…/_layout.py is generated similarly, but it also declares _subplotid_prop_names and _subplotid_prop_re; BaseLayoutType uses those to accept dynamic subplot containers such as xaxis2, scene3, or legend2, normalizing suffix 1 to the base property (xaxis1 -> xaxis).
BaseFigure implements the higher-level figure operations on top of these objects. add_trace/add_traces validate trace specs, optionally assign subplot references through plotly._subplots, parent traces, extend _data, _data_defaults, and _data_objs, and then call _send_addTraces_msg (a no-op in plain figures). Direct assignment to fig.data is intentionally restricted to a permutation/subset of existing trace objects; new traces must be added with add_trace(s). update, update_layout, and update_traces use BaseFigure._perform_update, which recursively merges compound properties unless overwrite=True. Restyle/relayout paths are strings such as marker.color or layout.shapes[0].x0; _str_to_dict_path_full, _check_path_in_prop_tree, and _is_key_path_compatible parse underscore/dot/bracket paths, produce detailed invalid-property errors, and guard plotly_restyle/plotly_relayout updates before _set_in mutates the underlying JSON-style dict.
Serialization intentionally exports explicit user state, not full Plotly.js defaults. BaseFigure.to_dict deep-copies _data, _layout, and frame _props, includes frames only when non-empty, and converts binary arrays to base64 with _plotly_utils.utils.convert_to_base64; to_plotly_json delegates to to_dict. BasePlotlyType.to_plotly_json deep-copies the object's _props. JSON/HTML/image methods in BaseFigure and BasePlotlyType delegate to plotly.io, so validation and encoding behavior also depends on plotly.io callers.
plotly/basewidget.py adds the FigureWidget integration points. BaseFigureWidget is both a BaseFigure and an anywidget.AnyWidget, sets _set_trace_uid=True so the copied data validator generates UIDs, and disables validation bypass with _allow_disable_validation=False. It exposes synced traitlets for _widget_layout, _widget_data, _config, Python-to-JS messages (_py2js_restyle, _py2js_relayout, _py2js_update, _py2js_addTraces, etc.), and JS-to-Python messages (_js2py_restyle, _js2py_relayout, _js2py_pointsCallback, etc.). Plain BaseFigure message methods are stubs; the widget subclass overrides them to increment edit IDs, set in-process flags, assign a message dict to the synced trait, and immediately reset it to None. JS responses update _layout_defaults/_data_defaults, remove overlapping user props, and dispatch registered callbacks. Frames are explicitly rejected by BaseFigureWidget.frames.
Important tests under tests/test_core/** pin the runtime contracts. tests/…/test_figure.py covers top-level construction, invalid property/value handling, skip_invalid, underscore kwargs, trace addition, and recursive/overwrite update behavior. tests/…/test_validate.py covers _validate=False accepting invalid names/values while still applying underscore path expansion. tests/…/test_dict_path_errors.py exercises the user-facing path parser and invalid-property diagnostics. tests/test_core/test_figure_messages/** covers restyle/relayout/update/add/move/delete message payloads. tests/test_core/test_figure_widget_backend/** covers widget initialization, no-frame validation, and frontend callback translation; test_selection_callbacks.py specifically checks that box/lasso selector state is resolved per trace axis. tests/…/test_thread_safety.py protects the lazy child cache against two concurrent first reads producing different child instances.
Coupling
- If plotly/…/_validators.json changes, also check generated classes under
plotly/graph_objs/**and plotly/validator_cache.py: generated_valid_props,_path_str, constructor parameters, and validator JSON keys must stay aligned orBasePlotlyType._get_validatorwill fail at runtime for schema-backed properties. - If a trace type is added, renamed, or removed in generated plotly/…/_*.py, update the lazy export lists in plotly/…/__init__.py and plotly/…/__init__.py together;
BaseDataValidatorimports trace classes throughplotly.graph_objs, while user code commonly imports throughplotly.graph_objects. - If dynamic subplot property rules change in plotly/…/_layout.py, verify plotly/validator_cache.py and
BaseLayoutTypein plotly/basedatatypes.py: cache lookup strips dynamic suffixes by consultingLayout._subplotid_prop_re, while assignment/access logic normalizes suffix1and tracks_subplotid_props. - If
BasePlotlyType.__getitem__or compound validatordata_classbehavior changes, run tests/…/test_thread_safety.py; the cache usessetdefaultso concurrent first reads must return the same child object that remains attached to its parent. - If path parsing or underscore keyword behavior changes in plotly/basedatatypes.py, verify generated constructors that call
_process_kwargsand tests in tests/…/test_dict_path_errors.py; public kwargs likelayout_title_textandmarker_line_colordepend on the parser's treatment of underscores, brackets, and known underscore-bearing property names such aserror_xandpaper_bgcolor. - If widget message payloads in plotly/basewidget.py change, verify both
BaseFiguremutation paths in plotly/basedatatypes.py and frontend trait names: trace/layout property setters only call_send_*hooks, and plain figures rely on those hooks remaining no-ops while widgets rely on traitlet synchronization.
Risks
- plotly/basedatatypes.py lazy compound child construction is concurrency-sensitive: recent history includes
5ebe3a2d8 fix: make lazy graph object properties thread-safe, and tests/…/test_thread_safety.py asserts concurrent first reads share the same child. If cache publication changes, callbacks or later mutations can target an orphan child that is not backed by the figure's_props. - plotly/basewidget.py selector handling is axis-sensitive: recent history includes
14a069560 Build the selector per trace, and tests/…/test_selection_callbacks.py covers selections onx2/y2. If_selector_for_tracestops resolving ranges against each trace'sxaxis/yaxis, callbacks on other subplots receive the wrong selection orNone. - plotly/basedatatypes.py error-path parsing is fragile because it must make underscore shortcuts and nested paths produce equivalent diagnostics. tests/…/test_dict_path_errors.py encodes exact message substrings; changing
_str_to_dict_path_full,_check_path_in_prop_tree, or_valid_underscore_propertiescan break both error quality and accepted keyword paths.
Coverage / Routing
This doc owns:
- plotly/basedatatypes.py
- plotly/basewidget.py
plotly/graph_objects/**plotly/graph_objs/**plotly/validators/**- plotly/validator_cache.py
- plotly/exceptions.py
tests/test_core/**