Load theme from file using plotly's theme

Looking through the docs for plotly’s theme capability, is there a way to load a (assume it would be: json) file of a custom layout theme?

I saw the capability to save locally in #1224 but for a use case where I want to share my theme so that others (or myself on a different machine) can use it for subsequent graphs, this would be a useful feature without digging through where the package saves locally to find the created theme. When working with ggplot2, I have added a separate .R to the repo with the appropriate theme to use.

Hi @apawlows,

To save a theme as a json file, you could to something like…

import json
from plotly.utils import PlotlyJSONEncoder
with open('my_theme.json', 'w') as f:
     json.dump(f, fig.layout.template, cls=PlotlyJSONEncoder)

And then to load it later

import json
import plotly.io as pio
with open('my_theme.json', 'r') as f:
    template = json.load(f)

pio.templates['my_theme'] = template

My general recommendation at this point would be to create a .py file that defines one or more templates when it is imported and registers them with plotly.io.templates. The .py file could load the template from JSON as above, or it could define the template inline.

With this approach you would share the theme by sharing the .py file (or publishing it to PyPI), and users would enable the theme by importing the module.

Does that make sense?

1 Like

Okay wow, great thank you, Jon. Yeah thank you for both giving a json example and a better recommendation. I’ll write a module with the template in it and give that a whirl.

Thanks Jon

1 Like