Showing and exporting figures

Plotly · Essentials · 10 min

A chart is only useful once it reaches its audience, whether in a notebook, a shared HTML file or a slide.

fig.show() displays a figure using a renderer chosen for your environment: inline in Jupyter, VS Code and Colab, or a new browser tab when run as a script. plotly.io.renderers.default reports or sets it ("browser", "notebook", "vscode", "png" ...).

Interactive HTML keeps all interactivity and needs no server:

fig.write_html("chart.html", include_plotlyjs="cdn")

include_plotlyjs=True (the default) embeds the whole plotly.js library, about 4-5 MB, so the file works offline; "cdn" loads it from the internet, making files tiny. full_html=False produces a <div> snippet to embed in an existing page. fig.to_html() returns the string instead of writing a file.

Static images come from Kaleido, a separate package (pip install kaleido), version 1 or later in Plotly 7. Kaleido 1 drives a headless Chrome, so a Chrome or Chromium installation is needed; plotly_get_chrome (installed with Plotly) downloads a compatible one.

fig.write_image("chart.png", scale=2)   # also .svg, .pdf, .jpg, .webp

width, height and scale control the output size; scale=2 doubles resolution for crisp slides.

The config argument controls the in-browser toolbar: fig.show(config={"displayModeBar": False}) hides it, and {"toImageButtonOptions": {"format": "svg"}} changes what the camera button downloads.

Example

import plotly.express as px
import plotly.io as pio
import os

fig = px.bar(x=["a", "b", "c"], y=[4, 2, 5], title="Exports")

fig.write_html("embedded.html")                         # self-contained
fig.write_html("cdn.html", include_plotlyjs="cdn")      # needs internet
print(os.path.getsize("embedded.html") > 1_000_000)     # True: includes plotly.js
print(os.path.getsize("cdn.html") < 20_000)             # True

snippet = fig.to_html(full_html=False, include_plotlyjs=False)
print(snippet.lstrip().startswith("<div"))              # True: embeddable fragment

print(list(pio.renderers)[:3])          # e.g. ['plotly_mimetype', 'jupyterlab', 'nteract']
# fig.write_image("chart.png", scale=2) # needs kaleido>=1 and Chrome
# fig.show(config={"displayModeBar": False})

Remember

  • fig.show() uses an environment-specific renderer
  • write_html keeps interactivity; include_plotlyjs='cdn' keeps files small
  • write_image needs Kaleido 1+ and a Chrome install for PNG, SVG and PDF

Watch out for

  • Emailing an HTML file written with include_plotlyjs='cdn' to someone offline, who then sees a blank page.

Check yourself

  1. You need a single HTML file that works on an air-gapped laptop. Which option is right?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: plotly.com/python/interactive-html-export/

Showing and exporting figures · Plotly · Topolearn