Back to Blog
Python

Python Plotly: Save HTML and Export Images

python plotly save html and export images: Learn how to save Plotly figures as interactive HTML and export them as PNG, JPEG, or SVG images using write_html and write_...

plotlydata visualizationhtml exportimage exportkaleido
A Plotly chart displayed both as an interactive HTML page and as a static PNG image, illustrating the two export methods.

python plotly save html and export images requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

To save a Plotly figure as HTML and export it as a static image, you use two separate APIs: write_html and write_image. The first produces an interactive HTML file; the second generates a PNG, JPEG, or SVG. The image export path depends on the kaleido package, so you need to understand how both APIs behave before you build an export pipeline.

Saving a Plotly Figure as HTML

The write_html method serializes a figure into a self-contained HTML document. By default, it embeds the Plotly.js library directly, so the file works offline and can be shared without additional dependencies.

import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[4, 5, 6])) fig.write_html("chart.html")

This produces a complete HTML page with the interactive chart. If you want to embed the chart in an existing page, set full_html=False to get only the <div> and <script> tags. You can also control whether Plotly.js is included inline or referenced from a CDN using the include_plotlyjs parameter:

fig.write_html("chart.html", full_html=False, include_plotlyjs="cdn")

For most standalone exports, the default is sufficient. When you need to embed multiple charts in one page, you may want to use full_html=False and include Plotly.js once manually.

Exporting a Plotly Figure as a Static Image

To export a static image, use write_image. This method requires the kaleido package, which is a separate dependency that must be installed in your environment.

fig.write_image("chart.png")

If kaleido is not installed, Plotly raises an error telling you to install it. The typical installation command is pip install kaleido. Once installed, write_image renders the figure using a headless browser engine and captures the output as an image.

The method accepts the same file extensions as the format parameter: png, jpeg, webp, svg, pdf, and eps. For raster formats, you can control resolution with the scale parameter, which multiplies the default pixel density.

Choosing Image Formats and Controlling Output Size

Image format affects both visual quality and file size. PNG is lossless and supports transparency, making it a good choice for web graphics. JPEG is lossy and smaller, but it does not support transparency. SVG is a vector format that scales without loss, ideal for diagrams that may be viewed at different zoom levels.

You can set the output dimensions directly in write_image using width and height in pixels:

fig.write_image("chart.png", width=800, height=600, scale=2)

The scale parameter multiplies the pixel dimensions. A scale of 2 with width=800 produces a 1600×1200 image. This is useful for high-resolution prints or retina displays.

When exporting to SVG, width and height define the viewBox, but the actual vector coordinates are resolution-independent. For PDF, the same parameters control the page size in points.

Exporting Multiple Figures and Working with Subplots

If you have several figures to export, you can loop over them and call write_html or write_image for each. A common pattern is to generate a report with one HTML file per chart or a single HTML file with multiple charts embedded.

import plotly.subplots as sp fig = sp.make_subplots(rows=2, cols=1) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1) fig.add_trace(go.Bar(x=["a", "b", "c"], y=[1, 2, 3]), row=2, col=1) fig.write_html("subplots.html") fig.write_image("subplots.png")

For subplots, write_image renders the entire grid as a single image. If you need each subplot as a separate image, you would have to create individual figures for each trace group.

When exporting many figures, be mindful of memory usage. Each write_image call spawns a rendering process. In a loop, this can accumulate if you keep references to figures. Reuse the figure object or delete it after export if you are processing a large batch.

Runtime and Operational Considerations for Image Export

The kaleido package is the main operational dependency. It is a separate binary that runs as a subprocess. On first use, it may need to download or initialize a browser engine, which can cause a noticeable delay. In production environments, you should install kaleido during the image build step rather than at runtime to avoid unexpected network calls.

In serverless or containerized environments, kaleido needs certain system libraries to run headless Chromium. If you encounter missing shared libraries, you may need to install additional system packages. The exact dependencies depend on your base image, but they are typically the same ones required by Chromium.

Another consideration is concurrency. write_image is not thread-safe because it launches an external process. If you need to export images concurrently, use a process pool or a task queue rather than spawning threads. Each process will have its own kaleido instance, which isolates failures but increases memory consumption.

Troubleshooting Common Export Failures

The most common error when calling write_image is a missing kaleido installation. The error message usually says something like:

ValueError: Image export requires the kaleido package.

Install it with pip install kaleido. If you are using a virtual environment, ensure the same environment is active when you run the script.

Another frequent issue is a kaleido subprocess failure due to missing system libraries. The error often appears as a non-zero exit code or a message about a missing shared object. On Debian-based systems, you may need to install packages like libnss3, libatk-bridge2.0-0, and libx11-xcb1. The exact set varies, so check the process output for the specific library name.

If you are exporting to SVG and the output looks blurry, check whether you are using a raster format by mistake. SVG is vector, so it should be crisp at any zoom. If you need a transparent background, use PNG or SVG; JPEG does not support transparency.

Finally, if the exported image is blank or cropped, verify that the figure has valid traces and that the layout margins are not set to zero. A figure with no traces will render as an empty canvas, which is often mistaken for a rendering failure.

python plotly save html and export images: Practical Usage a | RYUSLOG DEV