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 viafig.savefig(..., format="png", dpi=fig.dpi)so Matplotlib finalizes positions, optionally closes the Matplotlib figure, then callscrawl_fig().crawl_fig()wraps the figure inrenderer.draw_figure(...)and visits eachfig.axes.crawl_ax()wraps each axes inrenderer.draw_axes(...), then processesax.lines,ax.texts, x/y labels and title, text artists, patches, collections, images, and finally the legend. - plotly/…/renderer.py implements
PlotlyRenderer, a concretemplexporter.renderers.base.Rendererthat turns traversal callbacks into aplotly.graph_objs.Figurestored asself.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()createsgo.Scattertraces withmodeset tolines,markers, orlines+markers. Line color, width, dash, and step drawstyle come frommpltools.convert_dash()andmpltools.convert_drawstyle(). Marker color, symbol, size, and outline come frommpltools.convert_symbol()and marker style extraction in mplexporter/utils.py. Matplotlib labels that are missing or start with_becomename=Noneandshowlegend=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()anddraw_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 usingmpltools.is_bar(). Individual bar patches are buffered inself.current_bars;close_axes()groups them by container anddraw_bar()emits onego.Barper group. Orientation is inferred from rectangle widths/heights, stacked bars setlayout.barmode="stack"and adjust hovermode, date x bars convert x positions to date strings, and uniform gaps becomelayout.bargapthroughmpltools.get_bar_gap(). - Paths and patch collections: non-bar paths are ignored except Matplotlib
StepPatch(ax.stairs) objects, which_draw_step_path()converts into ago.Scatter(mode="lines"), optionallyfill="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, closesZsubpaths explicitly, separates disjoint subpaths withNone, 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/verticalaxline, and two-pointtransform=ax.transAxessegments becomelayout.shapeswith the appropriate axis or axis-domain references (x domain,y domain,x2 domain, etc.). Diagonalaxline, 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 throughmpltools._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 astick0/dtick, non-arithmetic fixed ticks astickvals, fixed/function formatter labels asticktext, 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 Matplotlibnoneto 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.
PlotlyRendererindexes keys such asprops["axes"],props["bounds"],props["xlim"], styledasharray, and collectionstyles["facecolor"]directly rather than through a schema. - If
plotly/matplotlylib/mplexporter/utils.py::export_color()orplotly/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 togo.Scatter,go.Bar, layout axes, annotations, shapes,plot_bgcolor, andpaper_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 MatplotlibBlendedGenericTransformobjects to distinguish data traces, axes-domain segments,axhline,axvline, andaxlinecases. - If axis or tick extraction in
plotly/matplotlylib/mplexporter/utils.py::get_axis_properties()changes, checkplotly/matplotlylib/mpltools.prep_ticks()andprep_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()orPlotlyRenderer.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 whetherstyles["facecolor"]is empty. - If legend traversal in
Exporter.crawl_legend()changes, verify native legend behavior inPlotlyRenderer.open_legend(),draw_marked_line(), anddraw_text(). The renderer suppresses fake legend children only while_processing_legendis true and a visible Matplotlib legend has enabled Plotly's native legend. - If
plotly/tools.py::mpl_to_plotlychanges its entrypoint behavior, keep plotly/…/__init__.py exports aligned. That external entrypoint expectsplotly.matplotlylib.PlotlyRendererandplotly.matplotlylib.Exporterto 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.AxLineor_AxLine,transforms.BlendedGenericTransform, andtrans._x/trans._y). The recent history forplotly/matplotlylibshows a long fix sequence aroundaxhline,axvline,axline, date axes, domain references, and finallyfacee3cf1 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_yaxisasserts 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 insertNoneseparators/closing vertices. If code-step handling changes, contour rings can become visually open or disjoint contour islands can be connected;test_contour_rings_are_closedandtest_disjoint_contour_subpaths_are_separated_by_nonecover this because Plotlylinesmode does not honor SVGZclosure automatically. - Bar conversion in
plotly/matplotlylib/renderer.py::draw_bar()buffers rectangle patches untilclose_axes()and infers orientation/stacking from rectangle geometry. If Matplotlib changes how bar containers expose patches, or if non-bar rectangles are added toax.patches, bars can be dropped or misclassified; generic non-bar paths are intentionally ignored with a warning. plotly/matplotlylib/mplexporter/exporter.py::draw_image()andmplexporter/utils.py::image_to_base64()still prepare image payloads, butplotly/matplotlylib/renderer.py::draw_image()always warns and emits no Plotly output. Any caller expectingimshowconversion throughmpl_to_plotlywill get no image despite traversal tests existing for fake renderers.