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 / plotly-express

Plotly Express

Overview

Plotly Express is the high-level chart API exposed from plotly/…/__init__.py. Importing plotly.express requires NumPy, re-exports the public px.* chart functions from plotly/…/_chart_types.py, px.imshow from plotly/…/_imshow.py, global px.defaults and px.get_trendline_results from plotly/…/_core.py, special input helpers from plotly/…/_special_inputs.py, and the data, colors, and trendline_functions helper namespaces.

Most px.* chart calls follow the same request flow. A public wrapper in plotly/…/_chart_types.py declares the chart-specific signature, captures locals(), and calls plotly/express/_core.py::make_figure with a graph-object constructor plus optional trace/layout patches. For example, scatter() passes go.Scatter, bar() passes go.Bar with textposition="auto" and barmode, timeline() passes a sentinel constructor string that later becomes go.Bar, hierarchy charts pass go.Sunburst/go.Treemap/go.Icicle, and map/geo/polar/ternary functions choose the corresponding graph-object trace classes. _chart_types.py also assigns generated docstrings with plotly/express/_doc.py::make_docstring, which builds parameter documentation from the central docs map and per-function append/override dictionaries.

plotly/express/_core.py::make_figure is the central assembler. It first applies the default cascade with apply_default_cascade(): unspecified values are filled from mutable px.defaults, then from plotly.io.templates.default or the plotly template, then from template colorways/colorscales, and finally from Plotly Express fallbacks such as plotly.colors.qualitative.D3, plotly.colors.sequential.Viridis, default symbols, line dashes, pattern shapes, and size_max=20. After this cascade, build_dataframe() rewrites user inputs into a Narwhals dataframe and replaces each express argument with a column reference in that dataframe. make_figure() then handles chart-specific data transforms (process_dataframe_hierarchy() for path-based sunburst/treemap/icicle, process_dataframe_pie() for custom category_orders on pie labels, and process_dataframe_timeline() for duration bars), infers trace configuration, groups rows into traces/frames/facets, builds traces, lays out subplots, attaches animation controls, trendline metadata, color axes, and axis configuration, and returns a go.Figure.

Input normalization lives mainly in plotly/express/_core.py::build_dataframe and process_args_into_dataframe. Dataframes and series are converted to narwhals.stable.v1 wrappers. Pandas-like objects keep pandas-specific index/MultiIndex handling; other Narwhals-supported eager dataframes are accepted; interchange-only dataframes are materialized through Arrow with projection pushdown for only needed columns when not in wide mode; PySpark-like objects are converted through toPandas; dict/list/array-like inputs fall back to pandas DataFrame construction. If no dataframe is supplied, list-like arguments are assembled into a dataframe and string/int column references are rejected. process_args_into_dataframe() copies array attributes (dimensions, custom_data, hover_data, path, wide_variable), normalizes hover-data dict values into (format_or_bool, data) tuples, detects name collisions with dataframe columns, creates columns for arrays, indexes, px.Constant, and px.Range, validates equal lengths, and mutates arguments so downstream code only sees column names.

Wide-form support is a first-class path in plotly/express/_core.py::build_dataframe. For cartesian traces, missing x and y or list-like x/y column selections turn on wide mode. The code chooses synthetic or index-derived names for index, value, and variable, escapes names that collide with real columns, validates that melted value columns have compatible dtypes, unpivots via Narwhals, and then rewrites x, y, color, and line_group according to the constructor and orientation. NO_COLOR lets callers suppress the automatic color-by-variable behavior. Tests in tests/…/test_px_wide.py cover implicit/explicit wide mode, internal build_dataframe() rewrites, column/index naming, partial melting, special collisions, mixed dtype errors, and ensuring wide-mode lists passed by callers are not mutated.

Trace and layout inference happens in plotly/express/_core.py::infer_config. It chooses whether color is continuous or grouped/discrete, computes sizeref, auto-detects orientation, assigns histogram histfunc/bin fields, creates text templates for text_auto, sets opacity, marker/line/fill modes, line shapes, geojson patches, marginal arguments, facet/marginal precedence, valid trendline names, ECDF normalization, and grouped mappings for color, symbol, line dash, pattern shape, animation frame, facet row/column, and line group. make_mapping() stores how each grouped variable maps data values to marker/line/facet updates, with IdentityMap support for maps such as color_discrete_map="identity".

make_figure() uses these mappings to compute ordered groups in get_groups_and_orders(), respecting category_orders and first-seen data order. For every group and every TraceSpec, it creates a graph-object trace, applies grouped style/facet/frame updates, computes subplot row/column coordinates including facet_col_wrap and marginals, performs ECDF cumulative transforms if needed, and calls make_trace_kwargs() to fill trace arrays, hovertemplate, customdata, error bars, colors, ids, hierarchy labels, dimensions, histogram labels, and trendline output. It then builds a frame list, creates coloraxis1 when needed, calculates subplot dimensions and marginal sizes in init_figure(), attaches traces/frames with _set_trace_grid_reference, applies the template/layout, configures axes for cartesian, 3D, polar, ternary, geo, and map traces, and installs play/slider controls in configure_animation_controls() when animation_frame produces more than one frame. Tests in tests/…/test_px_input.py and tests/…/test_px_functions.py pin dataframe conversion, hover/customdata behavior, index handling, orientation, histogram labels, hierarchy path aggregation, pie ordering, timeline datetime conversion, and empty histogram behavior.

Trendlines are split between plotly/…/_core.py and plotly/…/__init__.py. infer_config() validates names against the trendline_functions map. make_trace_spec() adds per-trace trendline specs when trendline_scope="trace"; make_figure() separately creates an “Overall Trendline” trace and replicates it across main facets when trendline_scope="overall". make_trace_kwargs() sorts by x, drops missing data, converts date/datetime x-values to Unix epoch seconds for fitting while preserving original plotted x values, casts non-numeric inputs where possible, and invokes the selected trendline function. ols() and lowess() require statsmodels; rolling(), expanding(), and ewm() delegate to pandas Series operations. OLS fit results are accumulated into fig._px_trendlines, which get_trendline_results() returns. tests/…/test_trendline.py owns the behavioral coverage for these hooks.

px.imshow is separate from the tabular make_figure() path and lives in plotly/…/_imshow.py. It still calls apply_default_cascade() and uses init_figure()/configure_animation_controls(), but it directly interprets image arrays and xarray inputs. It accepts 2D single-channel data as go.Heatmap unless binary_string=True, and accepts RGB/RGBA or binary-string image data as go.Image. It detects xarray dimensions and coordinates for labels, supports dataframe index/columns for axis labels, handles facet_col, facet_row, facet_col_wrap, and animation_frame by moving selected axes to the front, infers binary_string=True for multichannel arrays unless a dataframe is supplied, rescales booleans to uint8, lets range_color override zmin/zmax, chooses min/max or dtype-based contrast rescaling, and encodes binary images through plotly.utils.image_array_to_data_uri. The vendored plotly/…/imshow_utils.py provides rescale_intensity() and dtype range helpers copied from scikit-image. tests/…/test_imshow.py covers zmin/zmax heuristics, binary PNG/JPEG output, origin/autorange, xarray labels and slicing, invalid dimensions, hovertemplates, image coordinate constraints, compression, and combined animation/facets.

The helper namespaces are thin adapters. plotly/…/__init__.py re-exports demonstration datasets from plotly.data and declares the Express dataset names. plotly/…/__init__.py re-exports plotly.colors utilities and color namespaces for the documented px.colors API. plotly/…/_special_inputs.py defines IdentityMap, Constant, and Range, which are consumed by _core.py during mapping and dataframe construction.

Coverage/routing

This doc owns:

  • plotly/express/**
  • tests/test_optional/test_px/**
  • tests/test_core/test_px/**

Route changes here when they affect Plotly Express chart wrappers, dataframe/input normalization, trace/layout assembly, faceting, animation, trendlines, imshow/image behavior, express bundled data/colors/doc helpers, or tests dedicated to px behavior.

Coupling

  • If a public chart function signature changes in plotly/…/_chart_types.py, also update plotly/express/_doc.py::docs or the function's docstring append/override map. make_docstring() iterates actual function parameters and indexes the central docs map, so an undocumented new parameter fails at import/docstring-generation time rather than only in generated docs.
  • If a new argument should accept column references or arrays, add it to the appropriate attrable list in plotly/…/_core.py (direct_attrables, array_attrables, group_attrables, or renameable_group_attrables) and update make_trace_kwargs()/infer_config() as needed. build_dataframe() only normalizes names and arrays for fields in these lists, so leaving a field out means downstream trace code will see the raw user object instead of a dataframe column.
  • If dataframe backend support changes in plotly/express/_core.py::build_dataframe, verify tests/…/test_px_input.py and tests/…/conftest.py. Express relies on Narwhals level detection, pandas-like fast paths, Arrow materialization for interchange-only objects, and PySpark toPandas; small conversion changes can alter column names, index preservation, or equality checks used by hover labels.
  • If wide-form naming or melting changes in plotly/express/_core.py::build_dataframe, verify tests/…/test_px_wide.py. The rest of figure assembly assumes wide mode has already converted data to tidy columns named through the index/value/variable logic, including escaped names for collisions and automatic NO_COLOR suppression.
  • If grouped style mappings or category ordering change in plotly/express/_core.py::make_mapping or get_groups_and_orders, verify trace counts, legend titles, facet label order, and animation frame order. make_figure() uses the same orders structure for group sorting, facet labels, color/symbol/dash cycling, and animation slider step order.
  • If trendline function signatures change in plotly/…/__init__.py, also update plotly/express/_core.py::make_trace_kwargs. _core.py calls every trendline function with (trendline_options, x_raw, x_numpy, y_numpy, x_label, y_label, non_missing) and expects (y_out, hover_header, fit_results) with len(y_out) matching the non-missing plotted x values.
  • If plotly/…/_imshow.py image slicing or subplot creation changes, verify both imshow and core subplot behavior. imshow() bypasses make_figure() but reuses _core.py::init_figure() and configure_animation_controls(), so changes to subplot spacing, facet wrapping, or animation controls affect image figures too.
  • If color defaults change in plotly/express/_core.py::apply_default_cascade, check plotly/…/__init__.py exports and tests that assert template-vs-user colorscale precedence, especially tests/test_optional/test_px/test_imshow.py::test_imshow_color_continuous_scale_autocolorscale. Both make_figure() and imshow() track whether the user explicitly provided color_continuous_scale so template autocolorscale=True does not override explicit colorscales.

Risks

  • plotly/express/_core.py::process_dataframe_hierarchy has backend-sensitive aggregation and ordering logic for path-based sunburst/treemap/icicle. If grouping order or null handling changes, hierarchy ids/parents can be reordered or invalid non-leaf rows can slip through; tests/…/test_px_functions.py includes explicit skips for known pandas 3 plus pandas PyArrow constructor issues around hierarchy charts, which is evidence this area is fragile across dataframe backends.
  • plotly/express/_core.py::build_dataframe mutates the args dictionary in place while trying not to mutate caller-provided list-like arguments. If the defensive copies for array_attrables or wide variables are removed, caller inputs can be changed by a chart call; tests/test_optional/test_px/test_px_input.py::test_arguments_not_modified and tests/test_optional/test_px/test_px_wide.py::test_wide_mode_does_not_mutate_x_or_y pin this consequence.
  • plotly/…/_imshow.py chooses different trace types for the same 2D data depending on binary_string. If a change allows pandas/dataframe inputs with binary_string=True or non-numeric coordinates with go.Image, hover values and coordinate placement break because go.Image uses encoded source, x0/y0, and dx/dy rather than raw z, x, and y; test_imshow_dataframe, test_imshow_labels_and_ranges, and test_imshow_hovertemplate cover these edge cases.