Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📊 Week 4 – Visualisation & Storytelling  ·  Day 23

Day 23: Plotly Interactive Charts

⏱ 2 hours📶 Intermediate🎯 100% self-study
Day 23 / 60

✅ 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

Python
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")
Saved revenue_trend.html
▶  revenue_trend.html – live
🖱️ Try it

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

Python
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")
Saved houses.html
▶  houses.html – live

Hierarchies: sunburst

Python
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")
Saved sunburst.html
▶  sunburst.html – live

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.

Python
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")
Saved delhi.html
▶  delhi.html – live

Plotly Express cheat sheet

FunctionUse
px.line / px.areaTrends over time
px.barCompare categories (barmode="group")
px.scatterRelationships, hover_data, trendline="ols"
px.histogram / px.boxDistributions
px.pie / px.sunburst / px.treemapParts of a whole, hierarchy
px.choroplethMaps (needs geojson for Indian states)
animation_frame=Animate over time
Python
# 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 offline
⚖️ When not to use Plotly

For PDF reports and printed slides a static Matplotlib/Seaborn image is simpler. Use Plotly for dashboards, web pages and exploration.

🏅 Job skills unlocked today

✔ Build interactive charts with plotly.express✔ Add hover data, size and colour encodings✔ Use graph_objects for complex layouts✔ Export shareable HTML

Practice tasks

🏋️ Practice – do it yourself

Task 1: Make an interactive bar chart of churn rate by payment method with px.bar and save it as churn.html.
Show solution
Python
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)
payment_method churn_% 0 Bank Transfer 27.8 1 Cash 32.6 2 Credit Card 27.1 3 UPI AutoPay 29.0
Task 2: Create a px.treemap of revenue by category → product.
Show solution
Python
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")
saved
Task 3: Animate the mall customers scatter (income vs spending) with animation_frame set to an age band.

Quick quiz

🧠 Quick Quiz – test yourself

1. Which saves an interactive chart to share?
The HTML opens in any browser.
2. hover_data=["age"] in px.scatter…
Extra columns appear in the tooltip.
3. Best Plotly chart for region → city → category shares?
Sunburst and treemap show hierarchy.
4. include_plotlyjs="cdn" makes the HTML…
The library loads from a CDN.
5. Two different y-axes in one chart need…
Then pass secondary_y=True to the trace.

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.
➡️ Next

Day 24: Data storytelling – turn charts into a dashboard and a story that drives decisions.

Frequently Asked Questions

fig.show() does nothing in my script.
In a plain .py file it opens a browser tab; on a server use write_html. In Jupyter/Colab it renders below the cell.
Can Plotly export PNG?
Yes, with the kaleido package: fig.write_image("chart.png").
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 24: Data Storytelling & Dashboards Your progress: 23 / 60 (38%) · Lesson 24 / 60 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free