How to update the global font color for all Plotly charts?

Viewed 1263

I have a notebook with around ~20 different plots. Currently, I'm manually changing the color with this command in each plot function:

fig.update_layout(font = dict(color = '#051c2c')) 
return fig

This seems a bit redundant, is there a way to define a global color or font option for all of Plotly?

2 Answers

If you were to use Plotly Dash or JupyterDash, this could be done through stylesheets. To my knowledge, your only option seems to be to edit your figure objects directly through locals(). Just make sure that all your figures follow some sort of system when it comes to naming, like fig1, fig2 etc:

for l in list(locals().keys()):
    if l[:3] == 'fig':
        locals()[l].update_layout(font_family = 'Old Standard TT', font_size = 24)

Here are four figures to show that this little snippet will in fact edit the fonts for a collection of figures fig1 and fig2 following the locic above.

Plot:

enter image description here

Complete code:

import pandas as pd
import plotly.express as px

# data
df = pd.DataFrame({'a': {0: 1000, 1: 996, 2: 996},
                   'b': {0: 1000, 1: 1007, 2: 998},
                   'c': {0: 1000, 1: 1009, 2: 999}})

# figure setup and display
fig1 = px.scatter(df, x = 'a', y='c', title = 'Figure 1')
fig2  = px.bar(df, x = 'a', y='c', title = 'Figure 2')
fig2.update_layout(font=dict(family = 'Courier New'))
fig1.show()
fig2.show()

# some brute force editing
keys = list(locals().keys())
for l in keys:
    if l[:3] == 'fig':
        locals()[l].update_layout(font_color = 'firebrick', font_size = 16)

# display after editing
fig1.show()
fig2.show()

One option is to create your own theme. This can be combined with other themes, meaning you can override the bits of the config you care about and let Plotly handle the rest. The chained themes are handled like CSS, so later themes override earlier themes.

import plotly.io as pio
import plotly.graph_objects as go

# Register your theme as a named template
pio.templates['my_theme'] = go.layout.Template(
    layout=dict(
        font=dict(
            color='#051c2c',
        ),
    ),
)

# Combine your theme with plotly's default
pio.templates.default = 'plotly+my_theme'

For more information, check out Plotly's docs on the matter https://plotly.com/python/templates/#creating-themes

Related