Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions plotly/matplotlylib/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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"]),
Expand Down Expand Up @@ -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"
Expand Down
23 changes: 23 additions & 0 deletions plotly/matplotlylib/tests/test_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"