Skip to content

Commit 50aeed7

Browse files
Convert matplotlib step drawstyles to plotly line shapes
1 parent a5974ce commit 50aeed7

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
@@ -404,6 +404,9 @@ def draw_marked_line(self, **props):
404404
color=color,
405405
width=props["linestyle"]["linewidth"],
406406
dash=mpltools.convert_dash(props["linestyle"]["dasharray"]),
407+
shape=mpltools.convert_drawstyle(
408+
props["linestyle"]["drawstyle"]
409+
),
407410
)
408411
else:
409412
shape = dict(

‎plotly/matplotlylib/tests/test_renderer.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,3 +199,17 @@ def test_filled_path_collection_date_xaxis():
199199
filled = [t for t in plotly_fig.data if t.fill == "toself"]
200200
assert len(filled) >= 1
201201
assert all(isinstance(x, str) for x in filled[0].x)
202+
203+
204+
def test_drawstyle_maps_to_line_shape():
205+
cases = {
206+
"steps-pre": "vh",
207+
"steps": "vh",
208+
"steps-post": "hv",
209+
"steps-mid": "hvh",
210+
}
211+
for drawstyle, shape in cases.items():
212+
fig, ax = plt.subplots()
213+
ax.plot([0, 1, 2], [0, 1, 0], drawstyle=drawstyle)
214+
plotly_fig = tls.mpl_to_plotly(fig)
215+
assert plotly_fig.data[0].line.shape == shape

0 commit comments

Comments
 (0)