Black Lives Matter. Please consider donating to Black Girls Code today.

Show & Tell: Plotly graph background color in html file with css style

Hi. I would like to share this code to change the background color in a Plotly graph when you export it as HTML. When you save a plotly graph as html, the background color is not covering the full page, so I added a custom function to add css style support for the html output file, check it out!

import os
import plotly
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.offline as offline

background_color = '#111111' # change this color and <body style="background-color:#111111;"> line 20

config = dict({
'scrollZoom': False,
'displayModeBar': True,
'editable': False
})

def with_css_style(fig):
    plot_div = offline.plot(fig, config=config,output_type = 'div')

    template = """
    <head>
    <body style="background-color:#111111;">
    </head>
    <body>
    {plot_div:s}
    </body>""".format(plot_div = plot_div)

    return template

def graph():

    animals=['giraffes', 'orangutans', 'monkeys']
    fig = go.Figure([go.Bar(x=animals, y=[20, 14, 23])])

    # Update layout properties
    fig.update_layout(
        hovermode="closest",
        plot_bgcolor=background_color,
        paper_bgcolor=background_color,
        font=dict(color= 'white')
    )

    #=============================================================================
    # HTML OUTPUT FILE
    #=============================================================================
    output_file = 'plotly_graph.html'
    new_fig = with_css_style(fig)
    with open(output_file, 'w') as fp:
        fp.write(new_fig)
    os.startfile(output_file)

#******************************
# MAIN PROGRAM
#******************************
if __name__ == '__main__':
    graph()