Skip to content

Commit da4375f

Browse files
Convert matplotlib stairs plots to plotly step lines
1 parent d3105d4 commit da4375f

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

plotly/matplotlylib/renderer.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
import warnings
1111

12+
import matplotlib.patches as mpatches
1213
import plotly.graph_objs as go
1314
from plotly.matplotlylib.mplexporter import Renderer
1415
from plotly.matplotlylib import mpltools
@@ -602,13 +603,48 @@ def draw_path(self, **props):
602603
is_bar = mpltools.is_bar(self.current_mpl_ax.containers, **props)
603604
if is_bar:
604605
self.current_bars += [props]
606+
elif isinstance(props["mplobj"], mpatches.StepPatch):
607+
self.msg += " Drawing a step path\n"
608+
self._draw_step_path(props)
605609
else:
606610
self.msg += " This path isn't a bar, not drawing\n"
607611
warnings.warn(
608612
"I found a path object that I don't think is part "
609613
"of a bar chart. Ignoring."
610614
)
611615

616+
def _draw_step_path(self, props):
617+
"""Draw a matplotlib StepPatch as a step line trace."""
618+
if props["coordinates"] != "data":
619+
self.msg += " Step path is not in data coordinates, not drawing\n"
620+
return
621+
style = props["style"]
622+
x = []
623+
y = []
624+
for x0, y0 in props["data"]:
625+
if not x or x0 != x[-1] or y0 != y[-1]:
626+
x.append(x0)
627+
y.append(y0)
628+
if len(x) < 2:
629+
self.msg += " Step path has fewer than 2 points, not drawing\n"
630+
return
631+
self.plotly_fig.add_trace(
632+
go.Scatter(
633+
x=x,
634+
y=y,
635+
mode="lines",
636+
line=go.scatter.Line(
637+
color=mpltools.merge_color_and_opacity(
638+
style["edgecolor"], style["alpha"]
639+
),
640+
width=style["edgewidth"],
641+
dash=mpltools.convert_dash(style["dasharray"]),
642+
),
643+
xaxis="x{0}".format(self.axis_ct),
644+
yaxis="y{0}".format(self.axis_ct),
645+
)
646+
)
647+
612648
def draw_text(self, **props):
613649
"""Create an annotation dict for a text obj.
614650

plotly/matplotlylib/tests/test_renderer.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,17 @@ def test_background_colors_from_matplotlib_defaults():
211211
assert plotly_fig.layout.paper_bgcolor == "#FFFFFF"
212212

213213

214+
def test_stairs_converts_to_step_line():
215+
fig, ax = plt.subplots()
216+
ax.stairs([0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0])
217+
plotly_fig = tls.mpl_to_plotly(fig)
218+
assert len(plotly_fig.data) == 1
219+
trace = plotly_fig.data[0]
220+
assert trace.mode == "lines"
221+
assert tuple(trace.x) == (0.0, 1.0, 1.0, 2.0, 2.0, 3.0)
222+
assert tuple(trace.y) == (0.0, 0.0, 1.0, 1.0, 0.0, 0.0)
223+
224+
214225
def test_custom_background_colors_are_preserved():
215226
fig, ax = plt.subplots()
216227
fig.patch.set_facecolor("lightyellow")

0 commit comments

Comments
 (0)