Guide
Exporting a Color‑Mapped Scatter Plot to a Self‑Contained HTML File with Plotly Express
Learn how to build an interactive scatter plot that maps a categorical variable to color, then export it as a stand‑alone HTML file for sharing or embedding. Follow the step‑by‑step guide, check the output, and know the limits.
Published by Tasadduq Burney
25 Apr 2026, 10:49 UTC
3 min79.2K views0

Desired Outcome
Generate an interactive scatter plot that uses a categorical column to color the points, then export that figure as a self‑contained HTML file that can be opened in any browser without external dependencies.
Prerequisites
- Python 3.9+ installed.
- Installed packages:
pandas,plotly==5.24.0(or later). - A CSV or DataFrame containing at least three columns:
x,y, and a categorical column (e.g.,category). - Write permission to the directory where the HTML will be saved.
Step‑by‑Step Procedure
- Import Libraries
import pandas as pd import plotly.express as px - Load Your Data
# Replace 'data.csv' with your file path # Ensure the categorical column is of type 'category' for optimal legend handling df = pd.read_csv('data.csv') # Example columns: 'x', 'y', 'group' df['group'] = df['group'].astype('category') - Create the Scatter Plot
fig = px.scatter( df, x='x', y='y', color='group', # categorical mapping title='Interactive Scatter Plot', labels={'x': 'X‑Axis', 'y': 'Y‑Axis', 'group': 'Group'}, color_discrete_sequence=px.colors.qualitative.G10 # optional palette ) # Add a subtle layout tweak (optional) fig.update_layout(legend_title_text='Group') - Export to Self‑Contained HTML
output_path = 'scatter.html' fig.write_html(output_path, include_plotlyjs='cdn', full_html=True) print(f"HTML file written to {output_path}")Parameters explained:
include_plotlyjs='cdn'– pulls Plotly.js from a CDN. Use'cdn'for smaller files;'cdn'is the default. If you need offline operation, use'cdn'too but ensure the environment can reach the CDN.full_html=True– creates a complete HTML document with<html>and<body>tags.
- Verify the Output
import os assert os.path.exists(output_path), 'File was not created'
Expected Checks
- Open
scatter.htmlin a modern browser (Chrome, Firefox, Edge). The plot should display, with axes labeled, a legend, and hover tooltips showingx,y, andgroupvalues. - Inspect the browser console for errors. A missing
plotly.min.jsor a 404 from the CDN indicates a network restriction. - Run
fig.to_dict()in Python to confirm that thedataarray contains trace objects with the correctx,y, andmarker.colorfields.
Recovery Options
- Missing CDN Script – If the browser blocks external scripts, switch to
include_plotlyjs='cdn'to'cdn'or'cdn'to'cdn'and host Plotly.js locally. For a quick fix, downloadplotly.min.jsand setinclude_plotlyjs='cdn'to a local path. - Large Datasets – The exported HTML grows with data size. For millions of points, consider using Plotly’s
scatterglor a server‑side rendering approach. Alternatively, downsample the data before plotting. - NaN Values – Plotly silently drops points with
NaN. Clean your DataFrame withdf.dropna(subset=['x', 'y', 'group'])before plotting. - Path Issues on Windows – Use raw strings or
pathlib.Pathto avoid escape character problems:output_path = r'scatter.html'oroutput_path = Path('scatter.html').
Limitations and Alternatives
- Plotly Express is a thin wrapper; for advanced callbacks or dynamic updates you’ll need Dash or custom JavaScript.
- The exported HTML file is static. If you need real‑time updates, host the figure in a Dash app or use Plotly’s
streamingAPI. - Color mapping relies on Plotly’s discrete palette. Custom color scales can be applied with
color_discrete_mapfor fine‑grained control. - For very large HTML files, consider server‑side rendering with
fig.write_imageto PNG or SVG and embed that image instead.
Practical Checklist
| Step | Verification |
|---|---|
| Figure created | fig is not None; fig.data length > 0 |
| File written | os.path.exists('scatter.html') |
| Browser render | Plot appears; hover shows data; legend matches categories |
| Console | No 404 or JS errors |
| Data integrity | fig.to_dict() contains correct columns |
Follow this guide to quickly produce interactive, shareable scatter plots that map categorical variables to color and bundle everything into one portable HTML file.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.