Skip to content

Commit 31e8add

Browse files
Convert matplotlib stairs plots to plotly step lines
1 parent c0740bf commit 31e8add

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
@@ -551,13 +552,48 @@ def draw_path(self, **props):
551552
is_bar = mpltools.is_bar(self.current_mpl_ax.containers, **props)
552553
if is_bar:
553554
self.current_bars += [props]
555+
elif isinstance(props["mplobj"], mpatches.StepPatch):
556+
self.msg += " Drawing a step path\n"
557+
self._draw_step_path(props)
554558
else:
555559
self.msg += " This path isn't a bar, not drawing\n"
556560
warnings.warn(
557561
"I found a path object that I don't think is part "
558562
"of a bar chart. Ignoring."
559563
)
560564

565+
def _draw_step_path(self, props):
566+
"""Draw a matplotlib StepPatch as a step line trace."""
567+
if props["coordinates"] != "data":
568+
self.msg += " Step path is not in data coordinates, not drawing\n"
569+
return
570+
style = props["style"]
571+
x = []
572+
y = []
573+
for x0, y0 in props["data"]:
574+
if not x or x0 != x[-1] or y0 != y[-1]:
575+
x.append(x0)
576+
y.append(y0)
577+
if len(x) < 2:
578+
self.msg += " Step path has fewer than 2 points, not drawing\n"
579+
return
580+
self.plotly_fig.add_trace(
581+
go.Scatter(
582+
x=x,
583+
y=y,
584+
mode="lines",
585+
line=go.scatter.Line(
586+
color=mpltools.merge_color_and_opacity(
587+
style["edgecolor"], style["alpha"]
588+
),
589+
width=style["edgewidth"],
590+
dash=mpltools.convert_dash(style["dasharray"]),
591+
),
592+
xaxis="x{0}".format(self.axis_ct),
593+
yaxis="y{0}".format(self.axis_ct),
594+
)
595+
)
596+
561597
def draw_text(self, **props):
562598
"""Create an annotation dict for a text obj.
563599

plotly/matplotlylib/tests/test_renderer.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,14 @@ 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_stairs_converts_to_step_line():
90+
fig, ax = plt.subplots()
91+
ax.stairs([0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0])
92+
plotly_fig = tls.mpl_to_plotly(fig)
93+
assert len(plotly_fig.data) == 1
94+
trace = plotly_fig.data[0]
95+
assert trace.mode == "lines"
96+
assert tuple(trace.x) == (0.0, 1.0, 1.0, 2.0, 2.0, 3.0)
97+
assert tuple(trace.y) == (0.0, 0.0, 1.0, 1.0, 0.0, 0.0)

0 commit comments

Comments
 (0)