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

Setting global styles for plotly charts

Hi there

I’m building a dashboard using Dash, and I’d like to be able to set global styles for the dcc.Graph components - particularly setting the font family, color, size etc. What’s the easiest way to set this for all components?

I’ve tried to add a font={'family': 'New Font'} attribute at various places when the dcc.Graph component is being used, but none of them seem to change the font family for the charts.

Thanks

The beautiful thing about dash components are that they are essentially dictionary objects which means that they can be copied with minor tweaks to the key: value pairs. Borrowing from this recipe, here is how I’d create a global font for my figures.

Note that using deepcopy is subtle, but necessary. Since layouts are nested dictionaries, we want to make sure that we recursively copy the entire element.

from copy import deepcopy

GLOBAL_LAYOUT = dict(
    titlefont=dict(
        family = 'Balto',
        size = 25,
        color = '#6f199c'
    )
)

figure_1 = {
    'data': [{
      'x': [1, 2, 3, 4],
      'y': [12, 9, 15, 12],
      'mode': 'lines+markers',
      'type': 'bar'
    }],
    'layout': deepcopy(GLOBAL_LAYOUT)
}

figure_2 = {
    'data': [{
      'x': [1, 2, 3, 4],
      'y': [12, 9, 15, 12],
      'mode': 'lines+markers',
      'type': 'scatter'
    }],
    'layout': deepcopy(GLOBAL_LAYOUT)
}


# Use following recipe to overwrite/create any new layout properties
figure_1['layout']['title'] = 'Bar chart'
figure_2['layout']['title'] = 'Scatter'

app = dash.Dash(__name__)
app.layout = html.Div([
    dcc.Graph(
        id='graph-1',
        figure=figure_1
    ),
    dcc.Graph(
        id='graph-2',
        figure=figure_2
    )
])

Hope that helps!

I would like to point out that in some patterns you may want to just apply changes to the layout, therefore this dict-like behavior is extremly useful. You can use maps to filter keys and props you want to inherit from predefined layouts, etc.

For example, the given example with applying only font face and color, and maintaining individual size per figure:

GLOBAL_FONT= dict(
        family = 'Balto',
        color = '#6f199c'
)

figure_1 = {
    'data': [{
      'x': [1, 2, 3, 4],
      'y': [12, 9, 15, 12],
      'mode': 'lines+markers',
      'type': 'bar'
    }],
    'layout': {'titlefont':{'size':25}}
}

figure_2 = {
    'data': [{
      'x': [1, 2, 3, 4],
      'y': [12, 9, 15, 12],
      'mode': 'lines+markers',
      'type': 'scatter'
    }],
    'layout': {'titlefont':{'size':16}}
}
figure_1['layout']['titlefont'].update(**GLOBAL_FONT)
figure_2['layout']['titlefont'].update(**GLOBAL_FONT)

Thanks so much @mrmr and @mbkupfer - very speedy and helpful answers, exactly what I was looking for.