Index ¦ Archives ¦ Atom main theme in Plotly.js

If you're like me who is used to using (i.e. Plotly Python) and then suddenly decided to use Plotly.js directly, you might immediately realize that there are some significant differences in terms of the plot design.

Plotly Python Plot

For one, your default plot in Plotly.js has a white background and not the steel blue colour as you would expect from a default plot. The reason is that the plots produced in the python version of Plotly come prepackaged with nice out-of-the-box themes. For example, the plot image above is a scatter plot with the default plotly template. So how do we reproduce these themes inside of Plotly.js?

Diving deeper into the Plotly documentation, I discovered that you can actually get the "theme settings" for the templates with just 4 lines of Python code.

import as pio
template = "plotly"
plotly_template = pio.templates[template]

The Python code above prints the "theme settings" of the plot or in proper Plotly lingo, the plot layout settings. In our particular case above where we set template = "plotly", we get the default plotly theme layout settings:

    'annotationdefaults': {'arrowcolor': '#2a3f5f', 'arrowhead': 0, 'arrowwidth': 1},
    'autotypenumbers': 'strict',
    'coloraxis': {'colorbar': {'outlinewidth': 0, 'ticks': ''}},

As you can see, it is in serialized JSON format. The idea now then is to deserialize this layout settings into a JavaScript object literal and pass it into the layout of your plot in Plotly.js. I did the deserialize process manually because I cannot find a way to automate this process (I would love to hear if you are able to do it!). For the default plotly theme, the JavaScript object literal is given below:

Note: Stating the obvious but since the layout setting is extracted from the Plotly documentation, it is the hard work of the people behind Plotly. Thank you for the awesome theme!

The final step is to pass this layout into the layout parameter of the Plotly plot, and you get your favorite default theme again but now directly in Plotly.js!

© Salman Faris. Built using Pelican. Theme by Giulio Fidente on github.