Python Friday #194: Templates for Plotly

While colours are one of the most notable things we can change in Plotly, there are many more knobs we can turn to influence the visual aspects of our plots. In this post we explore how templates for Plotly work and what we need to create our own.

This post is part of my journey to learn Python. You find the code for this post in my PythonFriday repository on GitHub.

 

List the existing templates

Plotly organises the templates in the plotly.io module, that we can import as pio and ask for a list of known templates:

You can find an example of each template in the official documentation.

 

Our plot with the default template

If we do not specify a template, Plotly uses the default template “plotly“:

The scatter plot as we know it.

 

Use a specific template

We can set a template for our plot with the template parameter:

This uses the presentation template with a larger font size to be visible from a greater distance:

Our plot has now a larger font size and uses more distinct colours.

 

Inspect a template

If we want to know the different settings in a template, we can fetch the template and check the contents of the layout property:

This gives us a dictionary with everything set in the seaborn template:

 

Change the default template

If we want to change the default template, we can overwrite the setting in the plotly.io module:

 

Create a custom template

We can create our own template by passing a dictionary with our template definition to the constructor of the Graph Objects Template class:

This template adds the text “Work in Progress” over our plot to mark the ones we are still developing:

Our box plot now has Work in Progress written all over it.

 

Combine templates

We can combine multiple templates and merge their settings but be aware that it may not make sense with all templates. To combine the seaborn template with our work in progress text, we can combine them with a + sign:

This uses the seaborn template and adds the “Work in Progress” text on top:

The box plots use the colours of the seaborn template, while our grey text Work in Progress is on top of the plot.

 

Next

With the templates we can style our plots in one go. The built-in templates cover a wide range of visualisations and are a good starting point for your own template, should you need something else.

Next week we explore a few additional ways Plotly offers us to customise our plots.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.