Skip to content

Commit f01fba3

Browse files
Convert matplotlib step drawstyles to plotly line shapes
1 parent c0740bf commit f01fba3

3 files changed

Lines changed: 34 additions & 0 deletions

File tree

plotly/matplotlylib/mpltools.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,23 @@ def get_bar_gap(bar_starts, bar_ends, tol=1e-10):
272272
return gap0
273273

274274

275+
DRAWSTYLE_SHAPE_MAP = {
276+
"steps": "vh",
277+
"steps-pre": "vh",
278+
"steps-post": "hv",
279+
"steps-mid": "hvh",
280+
}
281+
282+
283+
def convert_drawstyle(drawstyle):
284+
"""Convert a matplotlib line drawstyle to a plotly line shape.
285+
286+
Matplotlib draws steps as vertical/horizontal segments; plotly's
287+
``line.shape`` expresses the same via "vh", "hv" and "hvh".
288+
"""
289+
return DRAWSTYLE_SHAPE_MAP.get(drawstyle)
290+
291+
275292
def convert_rgba_array(color_list):
276293
clean_color_list = list()
277294
for c in color_list:

plotly/matplotlylib/renderer.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,9 @@ def draw_marked_line(self, **props):
388388
color=color,
389389
width=props["linestyle"]["linewidth"],
390390
dash=mpltools.convert_dash(props["linestyle"]["dasharray"]),
391+
shape=mpltools.convert_drawstyle(
392+
props["linestyle"]["drawstyle"]
393+
),
391394
)
392395
else:
393396
shape = dict(

plotly/matplotlylib/tests/test_renderer.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,17 @@ def test_multiple_traces_native_legend():
8484
assert plotly_fig.data[0].mode == "lines"
8585
assert plotly_fig.data[1].mode == "markers"
8686
assert plotly_fig.data[2].mode == "lines+markers"
87+
88+
89+
def test_drawstyle_maps_to_line_shape():
90+
cases = {
91+
"steps-pre": "vh",
92+
"steps": "vh",
93+
"steps-post": "hv",
94+
"steps-mid": "hvh",
95+
}
96+
for drawstyle, shape in cases.items():
97+
fig, ax = plt.subplots()
98+
ax.plot([0, 1, 2], [0, 1, 0], drawstyle=drawstyle)
99+
plotly_fig = tls.mpl_to_plotly(fig)
100+
assert plotly_fig.data[0].line.shape == shape

0 commit comments

Comments
 (0)