Skip to content

Latest commit

 

History

History
140 lines (107 loc) · 6.59 KB

File metadata and controls

140 lines (107 loc) · 6.59 KB
jupyter
jupytext kernelspec language_info plotly
notebook_metadata_filter text_representation
all
extension format_name format_version jupytext_version
.md
markdown
1.3
1.14.6
display_name language name
Python 3 (ipykernel)
python
python3
codemirror_mode file_extension mimetype name nbconvert_exporter pygments_lexer version
name version
ipython
3
.py
text/x-python
python
python
ipython3
3.10.11
description display_as language layout name order page_type permalink thumbnail
Plotly allows you to save interactive HTML versions of your figures to your local disk.
file_settings
python
base
Interactive HTML Export
31
u-guide
python/interactive-html-export/
thumbnail/static-image-export.png

Interactive vs Static Export

Plotly figures are interactive when viewed in a web browser: you can hover over data points, pan and zoom axes, and show and hide traces by clicking or double-clicking on the legend. You can export figures either to static image file formats like PNG, JPEG, SVG or PDF or you can export them to HTML files which can be opened in a browser. This page explains how to do the latter.

Saving to an HTML file

Any figure can be saved as an HTML file using the write_html method. These HTML files can be opened in any web browser to access the fully interactive figure.

import plotly.express as px

fig = px.scatter(x=range(10), y=range(10))
fig.write_html("path/to/file.html")

Controlling the size of the HTML file

By default, the resulting HTML file is a fully self-contained HTML file which can be uploaded to a web server or shared via email or other file-sharing mechanisms. The downside to this approach is that the file is very large (5Mb+) because it contains an inlined copy of the Plotly.js library required to make the figure interactive. This can be controlled via the include_plotlyjs argument (see below).

Inserting Plotly Output into HTML using a Jinja2 Template

You can insert Plotly output and text related to your data into HTML templates using Jinja2. Use .to_html to send the HTML to a Python string variable rather than using write_html to send the HTML to a disk file. Use the full_html=False option to output just the code necessary to add a figure to a template. We do not want to output a full HTML page, as the Jinja template will define the rest of the page's structure — for example, the page's HTML and BODY tags. First create an HTML template file containing a Jinja variable, {{ fig }}. We use Python to generate HTML that is the template file with the Jinja variable {{ fig }} replaced with our graphic fig. The Python shows the steps to specify the height of the graphic as a percentage of the height of the browser window and provides a much simpler option if you are comfortable with a fixed height figure.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />   <!--It is necessary to use the UTF-8 encoding with plotly graphics to get e.g. negative signs to render correctly -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>
<h1>Here's a Plotly graph!</h1>
{{ fig }}
<p>And here's some text after the graph.</p>
</body>
</html>

Then use the following Python to replace {{ fig }} in the template with HTML that will display the Plotly figure "fig":

import plotly.express as px
from jinja2 import Template

data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')

output_html_path=r"/path/to/output.html"
input_template_path = r"/path/to/template.html"

# code block to set the vertical height as a percentage of the window height
# if you are comfortable with a fixed height graph, substitute
#     plotly_jinja_data = {"fig":fig.to_html(full_html=False)}
# for all the code up to the end of the responsive Plotly figure HTML Jinja dictionary population block

# we defer to the HTML and window size for the height by setting autosize to True,  height to None and responsive to True
fig.update_layout(autosize=True, height=None, )
fig_html = fig.to_html(full_html=False, config=dict(responsive=True))
#consider also defining the include_plotlyjs parameter to point to an external Plotly.js as described above

vertical_height_as_pct_window = 80
fig_html_with_vertical_height = f'<div style="height: {vertical_height_as_pct_window}vh;">'+fig_html.replace("<div>","", 1)
plotly_jinja_data = {"fig":fig_html_with_vertical_height}
# end of responsive Plotly figure HTML Jinja dictionary population block

#consider also defining the include_plotlyjs parameter to point to an external Plotly.js as described above

with open(output_html_path, "w", encoding="utf-8") as output_file:
    with open(input_template_path) as template_file:
        j2_template = Template(template_file.read())
        output_file.write(j2_template.render(plotly_jinja_data))

HTML export in Dash

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python app.py.

Get started with the official Dash docs and learn how to effortlessly style & publish apps like this with Dash Enterprise or Plotly Cloud.

from IPython.display import IFrame
snippet_url = 'https://python-docs-dash-snippets.herokuapp.com/python-docs-dash-snippets/'
IFrame(snippet_url + 'interactive-html-export', width='100%', height=1200)

Sign up for Dash Club → Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture. Join now.

Full Parameter Documentation

import plotly.graph_objects as go

help(go.Figure.write_html)