Exporting#

plotly figures are interactive when viewed in a web browser. But since version 4.0, plotly is offline only, which means all figures are rendered in the local environment. Even if figures are displayed in a web browser window, the figure does not exist online–the web browser is loading a figure from the local environment.

Static Image Export#

We can export plotly figures as static image file formats (.png, .jpeg, .svg, and .pdf).

Static image generation requires the Kaleido package.

To install Kaleido:

  • using pip: pip install kaleido

  • using conda: conda install conda-forge python-kaleido

# install kaleido
!pip install -U kaleido
Requirement already satisfied: kaleido in /usr/local/lib/python3.10/dist-packages (0.2.1)

You may need to restart your runtime or kernel after the install.

Once a figure has been created, we can use the .write_image() method in combination with plotly to write the figure to an image file.

import plotly.express as px
df = px.data.gapminder() # subset data
fig = px.line(df, x="year", y="lifeExp", color='continent', line_group='country', hover_name='country', title='Country Life Expectancy by Continent') # create figure
fig.write_image('output.png')
fig # show output

Other file types Plotly export supports:

  • png

  • jpeg

  • svg

  • pdf

Additional Resources#

For more on static image export: plotly, Static Image Export in Python

Saving to HTML#

We can also export plotly figures as HTML files which can be loaded in a web browser. Unlike static image exports, these HTML files will include the interactivity of the plotly figure. Once a figure has been created, we can use the .write_html() method to save the figure as an HTML file.

fig.write_html("output.html") # write to html

Additional Resources#

For more on HTML file export: plotly, Interactive HTML Export in Python