TL;DR
Use fig.write_html('chart.html', full_html=True, include_plotlyjs='cdn') to save a fully interactive Plotly figure as a standalone HTML file.
fig.write_html('plotly-figure.html', full_html=True, include_plotlyjs='cdn')
Why save Plotly figures as HTML?
A standalone HTML file keeps the interactive Plotly chart intact and portable. It can be opened in a browser, shared with colleagues, or embedded inside documentation without needing a Python environment.
Use fig.write_html()
The easiest export is fig.write_html().
import plotly.graph_objects as go
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[2, 4, 3], mode='lines+markers')])
fig.write_html('plotly-figure.html', full_html=True, include_plotlyjs='cdn')
full_html=True writes a complete HTML page. include_plotlyjs='cdn' loads Plotly.js from the CDN, keeping the file smaller.
Export a completely self-contained HTML file
If you need a single file with Plotly.js embedded, use:
fig.write_html('plotly-figure-standalone.html', full_html=True, include_plotlyjs='cdn')
If you want to embed the JS inside the same file without depending on external resources, pass include_plotlyjs=True.
fig.write_html('plotly-figure-full.html', full_html=True, include_plotlyjs=True)
Save only the chart fragment
For embedding into an existing web page, export only the chart fragment.
fig.write_html('plotly-fragment.html', full_html=False, include_plotlyjs='cdn')
This creates an HTML snippet that can be inserted into a larger document.
Use auto_open=False for scripts
When exporting from a script or notebook, disable automatic browser opening.
fig.write_html('plotly-figure.html', auto_open=False)
Add a title and metadata
You can customize the exported HTML file with standard figure metadata.
fig.update_layout(title='Visitor and Signup Trends')
fig.write_html('plotly-figure.html', full_html=True, include_plotlyjs='cdn')
Summary
- Use
fig.write_html()to save interactive Plotly charts. full_html=Truewrites a complete HTML page.include_plotlyjs='cdn'keeps the file smaller.include_plotlyjs=Trueembeds Plotly.js directly.auto_open=Falseis useful for automated exports.
