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 / matplotlylib-conversion

Matplotlib-to-Plotly conversion bridge (matplotlylib)

Overview

This area owns Plotly's legacy Matplotlib conversion bridge under plotly/matplotlylib/**. The public package surface in plotly/…/__init__.py re-exports PlotlyRenderer from plotly/…/renderer.py and Exporter from plotly/…/exporter.py. The usual entrypoint is outside this owned tree, plotly/tools.py::mpl_to_plotly, which optional-imports plotly.matplotlylib, builds a PlotlyRenderer, runs Exporter(renderer).run(fig), optionally calls resize() / strip_style(), and returns renderer.plotly_fig.

The conversion is split into two layers:

  • plotly/…/exporter.py traverses a Matplotlib Figure. Exporter.run() ensures a canvas exists, renders the figure via fig.savefig(..., format="png", dpi=fig.dpi) so Matplotlib finalizes positions, optionally closes the Matplotlib figure, then calls crawl_fig(). crawl_fig() wraps the figure in renderer.draw_figure(...) and visits each fig.axes. crawl_ax() wraps each axes in renderer.draw_axes(...), then processes ax.lines, ax.texts, x/y labels and title, text artists, patches, collections, images, and finally the legend.
  • plotly/…/renderer.py implements PlotlyRenderer, a concrete mplexporter.renderers.base.Renderer that turns traversal callbacks into a plotly.graph_objs.Figure stored as self.plotly_fig.

mplexporter normalizes Matplotlib objects into renderer-neutral dictionaries before the Plotly renderer sees them. plotly/…/utils.py extracts figure, axes, axis, legend, path, line, marker, text, grid, color, dash, SVG path, and image properties. Exporter.process_transform() classifies coordinates as data, axes, figure, or display by comparing Matplotlib transforms to ax.transData, ax.transAxes, ax.figure.transFigure, or identity, and can also force legend/title transforms into axes coordinates. That coordinate code is central to PlotlyRenderer: most trace output only happens for data coordinates, while selected axes/display cases become annotations or layout shapes.

PlotlyRenderer.open_figure() initializes a go.Figure, copies Matplotlib pixel size from figwidth * dpi and figheight * dpi, disables autosize, sets hovermode="closest", defaults showlegend=False, copies the figure background into layout.paper_bgcolor, and derives Plotly margins from the union of Matplotlib axes bounds via mpltools.get_axes_bounds(). PlotlyRenderer.open_axes() increments an axis counter, stores current axes state, discovers Matplotlib bar containers, copies the axes patch background into layout.plot_bgcolor when visible, creates xaxisN/yaxisN layout objects anchored to each other, and merges axis properties from mpltools.prep_xy_axis(). It also maps displayed-side spines into linecolor, showline, mirror, and tick visibility, detects overlaid axes such as twinx()/twiny() only when Matplotlib axes share identical bounds, hides invisible axes, and tracks whether the current x axis is a date axis.

Supported output is mostly Plotly traces plus a few layout features:

  • Lines and markers: PlotlyRenderer.draw_marked_line() creates go.Scatter traces with mode set to lines, markers, or lines+markers. Line color, width, dash, and step drawstyle come from mpltools.convert_dash() and mpltools.convert_drawstyle(). Marker color, symbol, size, and outline come from mpltools.convert_symbol() and marker style extraction in mplexporter/utils.py. Matplotlib labels that are missing or start with _ become name=None and showlegend=False.
  • Legends: open_legend() enables Plotly's native legend only when the Matplotlib legend exists and is visible. While processing a visible legend, draw_marked_line() and draw_text() suppress fake legend geometry/text instead of turning legend children into Plotly shapes/annotations.
  • Bars and histograms: draw_path() recognizes bars only by membership in the current axes' BarContainers using mpltools.is_bar(). Individual bar patches are buffered in self.current_bars; close_axes() groups them by container and draw_bar() emits one go.Bar per group. Orientation is inferred from rectangle widths/heights, stacked bars set layout.barmode="stack" and adjust hovermode, date x bars convert x positions to date strings, and uniform gaps become layout.bargap through mpltools.get_bar_gap().
  • Paths and patch collections: non-bar paths are ignored except Matplotlib StepPatch (ax.stairs) objects, which _draw_step_path() converts into a go.Scatter(mode="lines"), optionally fill="toself", preserving label/showlegend behavior and date x conversion. Data-coordinate path collections with data offsets become scatter markers. Data-coordinate path collections with no facecolors become grouped line traces via _draw_line_collection(); this supports contour/event/stem-style line collections, closes Z subpaths explicitly, separates disjoint subpaths with None, groups consecutive same-style paths, preserves per-path edge color/line width/dash, and hides them from the legend. Data-coordinate path collections with facecolors become filled polygon scatter traces via _draw_filled_path_collection(), used by violin bodies, pcolor rectangles, stackplot, fill_between, and contourf-style fills.
  • Reference lines and axes-coordinate segments: draw_marked_line() routes qualifying two-point non-data lines through _draw_axes_line(). axhline, axvline, horizontal/vertical axline, and two-point transform=ax.transAxes segments become layout.shapes with the appropriate axis or axis-domain references (x domain, y domain, x2 domain, etc.). Diagonal axline, marker-only non-data lines, and non-two-point axes/display lines are skipped with warnings.
  • Text: draw_text() emits Plotly axis titles for x/y labels, a layout title for a single-subplot title, paper annotations for multi-subplot titles and non-data text, and data-referenced annotations for in-range data text. It warns when text corners fall outside the Matplotlib figure bounds. Font color and size are copied through mpltools._export_color() and the Matplotlib text style.
  • Axes, ticks, grids, colors, and dates: mpltools.prep_xy_axis() maps Matplotlib scale, range, grid visibility, side, tick label font, and domain into Plotly axis dictionaries. mpltools.prep_ticks() exports arithmetic linear/log tick spacing as tick0/dtick, non-arithmetic fixed ticks as tickvals, fixed/function formatter labels as ticktext, base-10 log ranges as log10 ranges, and x date axes as Plotly date axes with date-string ranges/ticks. mpltools._export_color() is the final guard for Plotly-compatible colors, translating Matplotlib none to transparent black and combining/overriding alpha for hex/rgb/rgba inputs.

Known limitations are explicit in the code. PlotlyRenderer.draw_image() always warns and does not add image output, even though mplexporter/exporter.py can produce base64 image data. Generic patches that are not recognized bars or StepPatch are ignored with a warning. Path collections outside data coordinates are skipped. PlotlyRenderer handles date conversion only for x coordinates (self.x_is_mpl_date); date y reference lines remain numeric Matplotlib date values. mpltools.prep_ticks() converts non-base-10 log axes back to linear with a warning. resize() deletes width, height, autosize, and margin from the generated layout, while strip_style() now only logs that stripping style is unsupported.

The owned tree also includes alternate mplexporter renderers that are not the Plotly conversion path. plotly/…/base.py defines the renderer callback contract and default fallbacks: marked lines can split into line and marker callbacks, lines can become paths, markers can become repeated paths, and path collections can iterate into paths unless subclasses override. plotly/…/fake_renderer.py provides FakeRenderer and FullFakeRenderer for traversal tests. plotly/…/vega_renderer.py and vincent_renderer.py are small experimental converters for line/marker data-coordinate plots, exposed by fig_to_vega() and fig_to_vincent() through plotly/…/__init__.py. plotly/…/tools.py only provides notebook JavaScript setup for Vega.

Tests are concentrated in two layers. plotly/…/test_basic.py verifies traversal order and renderer fallback behavior with fake renderers for lines, markers, scatter collections, text, paths, bare plt.Figure, multi-axes, images, legends, and blended transforms. plotly/…/test_utils.py verifies SVG path extraction, line dash extraction, and fixed tick formatter metadata. plotly/…/test_renderer.py exercises the end-to-end plotly.tools.mpl_to_plotly() path for native legends, line/marker modes, step drawstyles, spines/mirroring/tick visibility, twin axes and shared subplots, path collections (violin, pcolor, eventplot, stackplot, fill_between, contour/contourf/stem), color and alpha conversion, date axes/ticks, stairs/StepPatch output, backgrounds, histograms/bargap, reference-line layout shapes, dash conversion, tick label color, and contour grouping differences across Matplotlib versions.

Coverage / routing

This document owns and should route reviews for:

  • plotly/matplotlylib/**

Use it for changes to Matplotlib traversal (mplexporter/exporter.py), renderer callback contracts and alternate renderers (mplexporter/renderers/**), property extraction (mplexporter/utils.py), Plotly conversion behavior (renderer.py), conversion helpers (mpltools.py), and the tests under plotly/matplotlylib/**/tests/.

Coupling

  • If plotly/…/exporter.py changes the property dictionaries or coordinate codes passed to renderer callbacks, update plotly/…/renderer.py and plotly/…/mpltools.py together. PlotlyRenderer indexes keys such as props["axes"], props["bounds"], props["xlim"], style dasharray, and collection styles["facecolor"] directly rather than through a schema.
  • If plotly/matplotlylib/mplexporter/utils.py::export_color() or plotly/matplotlylib/mpltools._export_color() changes color formats, run the renderer tests that assert Plotly accepts transparent, hex, rgb, rgba, background, tick label, marker, and contour colors. renderer.py assumes _export_color() is the final compatibility layer before assigning colors to go.Scatter, go.Bar, layout axes, annotations, shapes, plot_bgcolor, and paper_bgcolor.
  • If Matplotlib transform handling in Exporter.process_transform() changes, verify reference-line and annotation behavior in plotly/…/renderer.py. _draw_axes_line() relies on exact coordinate classifications and on Matplotlib BlendedGenericTransform objects to distinguish data traces, axes-domain segments, axhline, axvline, and axline cases.
  • If axis or tick extraction in plotly/matplotlylib/mplexporter/utils.py::get_axis_properties() changes, check plotly/matplotlylib/mpltools.prep_ticks() and prep_xy_axis(). The latter expects tick values, tick formats, scale, label font color/size, grid metadata, and side to already be normalized, and silently changes Plotly tick mode/range behavior based on those fields.
  • If collection processing changes in Exporter.draw_collection() or PlotlyRenderer.draw_path_collection(), verify both scatter-like collections and path-based collections. Offset-coordinate collections become marker traces, while path-coordinate collections become either line collections or filled polygons based only on whether styles["facecolor"] is empty.
  • If legend traversal in Exporter.crawl_legend() changes, verify native legend behavior in PlotlyRenderer.open_legend(), draw_marked_line(), and draw_text(). The renderer suppresses fake legend children only while _processing_legend is true and a visible Matplotlib legend has enabled Plotly's native legend.
  • If plotly/tools.py::mpl_to_plotly changes its entrypoint behavior, keep plotly/…/__init__.py exports aligned. That external entrypoint expects plotly.matplotlylib.PlotlyRenderer and plotly.matplotlylib.Exporter to be importable from the package root.

Risks

  • Reference-line conversion in plotly/…/renderer.py is fragile because it depends on Matplotlib private/implementation-specific transforms and class names (mlines.AxLine or _AxLine, transforms.BlendedGenericTransform, and trans._x / trans._y). The recent history for plotly/matplotlylib shows a long fix sequence around axhline, axvline, axline, date axes, domain references, and finally facee3cf1 Drop support for diagonal axline shapes; changing this path can easily make lines disappear or bind to the wrong subplot/domain.
  • Date handling is asymmetric in plotly/…/renderer.py: _convert_x_dates() is applied to x values for traces, bars, line/fill collections, stairs, and vertical reference lines, but there is no equivalent y-date conversion. plotly/matplotlylib/tests/test_renderer.py::test_axhline_on_date_yaxis asserts the y value remains a numeric Matplotlib date, so adding y-date conversion would change current output semantics.
  • Path collection rendering in plotly/matplotlylib/renderer.py::_draw_line_collection() must interpret SVG path codes and manually insert None separators/closing vertices. If code-step handling changes, contour rings can become visually open or disjoint contour islands can be connected; test_contour_rings_are_closed and test_disjoint_contour_subpaths_are_separated_by_none cover this because Plotly lines mode does not honor SVG Z closure automatically.
  • Bar conversion in plotly/matplotlylib/renderer.py::draw_bar() buffers rectangle patches until close_axes() and infers orientation/stacking from rectangle geometry. If Matplotlib changes how bar containers expose patches, or if non-bar rectangles are added to ax.patches, bars can be dropped or misclassified; generic non-bar paths are intentionally ignored with a warning.
  • plotly/matplotlylib/mplexporter/exporter.py::draw_image() and mplexporter/utils.py::image_to_base64() still prepare image payloads, but plotly/matplotlylib/renderer.py::draw_image() always warns and emits no Plotly output. Any caller expecting imshow conversion through mpl_to_plotly will get no image despite traversal tests existing for fake renderers.