From fb6e9c125d8159c77549df893cc0eb8c24d98fef Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Wed, 2 Sep 2026 20:56:10 +0000 Subject: [PATCH 1/7] Separate filled path collection subpaths with null coordinates --- plotly/matplotlylib/renderer.py | 60 ++++++++++++++++++++-- plotly/matplotlylib/tests/test_renderer.py | 24 ++++++++- 2 files changed, 78 insertions(+), 6 deletions(-) diff --git a/plotly/matplotlylib/renderer.py b/plotly/matplotlylib/renderer.py index 0a3c829945..5afc6a1684 100644 --- a/plotly/matplotlylib/renderer.py +++ b/plotly/matplotlylib/renderer.py @@ -13,6 +13,7 @@ import matplotlib.patches as mpatches from matplotlib import lines as mlines from matplotlib import transforms +import numpy as np import plotly.graph_objs as go from plotly.matplotlylib.mplexporter import Renderer from plotly.matplotlylib import mpltools @@ -99,12 +100,21 @@ def __init__(self): self.axes_list = [] def _convert_x_dates(self, x): - """Convert x values to date strings when the x-axis is a date axis.""" + """Convert x values to date strings when the x-axis is a date axis. + + None values (subpath separators) stay None. + """ if self.x_is_mpl_date: formatter = ( self.current_mpl_ax.get_xaxis().get_major_formatter().__class__.__name__ ) - x = mpltools.mpl_dates_to_datestrings(x, formatter) + if any(val is None for val in x): + valid_x = [val for val in x if val is not None] + converted = mpltools.mpl_dates_to_datestrings(valid_x, formatter) + conv_iter = iter(converted) + x = [next(conv_iter) if val is not None else None for val in x] + else: + x = mpltools.mpl_dates_to_datestrings(x, formatter) return x def open_figure(self, fig, props): @@ -851,7 +861,11 @@ def flush(): flush() def _draw_filled_path_collection(self, props): - """Draw a path collection (e.g. violin plot bodies) as filled polygons.""" + """Draw a path collection (e.g. violin plot bodies) as filled polygons. + + Each path becomes one trace, with None separating its disjoint + subpaths (e.g. the islands and holes of a contourf band). + """ facecolors = mpltools.convert_rgba_array(props["styles"]["facecolor"]) edgecolors = mpltools.convert_rgba_array(props["styles"]["edgecolor"]) linewidths = mpltools.convert_linewidth_array(props["styles"]["linewidth"]) @@ -860,10 +874,46 @@ def _draw_filled_path_collection(self, props): facecolor = _per_path(facecolors, i, "rgba(0,0,0,0)") edgecolor = _per_path(edgecolors, i, "rgba(0,0,0,0)") linewidth = _per_path(linewidths, i, 0) + subpaths = [] + current = [] + closed = False + vi = 0 + for c in codes: + if c == "M": + if current: + subpaths.append((current, closed)) + current = [verts[vi]] + closed = False + vi += 1 + elif c == "Z": + closed = True + else: + current.append(verts[vi]) + vi += 1 + if current: + subpaths.append((current, closed)) + + xs = [] + ys = [] + for sub, cl in subpaths: + if len(sub) < 2: + continue + if xs: + xs.append(None) + ys.append(None) + if cl and not np.allclose(sub[0], sub[-1]): + sub = sub + [sub[0]] + xs.extend([v[0] for v in sub]) + ys.extend([v[1] for v in sub]) + + if not xs and len(verts) > 0: + xs = [v[0] for v in verts] + ys = [v[1] for v in verts] + self.plotly_fig.add_trace( go.Scatter( - x=self._convert_x_dates([v[0] for v in verts]), - y=[v[1] for v in verts], + x=self._convert_x_dates(xs), + y=ys, mode="lines", line=go.scatter.Line( color=_export_color(edgecolor), width=linewidth diff --git a/plotly/matplotlylib/tests/test_renderer.py b/plotly/matplotlylib/tests/test_renderer.py index 90f73bff36..9246985d79 100644 --- a/plotly/matplotlylib/tests/test_renderer.py +++ b/plotly/matplotlylib/tests/test_renderer.py @@ -528,7 +528,8 @@ def test_contour_lines_convert(): def test_contourf_bands_render(): - """Contourf bands (multi-subpath collections) must render as fills.""" + """Contourf bands (multi-subpath collections) must render as fills with + None separating disjoint subpaths.""" x = np.linspace(-3, 3, 30) X, Y = np.meshgrid(x, x) fig, ax = plt.subplots() @@ -536,6 +537,27 @@ def test_contourf_bands_render(): plotly_fig = tls.mpl_to_plotly(fig) filled = [t for t in plotly_fig.data if t.fill == "toself"] assert len(filled) > 0 + assert any(None in t.x for t in filled) + assert any(None in t.y for t in filled) + + +def test_contourf_bands_date_xaxis(): + """Contourf bands on a date x-axis export date strings, with None + separating disjoint subpaths.""" + dates = [ + datetime.datetime(2023, 1, 1) + datetime.timedelta(days=i) for i in range(30) + ] + y = np.linspace(-3, 3, 30) + X, Y = np.meshgrid(np.linspace(-3, 3, 30), y) + fig, ax = plt.subplots() + ax.contourf(dates, y, np.sin(X) * np.cos(Y), 10) + plotly_fig = tls.mpl_to_plotly(fig) + filled = [t for t in plotly_fig.data if t.fill == "toself"] + split = [t for t in filled if None in t.x] + assert len(split) > 0 + for t in split: + assert [v is None for v in t.x] == [v is None for v in t.y] + assert all(isinstance(v, str) for v in t.x if v is not None) def test_axis_linecolor_defaults_to_black(): From 5f203b7d58fe80af8b6b4733fcd93fe9f9f537f4 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Mon, 26 Oct 2026 14:53:47 +0000 Subject: [PATCH 2/7] Step over all Bezier vertices when splitting filled path subpaths --- plotly/matplotlylib/renderer.py | 78 ++++++++++------------ plotly/matplotlylib/tests/test_renderer.py | 37 ++++++++++ 2 files changed, 72 insertions(+), 43 deletions(-) diff --git a/plotly/matplotlylib/renderer.py b/plotly/matplotlylib/renderer.py index 5afc6a1684..93adfc1311 100644 --- a/plotly/matplotlylib/renderer.py +++ b/plotly/matplotlylib/renderer.py @@ -42,6 +42,39 @@ def _per_path(values, i, default): return values[i % n] if n else default +# In SVG paths, codes carry different numbers of vertices: +# M/L: 1, C: 3 (cubic curve), S: 2 (smooth/quad curve), Z: 0. +_VERTICES_PER_CODE = {"M": 1, "L": 1, "C": 3, "S": 2, "Z": 0} + + +def _split_subpaths(verts, codes): + """Split SVG path vertices into subpaths, one per "M" code. + + Returns a list of (vertices, closed) pairs; `closed` is True for + subpaths that have a "Z" code. + """ + subpaths = [] + current = [] + closed = False + vi = 0 + for c in codes: + step = _VERTICES_PER_CODE.get(c, 1) + if c == "M": + if current: + subpaths.append((current, closed)) + current = [verts[vi]] + closed = False + vi += 1 + elif c == "Z": + closed = True + else: + current.extend(verts[vi : vi + step]) + vi += step + if current: + subpaths.append((current, closed)) + return subpaths + + def _convert_collection_dash(linestyle): """Convert a matplotlib collection line style to a plotly dash string. @@ -801,31 +834,9 @@ def flush(): # a path may contain several disjoint lines (e.g. contour lines # of the same level); separate disjoint subpaths with None so # plotly does not connect them. - # In SVG paths, codes carry different numbers of vertices: - # M/L: 1, C: 3 (cubic curve), S: 2 (smooth/quad curve), Z: 0. - code_steps = {"M": 1, "L": 1, "C": 3, "S": 2, "Z": 0} - subpaths = [] - current = [] - closed = False - vi = 0 - for c in codes: - step = code_steps.get(c, 1) - if c == "M": - if current: - subpaths.append((current, closed)) - current = [verts[vi]] - closed = False - vi += 1 - elif c == "Z": - closed = True - else: - current.extend(verts[vi : vi + step]) - vi += step - if current: - subpaths.append((current, closed)) path_x = [] path_y = [] - for sub, closed in subpaths: + for sub, closed in _split_subpaths(verts, codes): if len(sub) < 2: continue # a closed subpath (Z code) must be closed explicitly since @@ -874,28 +885,9 @@ def _draw_filled_path_collection(self, props): facecolor = _per_path(facecolors, i, "rgba(0,0,0,0)") edgecolor = _per_path(edgecolors, i, "rgba(0,0,0,0)") linewidth = _per_path(linewidths, i, 0) - subpaths = [] - current = [] - closed = False - vi = 0 - for c in codes: - if c == "M": - if current: - subpaths.append((current, closed)) - current = [verts[vi]] - closed = False - vi += 1 - elif c == "Z": - closed = True - else: - current.append(verts[vi]) - vi += 1 - if current: - subpaths.append((current, closed)) - xs = [] ys = [] - for sub, cl in subpaths: + for sub, cl in _split_subpaths(verts, codes): if len(sub) < 2: continue if xs: diff --git a/plotly/matplotlylib/tests/test_renderer.py b/plotly/matplotlylib/tests/test_renderer.py index 9246985d79..ee473a09fb 100644 --- a/plotly/matplotlylib/tests/test_renderer.py +++ b/plotly/matplotlylib/tests/test_renderer.py @@ -560,6 +560,43 @@ def test_contourf_bands_date_xaxis(): assert all(isinstance(v, str) for v in t.x if v is not None) +def test_filled_path_collection_curve_codes(): + """Filled paths with Bezier curve codes export every vertex of each + subpath, so the curved outline spans its full extent and the following + subpath keeps its own vertices.""" + from matplotlib.collections import PatchCollection + from matplotlib.patches import PathPatch + from matplotlib.path import Path + + circle = Path.circle(center=(1, 1), radius=0.5) + square = Path( + [(2, 0.5), (3, 0.5), (3, 1.5), (2, 1.5), (2, 0.5)], + [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY], + ) + fig, ax = plt.subplots() + ax.add_collection( + PatchCollection([PathPatch(Path.make_compound_path(circle, square))]) + ) + ax.set_xlim(0, 4) + ax.set_ylim(0, 2) + plotly_fig = tls.mpl_to_plotly(fig) + (trace,) = [t for t in plotly_fig.data if t.fill == "toself"] + split = list(trace.x).index(None) + circle_x = trace.x[:split] + circle_y = trace.y[:split] + assert min(circle_x) == pytest.approx(0.5, abs=0.02) + assert max(circle_x) == pytest.approx(1.5, abs=0.02) + assert min(circle_y) == pytest.approx(0.5, abs=0.02) + assert max(circle_y) == pytest.approx(1.5, abs=0.02) + assert list(zip(trace.x[split + 1 :], trace.y[split + 1 :])) == [ + (2, 0.5), + (3, 0.5), + (3, 1.5), + (2, 1.5), + (2, 0.5), + ] + + def test_axis_linecolor_defaults_to_black(): fig, ax = plt.subplots() ax.plot([0, 1], [0, 1]) From 24e8759a65d710d181193ebd6c1d1aed3e24f0f6 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Mon, 26 Oct 2026 14:55:11 +0000 Subject: [PATCH 3/7] Add changelog entry --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32590d344f..ff21fdc8ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ This project adheres to [Semantic Versioning](http://semver.org/). - Fix `convert_dash` mapping dotted lines (`linestyle=':'`) to invalid `'circle'` in Plotly, correctly converting them to `'dot'` and preserving custom dash patterns as pixel lists, [[#5719](https://github.com/plotly/plotly.py/pull/5719)] with thanks to @robertoffmoura for the contribution! - Fix `px.sunburst`, `px.treemap` and `px.icicle` listing sectors in a different order on every run when `path` is used with a Polars DataFrame; sectors now follow their order of first appearance for all dataframe backends [[#5766](https://github.com/plotly/plotly.py/pull/5766)], with thanks to @Irahan2 for the contribution! - Fix `mpl_to_plotly` conversion of matplotlib contour lines and line collections: close contour rings ending with `Z` codes, support dash styles, convert date x-axes, separate disjoint subpaths with `None` separators, hide line collection traces from the legend by default, and group consecutive same-style lines into single traces [[#5770](https://github.com/plotly/plotly.py/pull/5770)], with thanks to @robertoffmoura for the contribution! +- Fix `mpl_to_plotly` drawing matplotlib filled contour plots (`plt.contourf`) with spurious wedges joining the disjoint regions of each band by separating the subpaths of filled path collections with `None`, including on date x-axes, with thanks to @robertoffmoura for the contribution! ## [7.1.0] - 2026-09-15 From 0b5cd596a6bdb525ce41afc7c11e2c1d64a4a725 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Wed, 28 Oct 2026 17:53:52 +0000 Subject: [PATCH 4/7] Close filled path subpaths with the line collection rule A closed subpath of a filled path collection now always gets its first vertex appended, as in _draw_line_collection. The np.allclose check compared with a relative tolerance, so on large coordinates (e.g. mpl date numbers) a closing edge up to ~0.19 days long was dropped from the outline. --- plotly/matplotlylib/renderer.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/plotly/matplotlylib/renderer.py b/plotly/matplotlylib/renderer.py index 93adfc1311..dce23236c5 100644 --- a/plotly/matplotlylib/renderer.py +++ b/plotly/matplotlylib/renderer.py @@ -13,7 +13,6 @@ import matplotlib.patches as mpatches from matplotlib import lines as mlines from matplotlib import transforms -import numpy as np import plotly.graph_objs as go from plotly.matplotlylib.mplexporter import Renderer from plotly.matplotlylib import mpltools @@ -893,7 +892,7 @@ def _draw_filled_path_collection(self, props): if xs: xs.append(None) ys.append(None) - if cl and not np.allclose(sub[0], sub[-1]): + if cl: sub = sub + [sub[0]] xs.extend([v[0] for v in sub]) ys.extend([v[1] for v in sub]) From 90bb1d436522ec2d8188a542e4438dcf2366d18c Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Wed, 28 Oct 2026 17:54:47 +0000 Subject: [PATCH 5/7] Share subpath joining between line and filled path collections _draw_line_collection and _draw_filled_path_collection each split a path into subpaths, dropped short ones, closed Z subpaths and joined them with None. Both now call _join_subpaths. --- plotly/matplotlylib/renderer.py | 58 +++++++++++++++------------------ 1 file changed, 27 insertions(+), 31 deletions(-) diff --git a/plotly/matplotlylib/renderer.py b/plotly/matplotlylib/renderer.py index dce23236c5..f07ce4bb6a 100644 --- a/plotly/matplotlylib/renderer.py +++ b/plotly/matplotlylib/renderer.py @@ -74,6 +74,29 @@ def _split_subpaths(verts, codes): return subpaths +def _join_subpaths(verts, codes): + """Return the x and y values of a path's subpaths as two lists, with + None between consecutive subpaths. + + A closed subpath (Z code) ends with its first vertex repeated, since + plotly's lines mode draws only the segments between the given points. + Subpaths with fewer than 2 vertices are skipped. + """ + xs = [] + ys = [] + for sub, closed in _split_subpaths(verts, codes): + if len(sub) < 2: + continue + if closed: + sub = sub + [sub[0]] + if xs: + xs.append(None) + ys.append(None) + xs.extend(v[0] for v in sub) + ys.extend(v[1] for v in sub) + return xs, ys + + def _convert_collection_dash(linestyle): """Convert a matplotlib collection line style to a plotly dash string. @@ -831,26 +854,11 @@ def flush(): for i, (verts, codes) in enumerate(props["paths"]): # a path may contain several disjoint lines (e.g. contour lines - # of the same level); separate disjoint subpaths with None so - # plotly does not connect them. - path_x = [] - path_y = [] - for sub, closed in _split_subpaths(verts, codes): - if len(sub) < 2: - continue - # a closed subpath (Z code) must be closed explicitly since - # plotly's lines mode does not close the loop - if closed: - sub = sub + [sub[0]] - sub_x = self._convert_x_dates([v[0] for v in sub]) - sub_y = [v[1] for v in sub] - if path_x: - path_x.append(None) - path_y.append(None) - path_x.extend(sub_x) - path_y.extend(sub_y) + # of the same level), separated by None + path_x, path_y = _join_subpaths(verts, codes) if not path_x: continue + path_x = self._convert_x_dates(path_x) edgecolor = _per_path(edgecolors, i, "rgba(0,0,0,0)") linewidth = _per_path(linewidths, i, 0) @@ -884,19 +892,7 @@ def _draw_filled_path_collection(self, props): facecolor = _per_path(facecolors, i, "rgba(0,0,0,0)") edgecolor = _per_path(edgecolors, i, "rgba(0,0,0,0)") linewidth = _per_path(linewidths, i, 0) - xs = [] - ys = [] - for sub, cl in _split_subpaths(verts, codes): - if len(sub) < 2: - continue - if xs: - xs.append(None) - ys.append(None) - if cl: - sub = sub + [sub[0]] - xs.extend([v[0] for v in sub]) - ys.extend([v[1] for v in sub]) - + xs, ys = _join_subpaths(verts, codes) if not xs and len(verts) > 0: xs = [v[0] for v in verts] ys = [v[1] for v in verts] From b3f2ed3cebf944af743840e31f9b11ee3e2a542e Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Wed, 28 Oct 2026 17:55:21 +0000 Subject: [PATCH 6/7] Convert date x-values before joining subpaths Callers convert a path's x values once and pass x and y to _join_subpaths, which inserts the None separators after conversion. _convert_x_dates is back to its single-list form without the None splicing. --- plotly/matplotlylib/renderer.py | 33 ++++++++++++++------------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/plotly/matplotlylib/renderer.py b/plotly/matplotlylib/renderer.py index f07ce4bb6a..c4bd688aa2 100644 --- a/plotly/matplotlylib/renderer.py +++ b/plotly/matplotlylib/renderer.py @@ -74,7 +74,7 @@ def _split_subpaths(verts, codes): return subpaths -def _join_subpaths(verts, codes): +def _join_subpaths(x, y, codes): """Return the x and y values of a path's subpaths as two lists, with None between consecutive subpaths. @@ -84,7 +84,7 @@ def _join_subpaths(verts, codes): """ xs = [] ys = [] - for sub, closed in _split_subpaths(verts, codes): + for sub, closed in _split_subpaths(list(zip(x, y)), codes): if len(sub) < 2: continue if closed: @@ -155,21 +155,12 @@ def __init__(self): self.axes_list = [] def _convert_x_dates(self, x): - """Convert x values to date strings when the x-axis is a date axis. - - None values (subpath separators) stay None. - """ + """Convert x values to date strings when the x-axis is a date axis.""" if self.x_is_mpl_date: formatter = ( self.current_mpl_ax.get_xaxis().get_major_formatter().__class__.__name__ ) - if any(val is None for val in x): - valid_x = [val for val in x if val is not None] - converted = mpltools.mpl_dates_to_datestrings(valid_x, formatter) - conv_iter = iter(converted) - x = [next(conv_iter) if val is not None else None for val in x] - else: - x = mpltools.mpl_dates_to_datestrings(x, formatter) + x = mpltools.mpl_dates_to_datestrings(x, formatter) return x def open_figure(self, fig, props): @@ -855,10 +846,13 @@ def flush(): for i, (verts, codes) in enumerate(props["paths"]): # a path may contain several disjoint lines (e.g. contour lines # of the same level), separated by None - path_x, path_y = _join_subpaths(verts, codes) + path_x, path_y = _join_subpaths( + self._convert_x_dates([v[0] for v in verts]), + [v[1] for v in verts], + codes, + ) if not path_x: continue - path_x = self._convert_x_dates(path_x) edgecolor = _per_path(edgecolors, i, "rgba(0,0,0,0)") linewidth = _per_path(linewidths, i, 0) @@ -892,14 +886,15 @@ def _draw_filled_path_collection(self, props): facecolor = _per_path(facecolors, i, "rgba(0,0,0,0)") edgecolor = _per_path(edgecolors, i, "rgba(0,0,0,0)") linewidth = _per_path(linewidths, i, 0) - xs, ys = _join_subpaths(verts, codes) + x = self._convert_x_dates([v[0] for v in verts]) + y = [v[1] for v in verts] + xs, ys = _join_subpaths(x, y, codes) if not xs and len(verts) > 0: - xs = [v[0] for v in verts] - ys = [v[1] for v in verts] + xs, ys = x, y self.plotly_fig.add_trace( go.Scatter( - x=self._convert_x_dates(xs), + x=xs, y=ys, mode="lines", line=go.scatter.Line( From 723f1414530652405a8b82cfbe0b5ae09d307131 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Wed, 28 Oct 2026 18:41:19 +0000 Subject: [PATCH 7/7] Add PR link to changelog entry --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff21fdc8ce..e3dff8728f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ This project adheres to [Semantic Versioning](http://semver.org/). - Fix `convert_dash` mapping dotted lines (`linestyle=':'`) to invalid `'circle'` in Plotly, correctly converting them to `'dot'` and preserving custom dash patterns as pixel lists, [[#5719](https://github.com/plotly/plotly.py/pull/5719)] with thanks to @robertoffmoura for the contribution! - Fix `px.sunburst`, `px.treemap` and `px.icicle` listing sectors in a different order on every run when `path` is used with a Polars DataFrame; sectors now follow their order of first appearance for all dataframe backends [[#5766](https://github.com/plotly/plotly.py/pull/5766)], with thanks to @Irahan2 for the contribution! - Fix `mpl_to_plotly` conversion of matplotlib contour lines and line collections: close contour rings ending with `Z` codes, support dash styles, convert date x-axes, separate disjoint subpaths with `None` separators, hide line collection traces from the legend by default, and group consecutive same-style lines into single traces [[#5770](https://github.com/plotly/plotly.py/pull/5770)], with thanks to @robertoffmoura for the contribution! -- Fix `mpl_to_plotly` drawing matplotlib filled contour plots (`plt.contourf`) with spurious wedges joining the disjoint regions of each band by separating the subpaths of filled path collections with `None`, including on date x-axes, with thanks to @robertoffmoura for the contribution! +- Fix `mpl_to_plotly` drawing matplotlib filled contour plots (`plt.contourf`) with spurious wedges joining the disjoint regions of each band by separating the subpaths of filled path collections with `None`, including on date x-axes [[#5851](https://github.com/plotly/plotly.py/pull/5851)], with thanks to @robertoffmoura for the contribution! ## [7.1.0] - 2026-09-15