Offline plotting and notebook helpers
Overview
The offline plotting API is exported from plotly/…/__init__.py, which re-exports the public functions implemented in plotly/…/offline.py: plot, iplot, init_notebook_mode, get_plotlyjs, get_plotlyjs_version, the matplotlib wrappers plot_mpl/iplot_mpl/enable_mpl_offline, and the deprecated download_plotlyjs stub.
plotly/…/offline.py is mostly a compatibility layer over the newer plotly.io HTML and renderer machinery. It still owns the legacy public signatures and pre-processing behavior, then delegates actual HTML generation to plotly.io._html through plotly.io.to_html or plotly.io.write_html, and notebook display to plotly.io.show.
The bundled plotly.js content and version are handled in two places:
- plotly/…/_plotlyjs_version.py defines generated
__plotlyjs_version__, returned byget_plotlyjs_version(). plotly/offline/offline.py:get_plotlyjs()reads package_data/plotly.min.js from the installedplotlypackage viapkgutil.get_data()and returns it as UTF-8 text.
plotly.io._utils.plotly_cdn_url() uses plotly.offline.get_plotlyjs_version() to construct the versioned CDN URL, and plotly.io._html.to_html() uses plotly.offline.get_plotlyjs() both for inline plotly.js and for generating the SRI hash when include_plotlyjs="cdn".
plot file and div output
plotly/offline/offline.py:plot() accepts a Plotly figure-like object or data list, validates/coerces it with plotly.tools.return_figure_from_figure_or_data(), and supports only output_type="file" or output_type="div". Invalid output_type raises ValueError. For file output, a filename that does not end in .html is warned about and has .html appended.
Before delegating, plot() copies the supplied config dict, derives width and height from figure["layout"], and sets config["responsive"] = True when either dimension is "100%" so legacy full-page outputs resize. If image is requested, build_save_image_post_script() validates it against jpeg, png, webp, and svg, then builds a Plotly.downloadImage post-script.
The output branch is:
output_type="file": callplotly.io.write_html()withfull_html=True, the caller'sfilename,auto_open,include_plotlyjs,include_mathjax,config, animation settings, validation flag, and optional image downloadpost_script; return the final filename string.output_type="div": callplotly.io.to_html()withfull_html=Falseand return the generated<div>...</div>string.
plotly.io._html.to_html() performs the actual HTML serialization: it validates/coerces the figure through plotly.io._utils.validate_coerce_fig_to_dict(), serializes data/layout/frames via plotly.io.json.to_json_plotly, generates a UUID div id unless one is supplied, normalizes config through plotly.offline.offline._get_jconfig(), sets responsive by default, and builds JavaScript that calls Plotly.newPlot. If frames are present, it appends Plotly.addFrames; if auto_play is true, it appends Plotly.animate, including animation_opts only on the auto-play path. Any post_script string or list is chained after plot creation, with {plot_id} placeholders replaced by the generated div id.
plotly.io._html.write_html() writes that HTML to a path, pathlib.Path, or file-like object. For path-like outputs it also implements the only file-system side effect for include_plotlyjs="directory": when full_html=True, it writes plotly.min.js beside the HTML file if it is not already present. It opens a browser only when the output is path-like, full_html=True, and auto_open=True.
Notebook display
plotly/offline/offline.py:init_notebook_mode() requires IPython, sets plotly.io.renderers.default to plotly_mimetype+notebook_connected when connected=True or plotly_mimetype+notebook when connected=False, then calls plotly.io.renderers._activate_pending_renderers() so notebook renderer initialization happens immediately. The concrete renderer registrations live in plotly/…/_renderers.py, where notebook and notebook_connected are NotebookRenderer instances.
plotly/offline/offline.py:iplot() is the notebook plotting entrypoint. It requires IPython, copies config, validates/coerces the figure with plotly.tools.return_figure_from_figure_or_data(), builds the same optional image-download post-script using caller mode "iplot", and calls plotly.io.show() with the figure, config, validation, auto-play, post-script, and animation options. The iplot image post-script wraps the download call in a document.readyState == 'complete' guard so reloading a notebook does not immediately re-trigger image downloads.
plotly/io/_renderers.py:show() validates the figure for renderer use, builds MIME bundles for the selected/default renderers, displays them through IPython when applicable, and then performs external rendering. The NotebookRenderer path in plotly/…/_base_renderers.py is HTML-based: it calls plotly.io._html.to_html() with full_html=False, notebook defaults, renderer config, and a cleanup MutationObserver post-script that purges the Plotly graph when notebook output is removed.
plotly.js and MathJax inclusion modes
The legacy plot() and iplot() functions pass inclusion options through to plotly.io._html.to_html(), which implements the HTML behavior:
include_plotlyjs=Trueand other truthy unrecognized values inlinewindow.PlotlyConfigfollowed by the full bundled plotly.min.js fromget_plotlyjs().include_plotlyjs=False,0, or""emits no PlotlyConfig or plotly.js script; callers must ensure plotly.js is already loaded.include_plotlyjs="cdn"emitswindow.PlotlyConfigplus a versionedhttps://cdn.plot.ly/plotly-<version>.min.jsscript tag, with integrity generated from the bundled plotly.min.js content byplotly.io._html._generate_sri_hash().include_plotlyjs="directory"emits a plotly.min.js script tag. Onlywrite_html()with full HTML and a path-like file copies the bundle to disk.- A string ending in .js emits that original string as the script
src, preserving caller casing/path while using lowercase only for mode detection.
include_mathjax is also handled in plotly.io._html.to_html(): falsey values emit nothing; "cdn" emits the MathJax 3 CDN URL plus the local STIX-Web MathJax config; strings ending in .js emit the caller's URL plus that config; any other truthy value raises ValueError.
Config validation and compatibility helpers
plotly/offline/offline.py:_get_jconfig() contains a static allowlist of known plotly.js config keys. It warns on unrecognized keys but still returns the original config dict, preserving compatibility for plotly.js config additions not yet reflected in Python. plotly.io._html.to_html() calls _get_jconfig(), then removes plotlyServerURL unless showSendToCloud is true so a Plotly URL is not emitted when the cloud button is disabled.
The matplotlib helpers in plotly/…/offline.py are thin adapters. plot_mpl() and iplot_mpl() convert a matplotlib figure through plotly.tools.mpl_to_plotly() and then call plot() or iplot(). enable_mpl_offline() calls init_notebook_mode(), obtains the active IPython HTML formatter, and registers a formatter for matplotlib.figure.Figure that returns iplot_mpl(...) output. download_plotlyjs() no longer downloads anything; it only emits a deprecation warning because plotly.js is shipped with the package.
Tests
tests/…/test_offline.py exercises the compatibility surface of plotly.offline.plot() against the HTML produced by plotly.io._html:
- default file output contains
Plotly.newPlot, serialized data/layout,window.PlotlyConfig, inline bundled plotly.js, and a full<!doctype html>...</html>document. include_plotlyjstruthy, falsey, CDN, directory, and .js path modes are checked for both file and div output. The directory file-output test verifies that plotly.min.js is copied beside temp-plot.html; the div-output test verifies no bundle is written.- div output is asserted to be only a
<div>wrapper, not a full HTML document. - config passthrough is tested for both known keys (
editable) and unknown keys (bogus), confirming warnings do not strip unknown options. - MathJax false, CDN, and custom .js path modes are tested for file and div output.
- frame handling is tested for
Plotly.addFrames,Plotly.animate, and conditional inclusion ofanimation_optsonly whenauto_play=True. - image-download support is tested by checking that
Plotly.downloadImageappears only when an image format is requested.
Coverage and routing
This doc owns:
plotly/offline/**tests/test_core/test_offline/**
Route changes here when they alter the legacy offline plotting entrypoints, notebook initialization/display behavior, plotly.js version or bundle access, HTML include modes exposed through plotly.offline.plot(), offline config handling, image-download post scripts, matplotlib offline adapters, or the offline test expectations.
Coupling
- If plotly/…/_plotlyjs_version.py changes, verify
plotly/io/_utils.py:plotly_cdn_url()and tests/…/test_offline.py expectations for CDN script tags and SRI hashes; CDN HTML uses the generated version while SRI is computed from the bundled package_data/plotly.min.js content. - If
plotly/offline/offline.py:get_plotlyjs()changes how the bundle is loaded, verify plotly/…/_html.py inline, CDN SRI, and directory-copy paths; all three callget_plotlyjs()rather than reading package data independently. - If
plotly/offline/offline.py:_get_jconfig()changes the config allowlist or warning behavior, verifyplotly/io/_html.py:to_html()and the offline config tests; unknown config keys are intentionally warned about but serialized instead of rejected. - If plotly/…/_html.py changes
include_plotlyjsorinclude_mathjaxbehavior, update tests/…/test_offline.py because the legacyplotly.offline.plot()tests assert exact script-presence behavior even though the implementation lives inplotly.io. - If
plotly/offline/offline.py:init_notebook_mode()changes renderer names, verify plotly/…/_renderers.py still registers those names; the offline notebook API hard-codesplotly_mimetype+notebookandplotly_mimetype+notebook_connected.
Risks
plotly/offline/offline.py:_get_jconfig()keeps a manual list of plotly.js config keys. Git history for this area includes config-key maintenance commits such asfa2b7dad2 delete removed config keys from offline.pyand836c34acc update config keys to match plotly.js 3.5.0; if plotly.js config options drift, users may get spurious warnings or tests may fail even though unknown keys are still serialized.- plotly/…/_plotlyjs_version.py,
plotly/io/_utils.py:plotly_cdn_url(), and plotly/…/_html.py must stay aligned with the bundled package_data/plotly.min.js. Recent history is dominated by plotly.js update commits; if the version file changes without the bundle, CDN URLs and SRI attributes can describe a different artifact than the one embedded offline.