Skip to content

Commit bc1e2a3

Browse files
Set plot_bgcolor and paper_bgcolor from matplotlib figure backgrounds
1 parent ec6e4c1 commit bc1e2a3

2 files changed

Lines changed: 32 additions & 6 deletions

File tree

plotly/matplotlylib/renderer.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,16 @@
1111

1212
import plotly.graph_objs as go
1313
from plotly.matplotlylib.mplexporter import Renderer
14+
from plotly.matplotlylib.mplexporter.utils import export_color
1415
from plotly.matplotlylib import mpltools
1516

1617

18+
def _export_background_color(color):
19+
"""Export a matplotlib patch facecolor for use as a plotly background color."""
20+
bgcolor = export_color(color)
21+
return "rgba(0,0,0,0)" if bgcolor == "none" else bgcolor
22+
23+
1724
class PlotlyRenderer(Renderer):
1825
"""A renderer class inheriting from base for rendering mpl plots in plotly.
1926
@@ -79,7 +86,9 @@ def open_figure(self, fig, props):
7986
autosize=False,
8087
hovermode="closest",
8188
)
82-
self.plotly_fig["layout"].template.layout.plot_bgcolor = "white"
89+
self.plotly_fig["layout"].paper_bgcolor = _export_background_color(
90+
fig.patch.get_facecolor()
91+
)
8392
self.mpl_x_bounds, self.mpl_y_bounds = mpltools.get_axes_bounds(fig)
8493
margin = go.layout.Margin(
8594
l=int(self.mpl_x_bounds[0] * self.plotly_fig["layout"]["width"]),
@@ -145,6 +154,10 @@ def open_axes(self, ax, props):
145154
]
146155
self.current_bars = []
147156
self.axis_ct += 1
157+
# update plot background with the axes background from mpl
158+
self.plotly_fig["layout"].plot_bgcolor = _export_background_color(
159+
props["axesbg"]
160+
)
148161
# set defaults in axes
149162
xaxis = go.layout.XAxis(
150163
anchor="y{0}".format(self.axis_ct), zeroline=False, ticks="inside"

plotly/matplotlylib/tests/test_renderer.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,23 @@ def test_multiple_traces_native_legend():
8787

8888

8989

90-
def test_plot_bgcolor_defaults_to_white():
91-
plt.figure()
92-
plt.plot([0, 1], [0, 1])
90+
def test_background_colors_from_matplotlib_defaults():
91+
fig, ax = plt.subplots()
92+
ax.plot([0, 1], [0, 1])
93+
94+
plotly_fig = tls.mpl_to_plotly(fig)
95+
96+
assert plotly_fig.layout.plot_bgcolor == "#FFFFFF"
97+
assert plotly_fig.layout.paper_bgcolor == "#FFFFFF"
9398

94-
plotly_fig = tls.mpl_to_plotly(plt.gcf())
9599

96-
assert plotly_fig.layout.template.layout.plot_bgcolor == "white"
100+
def test_custom_background_colors_are_preserved():
101+
fig, ax = plt.subplots()
102+
fig.patch.set_facecolor("lightyellow")
103+
ax.set_facecolor("lightgray")
104+
ax.plot([0, 1], [0, 1])
105+
106+
plotly_fig = tls.mpl_to_plotly(fig)
107+
108+
assert plotly_fig.layout.plot_bgcolor == "#D3D3D3"
109+
assert plotly_fig.layout.paper_bgcolor == "#FFFFE0"

0 commit comments

Comments
 (0)