Plotly: Interactive Charts for the Web

Plotly: Interactive Charts for the Web in Python: Matplotlib produces a picture. Plotly produces a web page. That difference is the entire reason to learn it.

Concept Explanation

Matplotlib produces a picture. Plotly produces a web page. That difference is the entire reason to learn it.

A Plotly figure renders as HTML plus JavaScript, so the reader can hover a point to see its exact value, drag to zoom, click legend entries to hide series, and export a PNG — all without you writing a line of front-end code. For a dashboard, a shared report, or anything embedded in a web app, that interactivity is not decoration; it is what lets one chart answer ten questions.

Installing

pip install plotly

No browser plugin, no server. A figure can write itself to a standalone .html file you can email.

Two APIs, and Which to Use

APIImportUse when
Plotly Expressimport plotly.express as pxAlmost always. One line per chart, DataFrame-native
Graph Objectsimport plotly.graph_objects as goFine control, mixed chart types, custom subplots

Start with Express. It returns the same Figure object Graph Objects builds, so you can always drop down a level with fig.update_traces() and fig.update_layout() rather than starting over.

Plotly Express Is Column-Oriented

You pass a DataFrame and name columns — including for the visual channels:

px.scatter(df, x="height", y="weight", color="team", size="age", hover_data=["name"])

color, size, symbol, facet_row, and facet_col all take column names. This is why Express is so compact: encoding a fourth variable is one more keyword, not a loop.

The Chart Functions

FunctionShows
px.lineTrends over an ordered axis
px.barMagnitude per category
px.scatterRelationship between two variables
px.histogramDistribution
px.box / px.violinDistribution comparison
px.pie / px.treemap / px.sunburstPart-to-whole, including hierarchies
px.choroplethValues on a map
px.imshowHeatmaps and matrices

Getting the Figure Out

MethodResult
fig.show()Opens in a browser tab (or renders inline in Jupyter)
fig.write_html("chart.html")Standalone interactive file — the killer feature
fig.write_image("chart.png")Static export (needs pip install kaleido)
fig.to_html(full_html=False)An HTML fragment to embed in your own template

That last one is how you put a Plotly chart into a Flask, Django, or FastAPI page.


Code Example #1 (Basic)

Three interactive charts, three lines of real work each.

import pandas as pd
import plotly.express as px

df = pd.DataFrame({
    "month":   ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] * 2,
    "region":  ["North"] * 6 + ["South"] * 6,
    "revenue": [12000, 14500, 13200, 17800, 19100, 21500,
                 9800, 10400, 12900, 11500, 14200, 16800],
    "orders":  [120, 145, 132, 178, 191, 215,
                 98, 104, 129, 115, 142, 168],
})

# 1. A grouped line chart -- hover shows exact values
fig = px.line(
    df, x="month", y="revenue", color="region",
    markers=True,
    title="Monthly Revenue by Region",
    labels={"revenue": "Revenue (GBP)", "month": "Month"},
)
fig.update_layout(hovermode="x unified")     # one tooltip listing every series
fig.write_html("revenue.html")

# 2. Grouped bars
fig = px.bar(
    df, x="month", y="orders", color="region",
    barmode="group",
    title="Orders by Region",
)
fig.write_html("orders.html")

# 3. Scatter with a fitted trend line
fig = px.scatter(
    df, x="orders", y="revenue", color="region",
    size="revenue", hover_data=["month"],
    trendline="ols",                          # needs: pip install statsmodels
    title="Revenue vs Order Volume",
)
fig.write_html("correlation.html")

print("Open revenue.html in a browser and hover over the lines.")

hovermode="x unified" is the single best default change: instead of one tooltip per series, the reader gets one box listing every series at that x position — which is almost always the comparison they wanted.

Code Example #2 (Intermediate)

A small dashboard: faceting, a secondary axis, and a self-contained HTML file.

import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

rng = np.random.default_rng(7)
days = pd.date_range("2024-01-01", periods=120, freq="D")

df = pd.DataFrame({
    "date":     np.repeat(days, 3),
    "product":  np.tile(["Basic", "Pro", "Enterprise"], len(days)),
    "revenue":  rng.gamma(6, 250, len(days) * 3).round(2),
    "signups":  rng.integers(2, 40, len(days) * 3),
})

# --- 1. Faceted view: one panel per product, shared scale ---
fig = px.area(
    df, x="date", y="revenue",
    facet_col="product", facet_col_wrap=3,
    title="Revenue Trend per Product",
    labels={"revenue": "Revenue (GBP)", "date": ""},
)
# Facet titles arrive as "product=Pro" -- strip the prefix
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update_layout(showlegend=False, height=380)
fig.write_html("facets.html")

# --- 2. Two measures on two y-axes, using Graph Objects ---
daily = df.groupby("date").agg(revenue=("revenue", "sum"),
                               signups=("signups", "sum")).reset_index()

fig = make_subplots(specs=[[{"secondary_y": True}]])

fig.add_trace(
    go.Scatter(x=daily["date"], y=daily["revenue"],
               name="Revenue", line=dict(width=2, color="#2b6cb0")),
    secondary_y=False,
)
fig.add_trace(
    go.Bar(x=daily["date"], y=daily["signups"],
           name="Signups", marker=dict(color="#f6ad55"), opacity=0.6),
    secondary_y=True,
)

fig.update_yaxes(title_text="Revenue (GBP)", secondary_y=False)
fig.update_yaxes(title_text="Signups", secondary_y=True, showgrid=False)
fig.update_layout(
    title="Revenue and Signups",
    hovermode="x unified",
    template="plotly_white",
    legend=dict(orientation="h", y=1.08, x=0),
    height=420,
)

# --- 3. Stitch both charts into one HTML page ---
facets_html = px.area(df, x="date", y="revenue", facet_col="product",
                      facet_col_wrap=3).to_html(full_html=False,
                                                include_plotlyjs="cdn")
combo_html = fig.to_html(full_html=False, include_plotlyjs=False)

page = f"""<!doctype html>
<html><head><meta charset="utf-8"><title>Sales Dashboard</title>
<style>body{{font-family:system-ui;margin:2rem;max-width:1100px}}</style>
</head><body>
<h1>Sales Dashboard</h1>
{facets_html}
{combo_html}
</body></html>"""

with open("dashboard.html", "w", encoding="utf-8") as f:
    f.write(page)

print("Wrote dashboard.html -- a single self-contained interactive page.")

Two details that matter for real use: include_plotlyjs="cdn" on the first chart and False on the rest keeps the file small instead of embedding the 3 MB library twice, and template="plotly_white" produces something that looks deliberate rather than default.


Common Mistakes

  1. Expecting fig.show() to work everywhere: in a plain script it opens a browser; in some remote or headless environments it silently does nothing. write_html always works.
  2. Forgetting kaleido for static export: write_image() fails with an unhelpful error until you pip install kaleido.
  3. Embedding plotly.js in every chart: three charts at include_plotlyjs=True is a 10 MB page. Use "cdn" once, then False.
  4. Passing lists instead of a DataFrame to Express: it works, but you lose color=, facet_col=, and automatic axis labels — the whole reason to use Express.
  5. Long-format vs wide-format confusion: Express wants long data (one row per observation, a category column). If your regions are separate columns, call df.melt() first.
  6. Plotting 500,000 points as a scatter: the browser has to hold every point. Use px.scatter(..., render_mode="webgl") or aggregate.
  7. Leaving product=Pro as a facet title: always strip the prefix with for_each_annotation.
  8. Choosing Plotly for a print report: interactivity is worthless on paper, and Matplotlib gives finer typographic control. Match the tool to the destination.

Best Practices

  • Default to Plotly Express, drop to Graph Objects for the last 10%.
  • Set hovermode="x unified" on any time series with more than one line.
  • Pass labels={...} to rename axes and legends without renaming your columns.
  • Pick a template: plotly_white or simple_white look far more professional than the default.
  • Use write_html for sharing: one file, no dependencies, works in any browser, no server needed — this is Plotly's real superpower.
  • Reshape to long format first: df.melt(id_vars="date", var_name="region", value_name="sales") unlocks the whole Express API.
  • Set height explicitly: the default aspect ratio rarely suits a dashboard.
  • Cap the point count: aggregate, sample, or switch to WebGL above ~50,000 marks.
  • Reach for Dash only when you need callbacks: static interactive HTML covers more cases than people expect, and needs no server.

Practice Exercises

  1. The Shareable Chart: Build a Plotly Express line chart from any DataFrame, set hovermode="x unified" and the plotly_white template, and write it to chart.html. Open it and confirm you can zoom, hover, and toggle series.
  2. The Reshape: Start with a wide DataFrame (one column per region), use df.melt() to make it long, then produce a faceted bar chart with one panel per region — stripping the region= prefix from the facet titles.
  3. The Dual Axis: Using make_subplots(specs=[[{"secondary_y": True}]]), plot revenue as a line and order count as bars on the same figure with two labelled y-axes. Then write a comment on when a dual axis genuinely helps and when it misleads.