📊 Section 3 · Data Viz 🟡 Intermediate MODULE 16

Plotly — Interactive Charts

⏱️ 24 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Section 360%
🎯 What you'll learn: Matplotlib and Seaborn produce static images — great for reports and print, but they can't respond to a mouse. Plotly builds charts as interactive web objects: hover over a point to see its exact value, drag to zoom into a region, and pan around — all without writing a line of JavaScript. You'll use Plotly Express (plotly.express), the high-level module that mirrors Seaborn's "point it at a DataFrame" style, to build bar, line, and scatter charts, then export one to a standalone HTML file.

Why Interactive Charts?

A static chart shows one fixed view of the data — if a bar's exact value matters, the viewer has to guess from the axis gridlines. An interactive chart lets the viewer explore it themselves.

🖱️
Hover tooltips
See the exact value behind any point or bar without guessing from the axis
🔍
Zoom & pan
Drag to zoom into a busy region, then pan around to explore it
🌐
Web-embeddable
Exports to a self-contained HTML file — no image, just a live chart
📝
When to reach for Plotly instead of Matplotlib/Seaborn
Static PNGs from Matplotlib or Seaborn are still the right choice for a printed report or a figure embedded in a PDF. Plotly earns its place when the chart will be viewed on a screen — a notebook, a web page, or (as you'll see in the next two lessons) a live dashboard — and letting someone explore the data themselves adds real value.

plotly.express and px.bar()

plotly.express, conventionally imported as px, is Plotly's high-level charting API — one function call per chart type, taking a DataFrame and column names, much like Seaborn.

px_bar.py
PYTHON
import plotly.express as px
import pandas as pd

df = pd.DataFrame({
    "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    "revenue": [420000, 388000, 455000, 470000, 512000, 498000],
})

fig = px.bar(df, x="month", y="revenue", title="Monthly Revenue")
fig.show()
🖼️ What fig.show() displays
Six vertical bars, one per month, rendered in a browser tab or notebook cell. Hovering over any bar pops up a small tooltip showing "month: Apr, revenue: 470000" — the exact underlying values, not just a visual estimate from the y-axis.

px.line()

px.line() follows the same pattern as px.bar() — same DataFrame, same x/y arguments — just connected with a line instead of bars, the natural choice for a trend over time.

px_line.py
PYTHON
fig = px.line(df, x="month", y="revenue", markers=True, title="Revenue Trend")
fig.show()
markers=True
By default px.line() draws just the connecting line. markers=True adds a visible dot at each actual data point, which makes it much easier to hover over an exact month rather than a spot along the line between two months.

px.scatter()

px.scatter() adds a few arguments beyond what Matplotlib and Seaborn offer directly: color for categorical grouping, size to scale points by a numeric column, and hover_name to control what label appears in the tooltip.

px_scatter.py
PYTHON
products = pd.DataFrame({
    "product": ["Laptop", "Mouse", "Monitor", "Keyboard", "Webcam"],
    "price": [1200, 45, 890, 65, 120],
    "units_sold": [120, 340, 90, 210, 150],
    "category": ["Electronics", "Accessories", "Electronics", "Accessories", "Electronics"],
})

fig = px.scatter(
    products, x="price", y="units_sold",
    color="category", size="units_sold",
    hover_name="product",
    title="Price vs. Units Sold",
)
fig.show()
📝
color= in Plotly Express does what hue= does in Seaborn
Where Seaborn's scatterplot uses hue to color points by category, Plotly Express uses color for the same job — both add a matching legend automatically. The names differ between the two libraries, which is worth remembering when switching back and forth.

fig.show()

Every px.*() function returns a Figure object — nothing is drawn until you call .show() on it. In a Jupyter notebook it renders inline as an interactive widget; in a plain script it opens in your default web browser.

⚠️
A Plotly Figure isn't a Matplotlib Figure
Even though the class is also called Figure, a Plotly figure is a completely different object from Matplotlib's — ax.set_title() and plt.show() don't apply here. Plotly figures use their own methods, like fig.update_layout(title="...") for further customization, which goes beyond what this lesson covers but is worth knowing exists.

Exporting to a Standalone HTML File

Because a Plotly chart is fundamentally a small web app (HTML + JavaScript), it can be saved as one — a single .html file that keeps its hover, zoom, and pan behavior when opened in any browser, with no Python installation needed to view it.

export_html.py
PYTHON
fig = px.line(df, x="month", y="revenue", markers=True, title="Revenue Trend")

# Writes a self-contained interactive HTML file — open it in any browser
fig.write_html("revenue_trend.html")
write_html() vs. write_image()
fig.write_html() keeps the chart fully interactive. If a plain static image is needed instead — for a slide deck or a printed report — fig.write_image("chart.png") is the equivalent, though it requires the extra kaleido package to be installed to render to a raster image.

Lesson Summary

Let's recap everything you learned in this lesson:

Plotly charts are interactive — hover tooltips, zoom, and pan, out of the box.
plotly.express (as px) is the high-level API — px.bar(), px.line(), px.scatter() all take a DataFrame directly.
color, size, and hover_name customize how points are grouped, scaled, and labeled.
fig.show() renders the chart — inline in a notebook, or in a browser tab from a script.
fig.write_html() exports the chart as a standalone, still-interactive HTML file.
🧩 Knowledge Check — Lesson 16
Answer all 5 questions to test your understanding. Instant feedback on every answer.
1. What module provides Plotly's quick, high-level charting API, conventionally imported as px?
2. Which function builds a bar chart in Plotly Express?
3. In px.scatter(df, x="price", y="units_sold", size="units_sold"), what does size control?
4. Which method actually renders a Plotly figure — inline in a notebook, or in a browser tab from a script?
5. Which method exports a Plotly figure to a standalone, still-interactive HTML file?
💪
Coding Challenge — Lesson 16
Apply what you learned · Intermediate Level

Build two interactive charts from the df and products DataFrames used in this lesson.

Challenge: Interactive Revenue Report 📈

Using df (month, revenue) and products (product, price, units_sold, category): (1) build a px.line() trend chart of revenue by month with markers=True, (2) build a px.scatter() chart of price vs. units_sold, colored by category and sized by units_sold, with hover_name="product", and (3) export just the line chart to "monthly_revenue.html".

Rules: Call fig.show() on both charts, and give both a title=.
💡 Show hints if you're stuck
  • Step 1: px.line(df, x="month", y="revenue", markers=True, title="Monthly Revenue Trend")
  • Step 2: px.scatter(products, x="price", y="units_sold", color="category", size="units_sold", hover_name="product", title="Price vs. Units Sold")
  • Step 3: fig.write_html("monthly_revenue.html") — call this on the line chart's figure before or after fig.show()
Finished this lesson?
Mark it complete to track your progress.
🎉

Lesson 16 Complete!

You can build interactive bar, line, and scatter charts with Plotly Express and export them to standalone HTML. Next up: turning these charts into a real, running web dashboard with Plotly Dash.

Module 16 of 18 Section 3 — Data Visualization: Matplotlib & Seaborn