Legacy Figure Factory
Overview
The legacy figure factory package in plotly/figure_factory/ exposes a small set of public factory functions from plotly/…/__init__.py: create_dendrogram, create_hexbin_map, create_quiver, create_streamline, create_table, create_ternary_contour, and create_trisurf. Importing the package requires NumPy immediately; pandas gates create_hexbin_map, and scikit-image gates create_ternary_contour with stub functions that raise ImportError when the optional dependency is missing.
plotly/…/utils.py contains the shared validation and formatting helpers used by several factories. validate_equal_length checks parallel array lengths, validate_positive_scalars rejects nonpositive numeric parameters, and flatten converts nested iterables such as meshgrid-style arrays into a flat list. Other helpers validate mixed string/number table-like data, convert interval endpoints, build subplot label annotations, and format English option lists.
plotly/…/_dendrogram.py implements create_dendrogram as a thin Plotly wrapper around scipy.cluster.hierarchy.dendrogram. It validates that SciPy, scipy.spatial, and scipy.cluster.hierarchy are importable, defaults the distance function to scipy.spatial.distance.pdist, and defaults linkage to complete linkage. _Dendrogram.get_dendrogram_traces computes the distance matrix, linkage, and SciPy dendrogram metadata with no_plot=True, then converts each SciPy icoord/dcoord segment into a Plotly scatter line trace with orientation-dependent x/y assignment and sign inversion. _Dendrogram.get_color_dict remaps SciPy color keys, including the newer C0-style cyclic keys, to Plotly RGB strings. Layout construction sets hidden legend, fixed autosize=False, hovermode="closest", linear axes, optional tick labels ordered by the dendrogram leaves, and leaf tick positions inferred from zero-valued branch coordinates.
plotly/…/_quiver.py implements create_quiver as a single Scatter trace in line mode. The public function validates equal-length x, y, u, and v arrays plus positive scale and arrow_scale, then _Quiver flattens nested inputs where possible, scales vector components, computes shaft endpoints, and appends None separators between shaft and arrowhead line segments. When scaleratio is supplied, the returned layout anchors the y-axis to x with yaxis.scaleanchor="x" and yaxis.scaleratio=scaleratio; otherwise the layout only sets hovermode="closest".
plotly/…/_streamline.py implements create_streamline as a single Scatter trace in line mode. validate_streamline requires evenly spaced one-dimensional x and y coordinates and NumPy availability. _Streamline converts inputs to NumPy arrays, rescales the velocity field into grid coordinates, builds a blank occupancy grid of int(30 * density) cells, and traces paths from the grid perimeter inward. Trajectories are integrated forward and backward with a Runge-Kutta routine adapted from Bokeh, stopping at occupied cells, bounds, or a maximum path length; accepted paths are converted back to data coordinates, separated by np.nan, and flattened into one trace. Arrowheads are placed around the one-third point of each streamline and appended to the same trace.
plotly/…/_table.py implements create_table as an annotated heatmap rather than a go.Table. It accepts a list-of-lists or, when pandas is available, a pandas DataFrame. _Table.__init__ converts DataFrame columns into the header row and can insert a header-colored index column. get_table_matrix builds the heatmap z matrix with values 0, 0.5, and 1 for header and alternating row colors, and make_table_annotations places one Plotly layout annotation per cell with bold header/index text and row-level font colors. The returned figure contains a heatmap trace with showscale=False, reversed y-axis, grid-like ticks, no tick labels, and height derived from the number of rows times height_constant.
plotly/…/_ternary_contour.py implements create_ternary_contour. It requires SciPy interpolation and scikit-image contour extraction, prepares barycentric input coordinates of shape (2, N) or (3, N), normalizes 3-coordinate input that sums to either 1 or 100, rejects negative coordinates, and interpolates scalar values on a regular grid. Interpolation happens either in Cartesian barycentric space or, by default, in isometric log-ratio (ilr) space after zero coordinates are replaced by a small delta. _contour_trace uses skimage.measure.find_contours, picks a boundary fill strategy that minimizes spurious contours, sorts contours by area, maps grid contours back to ternary coordinates, and emits scatterternary traces with filled polygons unless coloring="lines". The public factory builds a ternary layout, adds the contour traces, always adds an input-point scatterternary marker trace with opacity 1 only when showmarkers=True, and can add a hidden marker trace solely to display a colorbar when showscale=True.
plotly/…/_trisurf.py implements create_trisurf for triangulated 3D surfaces. It validates and normalizes the colormap with plotly.colors, then trisurf stacks x, y, and z into vertices, indexes triangles by simplices, and assigns face colors. Face coloring defaults to the mean z value per triangle, can be driven by a callable evaluated at each vertex, or can use a list/array the same length as simplices; string and tuple colors in a list are converted to RGB labels. The main surface is a Mesh3d trace with facecolor and triangle indices. If numeric face values and show_colorbar=True, a near-invisible Scatter3d marker trace supplies the colorbar. If plot_edges=True, triangle perimeters are flattened into a Scatter3d line trace with None separators. The returned figure configures a 3D scene with axis background, grid, zeroline colors, dimensions, title, and an aspectratio default of {x: 1, y: 1, z: 1}.
plotly/…/_hexbin_map.py implements create_hexbin_map by combining Plotly Express map functions with custom hexagonal aggregation. build_dataframe normalizes Plotly Express-style arguments, and Narwhals is used to operate across supported dataframe backends. _project_latlon_to_wgs84 and _project_wgs84_to_latlon map geographic coordinates into a projected space where regular hexagons can be computed. _compute_hexbin follows a Matplotlib-inspired two-lattice hexbin algorithm: each point is assigned to the nearer of two offset grids, bins either count points or aggregate a color metric with agg_func, and bins below min_count are dropped. _compute_wgs84_hexbin projects lat/lon, computes hexagons, converts polygon vertices back to lat/lon, and creates stable ids from projected centers. create_hexbin_map builds a GeoJSON FeatureCollection, auto-computes zoom and center from data bounds when omitted, aggregates either once or per animation_frame, builds a choropleth map keyed by hexagon id, and optionally overlays original points with scatter_map traces and matching animation frame data.
No files currently exist under the owned test glob tests/test_core/test_figure_factory/**, so this doc cannot point to in-scope test cases for these factories. Behavior coverage for this assignment is therefore grounded in plotly/figure_factory/** itself.
Coverage / routing
Route changes in these paths to this document:
plotly/figure_factory/**tests/test_core/test_figure_factory/**
Coupling
- If plotly/…/__init__.py changes optional dependency gating, verify the corresponding implementation files still raise or import consistently:
create_hexbin_mapdepends on pandas-compatible dataframe handling in plotly/…/_hexbin_map.py, andcreate_ternary_contourdepends on scikit-image plus SciPy interpolation in plotly/…/_ternary_contour.py. - If the flattening or scalar validation behavior in plotly/…/utils.py changes, recheck plotly/…/_quiver.py and plotly/…/_streamline.py; both accept meshgrid-like data and rely on
validate_equal_length,validate_positive_scalars, andflattenbefore constructing one long line trace with separators. - If Plotly colorscale validation or color conversion APIs change, recheck both plotly/…/_trisurf.py and plotly/…/_ternary_contour.py; each manually converts colors into trace-ready RGB strings and constructs colorbar-compatible colorscales instead of delegating all color handling to graph objects.
- If Plotly Express map argument normalization changes, recheck plotly/…/_hexbin_map.py;
create_hexbin_mappasseslocals()intobuild_dataframe, then assumes returned argument names such aslat,lon,color, andanimation_framecan be used as Narwhals column selectors. - If dataframe backend support changes, recheck plotly/…/_hexbin_map.py; it constructs intermediate Narwhals dataframes, converts aggregated data with
.to_native(), and builds unique GeoJSON ids from stringified projected hexagon centers. - If SciPy dendrogram color keys or output metadata change, recheck
_Dendrogram.get_color_dictand_Dendrogram.get_dendrogram_tracesin plotly/…/_dendrogram.py; trace color selection assumes SciPycolor_listkeys match the explicit old and cyclic key maps.
Risks
- plotly/…/_dendrogram.py has a validation bug at the 2D shape check:
exceptions.PlotlyError("X should be 2-dimensional array.")is constructed but not raised. If callers pass non-2DX, failure will occur later inside SciPy or shape-dependent code rather than at the documented validation point. - plotly/…/_streamline.py checks NumPy availability with
if np is False, butoptional_imports.get_module("numpy")returnsNonewhen unavailable. Ifcreate_streamlineis imported without NumPy in a context that bypasses package-level NumPy gating, laternp.arrayaccess would fail with an attribute error rather than the intendedImportError. - plotly/…/_ternary_contour.py imports
from skimage import measureat module import time even thoughcreate_ternary_contouralso checks for scikit-image later. If plotly/…/__init__.py stops gating this module import, missing scikit-image will fail before the factory can raise its tailoredImportError. - plotly/…/_hexbin_map.py casts aggregated
colorvalues tonw.Int64before plotting. If a customagg_funcreturns non-integral metrics, precision can be lost beforechoropleth_mapreceives the data.