As an open-source graphing library for Python, Plotly allows you to create interactive, publication-quality graphs. After creating stunning visualizations with Plotly, you may need to export the graphs as HTML files that can be shared online or viewed offline.

The plotly.io.to_html() function provides a convenient way to convert a Plotly figure into an HTML string or document. In this comprehensive guide, we‘ll demonstrate how to use to_html() to export your figures as consumable HTML content.

Overview of plotly.io.to_html()

The to_html() exporter function belongs to Plotly‘s io module. It accepts a figure object and numerous optional parameters for customizing the output.

Here is the function signature:

plotly.io.to_html(
    fig,
    config=None,
    auto_play=True,
    include_plotlyjs=True,
    include_mathjax=False, 
    post_script=None,
    full_html=True,
    animation_opts=None,
    default_width=‘100%‘,
    default_height=‘100%‘,
    validate=True
)

The parameters allow specifying plotly.js config options, animation settings, mathjax inclusion, post-export scripts, and more. The function returns an HTML string representing the figure.

Now let‘s see some examples of converting figures to HTML using this function.

Basic HTML Export

To demonstrate the basic usage, let‘s create a simple scatter plot figure with Plotly Express:

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")

We can now export fig to an HTML string like so:

import plotly.io as pio

html_str = pio.to_html(fig, full_html=False)
print(html_str[:500]+ ‘...‘)

This prints the initial 500 characters of the HTML string, which starts with the <div> container:

<div>
    <div id="3f4cb415-e03e-43c1-8305-d4826f9d8696" class="plotly-graph-div" style="height:100%; width:100%;"></div>
    <script type="text/javascript">

      window.PLOTLYENV=window.PLOTLYENV || {};

      if (document.getElementById("3f4cb415-e03e-43c1-8305-d4826f9d8696")) {
        Plotly.newPlot(
          ‘3f4cb415-e03e-43c1-8305-d4826f9d8696‘,
          [{"hovertemplate": "sepal_width=%{x}<br>sepal_length=%{y}<br>species=%{marker.color}<extra></extra>", "legendgroup": "", "marker": {"color": [...]), 
          {

The full HTML wasn‘t printed due to the full_html=False argument. If we want to export a complete HTML page, we need to set it to True:

full_html_str = pio.to_html(fig, full_html=True)
print(full_html_str[:500] + ‘...‘)  

Now the output contains the DOCTYPE declaration and <html> tags:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript" src="https://cdn.plot.ly/plotly-latest.min.js"></script>  
</head>
<body>
    <div>
      <div id="3f4cb415-e03e-43c1-8305-d4826f9d8696" class="plotly-graph-div" style="height:100%; width:100%;">...

The figure is embedded within the <body> section, ready for viewing!

Including plotly.js Library

When exporting to a standalone HTML document, the plotly.js library needs to be included so that the figure renders properly.

By default, to_html() embeds a CDN link to plotly.js in the <head>. But we can customize this using the include_plotlyjs parameter:

# Embed plotly.js from CDN 
pio.to_html(fig, include_plotlyjs=‘cdn‘)

# Include local plotly.min.js file
pio.to_html(fig, include_plotlyjs=‘directory‘) 

# Load plotly.js with require.js 
pio.to_html(fig, include_plotlyjs=‘require‘)

Setting include_plotlyjs=False excludes the library altogether. Avoid this when exporting full HTML, or the figure won‘t render!

For offline use cases, include_plotlyjs=‘directory‘ is useful for bundling a local plotly.js file with the HTML.

Exporting Animation

to_html() also handles exporting figures containing frame animations. Just set auto_play=True so that the animation runs automatically on page load:

import plotly.graph_objects as go

fig = go.Figure(
    data=[{‘x‘: [1, 2], ‘y‘: [1, 2]}],
    layout={‘xaxis‘: {‘range‘: [0, 5], ‘autorange‘: False}},
    frames=[
        {‘data‘: [{‘x‘: [1, 2], ‘y‘: [1, 2]}]},
        {‘data‘: [{‘x‘: [1, 4], ‘y‘: [1, 4]}]}
    ]  
)

html_str = pio.to_html(fig, auto_play=True, full_html=True) 
# Animation will now autoplay!

There are additional animation_opts that can be set as well.

Exporting to an HTML File

While to_html() returns the HTML string, we usually want to write this content to a .html file.

Here is how to export the figure as chart.html:

html_str = pio.to_html(fig, full_html=True)

with open(‘chart.html‘, ‘w‘) as f:
    f.write(html_str)

Now chart.html will contain a fully standalone HTML document with the rendered Plotly figure!

This file can be opened locally in the browser, shared online, or embedded into other webpages.

Customizing with Templates

Plotly‘s templating engine makes it easy to customize the exported HTML‘s overall style and appearance.

First, let‘s create a template that sets the page background color:

import plotly.io as pio
import plotly.graph_objs as go

template = pio.templates["plotly"] # Start with plotly template 
template.layout.paper_bgcolor = "lavender" # Customize

fig = go.Figure(...) 

# Apply template
fig.update_layout(template=template)  

html_str = pio.to_html(fig, full_html=True)

The exported html_str will now render the graph with a lavender background. Any layout style properties can be customized this way.

There are also many prebuilt templates available to quickly style your graphics.

Additional Tips

  • Use the post_script parameter to insert custom JavaScript that executes after plot creation. This allows further customizing the rendered output.

  • Set validate=False to skip validating the figure before exporting. This improves performance.

  • The exported <div> containing the graph defaults to 100% height and width. Adjust this using the default_width and default_height parameters.

  • Math equations written in TeX notation can also be included via the include_mathjax parameter.

Conclusion

As seen throughout these examples, Plotly‘s to_html() function empowers you to effortlessly export your figures as HTML documents or strings. You can save the outputs to files or inject them into webpages or applications.

Leverage parameters like full_html, include_plotlyjs, and template to tailor the HTML export to your specific use case. By handling minification and SVG conversion automatically, to_html() takes the complexity out of preparing Plotly charts for the web.

To learn more, refer to the plotly.io.to_html() documentation. I hope this guide gives you the tools to seamlessly share your Plotly visualizations as HTML to engage wider audiences!

Similar Posts