दिन 23: Plotly Interactive Charts
✅ आज आप सीखेंगे
- Plotly Express: हर chart एक line में
- Hover data, colour, size और facets
- Sunburst / treemap से hierarchy
- Dual axes और range sliders के लिए graph_objects
- Charts को एक HTML file की तरह share करना
🏢 असली दुनिया में
Static PNG एक सवाल का जवाब देता है। Interactive chart से regional manager अपने सवाल ख़ुद हल करती है: hover करके value देखना, October में zoom, कोई category छिपाना, किसी शहर में click करना। Plotly यह लगभग Matplotlib जितने code से करता है – और result किसी भी 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")किसी point पर hover करें, zoom के लिए drag करें, reset के लिए double-click, और legend में category पर click करके उसे छिपाएँ।
Hover details वाला scatter
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")Hierarchy: 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 90% ज़रूरतें पूरी करता है। पूरे control के लिए – दो y-axes, bar और line साथ – 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 | इस्तेमाल |
|---|---|
| px.line / px.area | समय के साथ trends |
| px.bar | Categories की तुलना (barmode="group") |
| px.scatter | Relationships, hover_data, trendline="ols" |
| px.histogram / px.box | Distributions |
| px.pie / px.sunburst / px.treemap | पूरे का हिस्सा, hierarchy |
| px.choropleth | Maps (Indian states के लिए geojson) |
| animation_frame= | समय के साथ animation |
# 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 offlinePDF reports और printed slides के लिए static Matplotlib/Seaborn image आसान है। Dashboards, web pages और exploration के लिए Plotly।
🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
px.bar से payment method के हिसाब से churn rate का interactive bar chart बनाकर churn.html में save करें।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 बनाएँ।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 से animate करें।Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
Static या interactive charts – कैसे चुनते हैं?
Reports, slides और जब पाठक को एक निष्कर्ष तक ले जाना हो तब static। Dashboards और exploration के लिए interactive जहाँ users को drill-down चाहिए। Interactive chart का default view भी साफ़ होना चाहिए।
Python में data dashboards बनाने के tools बताइए।
Plotly Dash, Streamlit (Day 50), Panel और Voilà। Business में Power BI और Tableau भी आम हैं (Day 52)।
सारांश
- plotly.express DataFrames से एक line में interactive charts बनाता है।
- hover_data, color, size, facet और animation_frame गहराई जोड़ते हैं।
- Dual axes और custom layouts के लिए graph_objects + make_subplots।
- write_html से chart किसी के साथ भी share।
Day 24: Data storytelling – charts को dashboard और ऐसी कहानी में बदलें जो फ़ैसले करवाए।
