Search code examples
pythonplotly

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


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?


Solution

  • 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()