Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 42 ยท Dash and Deployment

Exporting and Embedding Figures

Save Plotly figures as standalone HTML, JSON, PNG, SVG or PDF with write_html and write_image, embed them in web pages, control config options and share them safely.

A figure that lives only in a notebook helps nobody else. Sooner or later you must put it in a report, a blog post, an email, a slide deck or a web page. Plotly offers several ways out, from a single self-contained HTML file to static images, and the right choice depends on one question: does the reader need interactivity?

Goal Best format Call
Share an interactive chart as a file Standalone HTML fig.write_html("chart.html")
Put a chart into an existing web page HTML fragment or JSON + Plotly.js fig.to_html(full_html=False) / fig.to_json()
Store a figure or send it to an API JSON fig.write_json("fig.json")
Paper, slides, PDF report PNG / SVG / PDF fig.write_image("fig.png") (needs Kaleido)
Interactive chart in a live app Dash dcc.Graph see your first Dash app

The figure is just JSON

A Plotly figure is a plain data structure: a list of traces, a layout dictionary and optionally frames. Python objects such as go.Figure only help you build and validate it. That is why the same figure works in Python, R, Julia, JavaScript and Dash, and why exporting is simple.

Python Figure to JSON and back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how large the JSON is: the default theme ("template") is copied into every figure. For a small chart, the template is bigger than the data. In a production app you can shrink it with pio.templates.default = "none" or by selecting a lighter template. See also fig.to_plotly_json() (a Python dict) and fig.to_dict().

Standalone HTML: write_html and to_html

fig.write_html("chart.html") creates a page that contains the figure and the Plotly.js library (about 4.5 MB), so it works offline and can be emailed. The include_plotlyjs option changes this:

Value Result
True (default) Library embedded in the file: large but fully offline
"cdn" A <script> tag pointing to the CDN: tiny file, needs internet
"directory" Writes plotly.min.js next to the file: good for many pages in one folder
False No library. You must load Plotly.js yourself

full_html=False returns only a <div> and a <script>, which you can paste into an existing page or a template. Add include_plotlyjs="cdn" to avoid loading the library twice. Other useful arguments: config={"displayModeBar": False}, div_id="sales" (a predictable id for your own scripts), default_height="400px" and auto_play=False for animations.

Python Inspect the HTML that to_html produces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line shows why include_plotlyjs=True creates big files: the entire Plotly.js bundle is inside.

Embedding with Plotly.js and JSON

Often your site is not Python at all. A common pattern is to compute the figure in Python (or on a server), save fig.to_json(), and let the page draw it with Plotly.js. The figure data is the only thing that crosses the boundary.

Draw a figure from JSON in the browser

Treat the JSON as data, not as code: never build it by pasting untrusted strings into a <script> tag. Use JSON.parse on a fetch response or a <script type="application/json"> block, which cannot execute.

An interactive chart in a page you do not control (a CMS, an email, a PDF) is often blocked, because those places strip scripts. Use a static image there, with a link to the interactive version.

Static images with Kaleido

fig.write_image("chart.png", width=1000, height=600, scale=2) renders a static file. The supported formats are PNG, JPEG, WebP, SVG and PDF. Image export uses the Kaleido engine, installed with pip install kaleido; recent versions of Kaleido need a Chrome or Chromium installation on the machine, which the plotly_get_chrome command can fetch. Because image export needs a real browser engine, it cannot run on this site's in-browser Python, so the code below is read-only.

Python
fig.write_image("sales.png", width=1200, height=700, scale=2)   # sharp for slides
fig.write_image("sales.svg")                                     # vector, scales forever
fig.write_image("sales.pdf")                                     # for print and papers
png_bytes = fig.to_image(format="png")                           # bytes in memory

Tips for good static images: set width and height explicitly so text sizes are predictable, raise scale to 2 or 3 for retina and slides, use SVG or PDF for print, and switch to a white template for paper.

A user can also save the current view from the browser with the camera icon in the mode bar. Configure its output with config={"toImageButtonOptions": {"format": "svg", "filename": "my_chart", "scale": 2}}.

The config dictionary

config is the second options dictionary (after the figure itself) controlling the chart's behavior, not its content. You can pass it to fig.show(config=...), write_html, to_html and dcc.Graph(config=...).

Option Effect
displayModeBar True, False or "hover"
modeBarButtonsToRemove e.g. ["lasso2d", "select2d"]
scrollZoom Zoom with the mouse wheel
responsive Resize with the window
staticPlot No interaction at all (a plain image)
displaylogo Hide the Plotly logo with False
locale Translate the interface (needs the locale bundle)

Notebooks and renderers

fig.show() picks a renderer depending on where you run: "browser" opens a tab, "notebook"/"jupyterlab"/"vscode" display inline, "png" embeds a static image, "json" prints JSON. Choose one with pio.renderers.default = "browser" or the environment variable PLOTLY_RENDERER. A plain Python script has no display, so fig.show() opens your browser, and write_html is the reliable alternative.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call creates an HTML file that works offline?

    By default the Plotly.js library is embedded in the file. With "cdn" the page needs internet to load the library.
  2. 2. What does full_html=False return?

    It skips the surrounding html, head and body tags so the snippet can live inside your own template.
  3. 3. Why does write_image not run in this site's browser Python?

    Kaleido renders the figure with Chromium, which is not available inside a browser tab's Python runtime.
  4. 4. You paste a figure into an email. What is the safest format?

    Email clients strip scripts, so a static image is the dependable choice.

Summary

  • A Plotly figure is JSON: to_json, from_json, to_dict convert it.
  • write_html and to_html give interactive output; control size with include_plotlyjs and full_html.
  • write_image makes PNG, SVG, JPEG, WebP or PDF through Kaleido.
  • config controls the mode bar, zoom, responsiveness and the download button.
  • Pick a renderer for notebooks and use static images where scripts are blocked.

Next: Deploying Plotly and Dash Apps