diff --git a/plotly/matplotlylib/renderer.py b/plotly/matplotlylib/renderer.py index 7c2340180cc..3817246649a 100644 --- a/plotly/matplotlylib/renderer.py +++ b/plotly/matplotlylib/renderer.py @@ -11,9 +11,16 @@ import plotly.graph_objs as go from plotly.matplotlylib.mplexporter import Renderer +from plotly.matplotlylib.mplexporter.utils import export_color from plotly.matplotlylib import mpltools +def _export_background_color(color): + """Export a matplotlib patch facecolor for use as a plotly background color.""" + bgcolor = export_color(color) + return "rgba(0,0,0,0)" if bgcolor == "none" else bgcolor + + class PlotlyRenderer(Renderer): """A renderer class inheriting from base for rendering mpl plots in plotly. @@ -79,6 +86,9 @@ def open_figure(self, fig, props): autosize=False, hovermode="closest", ) + self.plotly_fig["layout"].paper_bgcolor = _export_background_color( + fig.patch.get_facecolor() + ) self.mpl_x_bounds, self.mpl_y_bounds = mpltools.get_axes_bounds(fig) margin = go.layout.Margin( l=int(self.mpl_x_bounds[0] * self.plotly_fig["layout"]["width"]), @@ -144,6 +154,10 @@ def open_axes(self, ax, props): ] self.current_bars = [] self.axis_ct += 1 + # update plot background with the axes background from mpl + self.plotly_fig["layout"].plot_bgcolor = _export_background_color( + props["axesbg"] + ) # set defaults in axes xaxis = go.layout.XAxis( anchor="y{0}".format(self.axis_ct), zeroline=False, ticks="inside" diff --git a/plotly/matplotlylib/tests/test_renderer.py b/plotly/matplotlylib/tests/test_renderer.py index 0d63e4815b9..e52feff8781 100644 --- a/plotly/matplotlylib/tests/test_renderer.py +++ b/plotly/matplotlylib/tests/test_renderer.py @@ -84,3 +84,26 @@ def test_multiple_traces_native_legend(): assert plotly_fig.data[0].mode == "lines" assert plotly_fig.data[1].mode == "markers" assert plotly_fig.data[2].mode == "lines+markers" + + + +def test_background_colors_from_matplotlib_defaults(): + fig, ax = plt.subplots() + ax.plot([0, 1], [0, 1]) + + plotly_fig = tls.mpl_to_plotly(fig) + + assert plotly_fig.layout.plot_bgcolor == "#FFFFFF" + assert plotly_fig.layout.paper_bgcolor == "#FFFFFF" + + +def test_custom_background_colors_are_preserved(): + fig, ax = plt.subplots() + fig.patch.set_facecolor("lightyellow") + ax.set_facecolor("lightgray") + ax.plot([0, 1], [0, 1]) + + plotly_fig = tls.mpl_to_plotly(fig) + + assert plotly_fig.layout.plot_bgcolor == "#D3D3D3" + assert plotly_fig.layout.paper_bgcolor == "#FFFFE0"