Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
📊 Week 4 – Visualisation और Storytelling  ·  दिन 23

दिन 23: Plotly Interactive Charts

⏱ 2 hours📶 Intermediate🎯 100% self-study
दिन 23 / 60

✅ आज आप सीखेंगे

  • 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

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
🖱️ आज़माएँ

किसी point पर hover करें, zoom के लिए drag करें, reset के लिए double-click, और legend में category पर click करके उसे छिपाएँ।

Hover details वाला scatter

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

Hierarchy: 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 90% ज़रूरतें पूरी करता है। पूरे control के लिए – दो y-axes, bar और line साथ – 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

Functionइस्तेमाल
px.line / px.areaसमय के साथ trends
px.barCategories की तुलना (barmode="group")
px.scatterRelationships, hover_data, trendline="ols"
px.histogram / px.boxDistributions
px.pie / px.sunburst / px.treemapपूरे का हिस्सा, hierarchy
px.choroplethMaps (Indian states के लिए geojson)
animation_frame=समय के साथ animation
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
⚖️ Plotly कब न लें

PDF reports और printed slides के लिए static Matplotlib/Seaborn image आसान है। Dashboards, web pages और exploration के लिए Plotly।

🏅 आज के Job Skills

✔ plotly.express से interactive charts✔ Hover data, size और colour जोड़ना✔ Complex layouts के लिए graph_objects✔ Share करने लायक HTML export

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: px.bar से payment method के हिसाब से churn rate का interactive bar chart बनाकर churn.html में save करें।
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: Category → product के हिसाब से revenue का px.treemap बनाएँ।
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: Mall customers scatter (income vs spending) को age band पर animation_frame से animate करें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. Interactive chart share करने के लिए कौन save करता है?
HTML किसी भी browser में खुलता है।
2. px.scatter में hover_data=["age"]…
Extra columns tooltip में दिखते हैं।
3. Region → city → category shares के लिए सबसे अच्छा Plotly chart?
Sunburst और treemap hierarchy दिखाते हैं।
4. include_plotlyjs="cdn" HTML को…
Library CDN से load होती है।
5. एक chart में दो अलग y-axes के लिए?
फिर trace में secondary_y=True दें।

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 और ऐसी कहानी में बदलें जो फ़ैसले करवाए।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

मेरी script में fig.show() कुछ नहीं करता।
सामान्य .py file में यह browser tab खोलता है; server पर write_html लें। Jupyter/Colab में cell के नीचे दिखता है।
क्या Plotly PNG export कर सकता है?
हाँ, 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.

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

अगला topicदिन 24: Data Storytelling और Dashboards आपकी प्रगति: 23 / 60 (38%) · Lesson 24 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें