Day 23: Plotly Interactive Charts
✅ Today you will learn
- Plotly Express: one line per chart
- Hover data, colour, size and facets
- Hierarchies with sunburst / treemap
- graph_objects for dual axes and range sliders
- Share charts as a single HTML file
🏢 In the real world
A static PNG answers one question. An interactive chart lets the regional manager answer her own: hover to see a value, zoom into October, hide a category, click into a city. Plotly makes this possible with almost the same code as Matplotlib – and the result opens in any browser.
Interactive line chart
import pandas as pd
import plotly.express as px
s = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
s["revenue"] = s["quantity"] * s["unit_price"] * (1 - s["discount"])
m = s.groupby([s["order_date"].dt.to_period("M").dt.to_timestamp(), "category"])["revenue"].sum().reset_index()
fig = px.line(m, x="order_date", y="revenue", color="category", markers=True,
title="Monthly revenue by category – hover, zoom, click the legend",
labels={"order_date": "Month", "revenue": "Revenue (₹)"})
fig.update_layout(template="plotly_white", height=420, legend_title_text="")
fig.write_html("revenue_trend.html", include_plotlyjs="cdn")
print("Saved revenue_trend.html")Hover over a point, drag to zoom, double-click to reset, and click a category in the legend to hide it.
Scatter with hover details
import pandas as pd
import plotly.express as px
h = pd.read_csv("house_prices.csv")
fig = px.scatter(h, x="area_sqft", y="price_lakh", color="city", size="bedrooms",
hover_data=["age_years", "metro_km", "furnishing"],
title="800 homes – hover any dot to see its details",
labels={"area_sqft": "Area (sqft)", "price_lakh": "Price (₹ lakh)"})
fig.update_traces(marker=dict(opacity=0.65, line=dict(width=0)))
fig.update_layout(template="plotly_white", height=440)
fig.write_html("houses.html", include_plotlyjs="cdn")
print("Saved houses.html")Hierarchies: sunburst
import pandas as pd
import plotly.express as px
s = pd.read_csv("sales_data.csv")
s["revenue"] = s["quantity"] * s["unit_price"] * (1 - s["discount"])
fig = px.sunburst(s, path=["region", "city", "category"], values="revenue",
title="Click a region to zoom in: region → city → category")
fig.update_layout(height=460, margin=dict(t=50, l=0, r=0, b=0))
fig.write_html("sunburst.html", include_plotlyjs="cdn")
print("Saved sunburst.html")graph_objects: dual axis + range slider
plotly.express covers 90% of needs. For full control – two y-axes, mixed bar and line – use plotly.graph_objects.
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
w = pd.read_csv("delhi_weather.csv", parse_dates=["date"])
m = w.set_index("date").resample("ME").mean().reset_index()
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Bar(x=m["date"], y=m["aqi"], name="AQI", marker_color="#fca5a5"), secondary_y=False)
fig.add_trace(go.Scatter(x=m["date"], y=m["avg_temp_c"], name="Temp °C", line=dict(color="#1d4ed8", width=3)), secondary_y=True)
fig.update_layout(title="Delhi: cold months = bad air", template="plotly_white", height=420,
xaxis=dict(rangeslider=dict(visible=True)))
fig.update_yaxes(title_text="AQI", secondary_y=False); fig.update_yaxes(title_text="°C", secondary_y=True)
fig.write_html("delhi.html", include_plotlyjs="cdn")
print("Saved delhi.html")Plotly Express cheat sheet
| Function | Use |
|---|---|
| px.line / px.area | Trends over time |
| px.bar | Compare categories (barmode="group") |
| px.scatter | Relationships, hover_data, trendline="ols" |
| px.histogram / px.box | Distributions |
| px.pie / px.sunburst / px.treemap | Parts of a whole, hierarchy |
| px.choropleth | Maps (needs geojson for Indian states) |
| animation_frame= | Animate over time |
# In Jupyter / Colab simply write:
fig.show() # opens the interactive chart below the cell
# Share with anyone (no Python needed to open):
fig.write_html("report.html", include_plotlyjs="cdn") # small file, needs internet
fig.write_html("report_offline.html") # ~4 MB, works offlineFor PDF reports and printed slides a static Matplotlib/Seaborn image is simpler. Use Plotly for dashboards, web pages and exploration.
🏅 Job skills unlocked today
Practice tasks
🏋️ Practice – do it yourself
px.bar and save it as churn.html.Show solution
import pandas as pd
import plotly.express as px
t = pd.read_csv("telecom_churn.csv")
r = (t.groupby("payment_method")["churn"].apply(lambda c: (c == "Yes").mean() * 100)).round(1).reset_index(name="churn_%")
fig = px.bar(r.sort_values("churn_%"), x="churn_%", y="payment_method", orientation="h", text="churn_%", title="Churn % by payment method")
fig.write_html("churn.html", include_plotlyjs="cdn")
print(r)px.treemap of revenue by category → product.Show solution
import pandas as pd
import plotly.express as px
s = pd.read_csv("sales_data.csv")
s["revenue"] = s["quantity"] * s["unit_price"] * (1 - s["discount"])
fig = px.treemap(s, path=["category", "product"], values="revenue")
fig.write_html("treemap.html", include_plotlyjs="cdn"); print("saved")animation_frame set to an age band.Quick quiz
🧠 Quick Quiz – test yourself
Interview corner
💼 Interview Corner
Static or interactive charts – how do you choose?
Static for reports, slides and when you want to guide the reader to one conclusion. Interactive for dashboards and exploration where users need to drill down. Interactive charts should still have a clear default view.
Name tools to build data dashboards in Python.
Plotly Dash, Streamlit (Day 50), Panel and Voilà. In business, Power BI and Tableau are also common (Day 52).
Summary
- plotly.express builds interactive charts from DataFrames in one line.
- hover_data, color, size, facet and animation_frame add depth.
- graph_objects + make_subplots for dual axes and custom layouts.
- write_html shares a chart with anyone.
Day 24: Data storytelling – turn charts into a dashboard and a story that drives decisions.
