Python Friday #196: Engine Troubles When Saving Plots With Plotly

So far, we saved our plots with the camera icon of the plot preview. If we want to automate the creation of our plots, this manual step will not be sufficient, and we need to have an alternative that we can call from our code. Unfortunately, there is a catch that you need to be aware of.

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

 

The problem

Plotly uses JavaScript to display its plots. As long as we run Plotly inside a browser (or we run our code inside JupyterLab within a browser), we do not need to care much about that fact. The browser handles everything and we can use the camera icon to save our plots.

In a code-only approach, we have no browser and need a so-called engine to simulate the needed browser capabilities. Currently we can choose between Kaleido and the older Orca engine.

 

Installing Kaleido

The recommended engine for Plotly is Kaleido. You can install it with this command:

From now on, you can use the method write_image() to save your plot in any of the supported formats :

If you run this code, you should find a Contest.svg, Contest.jpg and a Contest.png file next to your Python script.

 

Common problem with Kaleido

If you are out of luck, your method call to write_image() never finishes and your program hangs. Before you switch to Orca, you may want to try an older version of Kaleido that works for most people:

 

Installing Orca

If all efforts fail and Kaleido does not work, you can try to install Orca. Unfortunately, this is not an easy task. Orca is an Electron application that can run on the command line or as a server that accepts the plotly figures as inputs and turns them into static images.

You need to install a few Python packages and the whole NodeJS stack to get Electron working. Since I lack the knowledge of the various ways you can get NodeJS running, I strongly recommend you follow the instructions in the official documentation.

When you got everything installed, you can use Orca as the engine to save your plots:

 

Next

The problems with Kaleido and the lack of bugfixes may not be the best impression for a visualisation library. So far, the older version works, and I hope the Kaleido project gets a bit of support to fix that annoying bug.

Next week we explore a way to turn our Plotly plots into a full-featured dashboard for our website.

Leave a Comment

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