Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 31 ยท Production and Performance

Exporting, Embedding and Sharing Charts

Save interactive charts as HTML, export PNG, SVG and PDF, embed in Jupyter, Streamlit and websites, and handle CSP and offline use safely.

A chart that lives only in your notebook helps one person. To be useful it has to travel: into a report as an image, onto a web page as an interactive figure, into a dashboard framework, or into an email attachment that opens on a laptop with no internet. Each destination has its own format, and each has traps: huge files, blank images, scripts blocked by the host page, or user data injected into HTML unsafely.

This lesson maps the destinations and how the three libraries reach them. The export and embed calls need Python and a browser (or a headless browser) and cannot run on this site, so they are read-only. The runnable examples are stand-ins in JavaScript that demonstrate the two mechanics behind embedding that you can study without any library: how a chart spec is placed safely inside a page, and how a Content Security Policy decides whether that page runs. For the specs themselves, see Plotly Figures: Data, Layout and Traces and Reading and Writing Vega-Lite JSON.

Choose the format by the destination

Destination Format Interactive?
A web page or shared file HTML Yes
A slide, Word document or PDF report PNG, SVG or PDF No
Email or chat PNG, or an HTML file as attachment No / Yes
A notebook Inline output Yes
A Streamlit or Dash app The library's own component Yes
flowchart TD
    A["Figure or chart object"] --> B["Spec as JSON"]
    B --> C["HTML page<br/>JS library draws it"]
    B --> D["Headless browser<br/>renders it"]
    D --> E["PNG, SVG, PDF"]
    C --> F["Notebook, Streamlit,<br/>your website"]

Every path starts from the same JSON spec. HTML ships the spec to a browser; image export runs a browser for you.

Interactive HTML

The simplest way to share an interactive chart is one HTML file that anyone can open.

Python
# Plotly
fig.write_html("sales.html")                           # self-contained file
fig.write_html("sales.html", include_plotlyjs="cdn")   # smaller, needs internet
html_snippet = fig.to_html(full_html=False)            # just a <div> + script

# Bokeh
from bokeh.plotting import output_file, save
output_file("sales.html")
save(p)

# Altair
chart.save("sales.html")                  # loads Vega libraries from a CDN
chart.save("sales.html", inline=True)     # embeds them, works offline

Read-only. Each call writes a file whose JavaScript draws the chart in the viewer's browser.

The key choice is where the charting JavaScript comes from. Inline puts the whole library in your file: it works offline but weighs several megabytes per chart, so ten reports mean ten copies. A CDN link keeps the file tiny but needs internet access and trusts a third party. A middle road is a shared directory: write the library once next to your pages and point every page at it (Plotly offers include_plotlyjs="directory"). Pin an exact library version in any CDN URL; an unpinned URL can change under you and break old reports.

Static images

Images work everywhere, including places that cannot run scripts: PDFs, slides, README files, emails.

Python
# Plotly (needs the kaleido package)
fig.write_image("sales.png", width=900, height=500, scale=2)
fig.write_image("sales.svg")
fig.write_image("sales.pdf")

# Altair (needs vl-convert-python)
chart.save("sales.png", scale_factor=2)
chart.save("sales.svg")

# Bokeh (needs a browser driver)
from bokeh.io import export_png, export_svg
export_png(p, filename="sales.png")

Read-only. Static export launches a headless browser in the background, so it needs extra packages, and some versions need a Chrome or Chromium installation on the machine.

Pick the format by what happens next:

  • PNG for slides and documents. Use scale=2 (or higher) for sharp text on high-resolution screens.
  • SVG when the image will be edited or must stay sharp at any size. Fonts can differ on the reader's computer, so check the result.
  • PDF for print and reports; vector graphics, with the same font caveat.

If image export fails, the cause is almost always the missing renderer or browser, not your chart. Read the error, install the package it names, and try a tiny figure first.

Notebooks and apps

In Jupyter, Plotly shows figures inline with fig.show(), Bokeh needs output_notebook() once at the top, and Altair displays the chart object when it is the last expression of a cell. Interactive output lives in the notebook file as HTML and JavaScript, which many viewers (GitHub's preview, some PDF converters) strip. If your notebook will be viewed there, switch to a static renderer for those outputs, for example Plotly's png renderer, so readers see a picture.

In Streamlit, pass the figure to the matching component: st.plotly_chart(fig, use_container_width=True) or st.altair_chart(chart). Bokeh support is tied to specific Bokeh versions, so check the compatibility notes of the version you use. In Dash, a figure goes into a dcc.Graph (see Dashboards with Dash and Callbacks).

On your own website, you have three options, from easiest to most flexible:

  1. An <iframe> pointing to the exported HTML file. Add sandbox="allow-scripts" so the chart page cannot reach into the host page.
  2. The HTML snippet from to_html(full_html=False), pasted into your template. Load the library once per page, not once per chart.
  3. The spec as JSON plus the JavaScript library: Plotly.js newPlot, Bokeh's embed.json_item, or vega-embed for Vega-Lite specs. This is best for a real application, because the server returns data and the page draws it.

Putting a spec into a page safely

Option 3 means your server writes JSON into a <script> element. Here lies a real security trap. HTML ends a script at the first closing script tag it sees, even inside a JavaScript string. If any value in your spec comes from users (a series name, a title, a label from a database), a value containing a closing script tag followed by markup can break out of the script and inject arbitrary HTML and code into your page. That is cross-site scripting.

Plotly's to_html, Bokeh's components and Altair's save already handle this for you. When you build the page yourself, escape the angle bracket in the JSON as the unicode escape for it (a backslash, then u003c). It is still valid JSON and JavaScript, and it cannot close a tag. The stand-in shows the problem and the fix.

JS Embedding a spec in a page without breaking out

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

No output.

The naive embed has two closing script tags where the page expects one, so the series name would escape the script. The safe version has one, and the browser reads the escaped text back as the same data: the round trip is identical. The last lines show the CDN-versus-inline trade-off. The inline page here carries a 3.5-million-character placeholder for the library, a stand-in of the same order of size as a full charting bundle (check the real size of the version you use).

Content Security Policy and offline use

Many sites send a Content Security Policy (CSP) header that lists which scripts the browser may run. It protects against injected code, and it can also block your chart: if the CDN is not allowed, or if the page has inline scripts without permission, the chart area stays blank and the console shows a CSP violation.

The rules your embedded chart touches are simple:

  • Scripts from another origin run only if that origin is listed in script-src.
  • Inline scripts (including the one that calls newPlot) run only with 'unsafe-inline' or with a nonce: a random value your server sends in the header and in the script's nonce attribute. A nonce is the safer choice.
  • Charting libraries do extra work in the browser: Plotly.js ships a bundle meant for stricter policies, and Vega's expression evaluator generates functions at runtime, which strict policies block unless you use its interpreter-based alternative. These details change between versions, so test with your actual policy and the browser's developer console.

The stand-in applies the three rules above to a page with two CDN scripts, one local script and one inline script, and three sample policies.

JS Which policy lets the page run?

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

No output.

Even the permissive policies block the analytics script, which was never allowed. That is the policy working as designed, and a reminder that every extra script on a page needs a reason. A real CSP has more directives than script-src (style-src, connect-src for data fetches, img-src for exported images), and real browsers apply stricter parsing than this stand-in.

Offline use follows from the same logic. For a chart that must open with no network (a conference laptop, a secure environment), inline the library (include_plotlyjs=True, inline=True in Altair, Bokeh's INLINE resources), have no web fonts or remote images, and test by disconnecting. For a shared directory, ship the library file beside the HTML.

What is real and what is the stand-in

  • Real, read-only: write_html, write_image, export_png, chart.save, Streamlit and Dash components. They need Python, and image export needs a headless browser.
  • Stand-in: the JavaScript programs. The escaping rule and the CSP matching are real mechanisms, simplified: browsers implement far more of CSP, and the library file here is a placeholder, not the real bundle.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You need a chart in a PDF report. Which export fits?

    PDFs cannot run scripts. Use a static image export; PNG with scale=2 for sharp raster output or SVG/PDF for vector.
  2. 2. Why does a chart HTML file with the library loaded from a CDN stay small?

    The CDN link replaces several megabytes of inline JavaScript. The trade-off is that the viewer must be online and you trust the CDN; pin a version.
  3. 3. Why is it dangerous to put raw JSON into a script element when a series name comes from user input?

    HTML ends the script at the first closing tag, even inside a string. Escape the angle bracket in the JSON or use the library's own embed helper.
  4. 4. A page with an inline chart script is blocked by the site's CSP. What is the safer fix?

    A nonce allows only the scripts you mark, while 'unsafe-inline' allows any injected inline code too.

Summary

  • Pick the format by destination: HTML for interactive sharing, PNG/SVG/PDF for documents, library components for notebooks and apps.
  • HTML files either inline the library (offline, large), link a pinned CDN version (small, needs internet), or share a library file in a directory.
  • Static export needs extra packages (kaleido, vl-convert, a browser driver) and sometimes a Chrome installation; use scale for sharp PNGs.
  • Escape user-controlled values when you write a spec into a script element yourself, or use the library's embed helper.
  • A CSP can block CDNs and inline scripts: allow origins explicitly and prefer nonces to 'unsafe-inline'.
  • The export calls are read-only here; the JavaScript stand-ins show the escaping and policy logic.

Next: Testing Charts and Common Pitfalls.