Interactive Charts with Plotly Express
Interactive Charts with Plotly Express: Complete Guide
Static charts ki duniya se bahar aayein — Plotly ke interactive charts mein hover karke data dekhein, zoom karein, pan karein, aur click karke filter karein. 8 essential chart types jo aapke dashboards ko next level par le jayenge.
📑 Is Guide Mein 8 Interactive Charts Cover Honge:
- px.line() — Interactive Line Chart with hover & zoom
- px.bar() — Interactive Bar Chart with click filtering
- px.scatter() — Multi-dimensional Interactive Scatter
- px.histogram() — Interactive Histogram with marginals
- px.pie() — Interactive Pie & Donut Charts
- px.box() — Interactive Box Plot with data points
- px.violin() — Interactive Violin Plot
- px.area() — Interactive Stacked Area Chart
⚙️ Setup — Installation & Sample Data
# Installation
# pip install plotly
# pip install kaleido (for static image export)
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
# Sample Dataset
np.random.seed(42)
df = pd.DataFrame({
"Month": ["Jan","Feb","Mar","Apr","May","Jun"] * 4,
"Revenue": np.random.randint(30000, 90000, 24),
"Department": np.repeat(["IT","HR","Finance","Marketing"], 6),
"Employees": np.random.randint(50, 200, 24)
})
employees = pd.DataFrame({
"Name": [f"Emp_{i}" for i in range(500)],
"Salary": np.concatenate([
np.random.normal(55000, 10000, 200),
np.random.normal(82000, 15000, 200),
np.random.normal(120000, 20000, 100)
]),
"Experience": np.random.uniform(1, 20, 500),
"Age": np.random.randint(22, 58, 500),
"Department": np.random.choice(["IT","HR","Finance","Marketing"], 500),
"Gender": np.random.choice(["Male","Female"], 500),
"Rating": np.random.choice([1,2,3,4,5], 500, p=[0.05,0.1,0.3,0.35,0.2])
})
1. px.line() — Interactive Line Chart
🔍 Kya Hai: Plotly line chart mein hover karke exact values dikhte hain, zoom in/out kar sakte hain, specific lines click karke toggle kar sakte hain — yeh sab matplotlib mein manually impossible hai.
💻 Basic Version:
fig = px.line(df, x="Month", y="Revenue", color="Department",
title="Monthly Revenue by Department")
fig.show()
💻 Professional Styled Version:
fig = px.line(df, x="Month", y="Revenue",
color="Department", # separate line per department
line_group="Department", # group lines by department
markers=True, # show data point markers
symbol="Department", # different marker per group
line_dash="Department", # different line style per group
hover_name="Department", # bold text on hover
hover_data={ # customize hover info
"Revenue": ":.0f", # format as integer
"Employees": True # show employees count
},
labels={ # rename axis labels
"Revenue": "Revenue (₹)",
"Month": "Month",
"Department": "Dept"
},
title="Monthly Revenue Trend by Department",
template="plotly_white", # theme
color_discrete_sequence=px.colors.qualitative.Set2, # color palette
width=900, # figure width
height=500 # figure height
)
# Additional styling
fig.update_traces(
line_width=2.5, # line thickness
marker_size=8 # marker size
)
fig.update_layout(
hovermode="x unified", # "x","y","closest","x unified"
legend_title_text="Department",
font_family="Arial",
title_font_size=20
)
fig.write_html("line_chart.html") # save interactive HTML
fig.show()
📋 px.line() Key Parameters:
| Parameter | Values | Description |
|---|---|---|
color | column name | Category-wise separate colored lines |
markers | True / False | Data points dikhana |
line_dash | column name | Different dash style per group |
hover_data | dict / list | Extra columns hover mein dikhana |
template | "plotly_white","plotly_dark","seaborn" | Chart theme |
hovermode | "x","closest","x unified" | Hover behavior — unified = all lines at once |
2. px.bar() — Interactive Bar Chart
🔍 Kya Hai: Plotly bar chart mein bars par hover karke exact values dikhte hain, legend click karke specific categories on/off kar sakte hain, aur barmode se grouped/stacked switch kar sakte hain.
💻 Grouped + Stacked Versions:
# ===== GROUPED BAR =====
fig = px.bar(df, x="Month", y="Revenue",
color="Department",
barmode="group", # "group","stack","overlay","relative"
text_auto=True, # auto data labels on bars
hover_data=["Employees"],
labels={"Revenue": "Revenue (₹)"},
title="Revenue by Department (Grouped)",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.Set2,
width=900, height=500
)
fig.update_traces(
textfont_size=10, # data label font size
textposition="outside", # "inside","outside","auto","none"
marker_line_width=1, # bar border
marker_line_color="white", # border color
opacity=0.85 # transparency
)
fig.write_html("bar_grouped.html")
fig.show()
# ===== STACKED BAR =====
fig2 = px.bar(df, x="Month", y="Revenue",
color="Department",
barmode="stack", # stacked!
text_auto=",.0f", # formatted data labels
title="Revenue by Department (Stacked)",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.Pastel
)
fig2.write_html("bar_stacked.html")
fig2.show()
# ===== HORIZONTAL BAR =====
fig3 = px.bar(employees.groupby("Department")["Salary"].mean().reset_index(),
x="Salary", y="Department",
orientation="h", # horizontal
text_auto="₹,.0f",
title="Average Salary by Department",
color="Department",
template="plotly_white"
)
fig3.write_html("bar_horizontal.html")
fig3.show()
📋 px.bar() Key Parameters:
| Parameter | Values | Description |
|---|---|---|
barmode | "group","stack","overlay","relative" | Bars arrangement |
text_auto | True, ",.0f", "₹,.0f" | Auto data labels with format |
orientation | "v" / "h" | Vertical or horizontal |
textposition | "inside","outside","auto" | Data label position |
3. px.scatter() — Multi-Dimensional Interactive Scatter
🔍 Kya Hai: Plotly scatter mein hover karke har point ka complete data dikhta hai, lasso select se points select kar sakte hain, aur 6 dimensions tak ek chart mein dikhane ka power — x, y, color, size, symbol, facet.
💻 Professional Multi-Dimensional Version:
fig = px.scatter(employees, x="Experience", y="Salary",
color="Department", # color = department
size="Rating", # bubble size = rating
symbol="Gender", # marker shape = gender
hover_name="Name", # bold name on hover
hover_data={ # extra hover info
"Salary": "₹,.0f",
"Experience": ":.1f",
"Age": True,
"Rating": True
},
size_max=20, # maximum bubble size
opacity=0.7, # transparency
trendline="ols", # "ols"=linear regression, "lowess"=smooth
trendline_scope="overall", # "overall" or "trace"(per group)
marginal_x="histogram", # top marginal: "histogram","box","violin","rug"
marginal_y="box", # right marginal
labels={
"Experience": "Experience (Years)",
"Salary": "Salary (₹)"
},
title="Experience vs Salary (Color=Dept, Size=Rating, Shape=Gender)",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.Set2,
width=1000, height=650
)
fig.write_html("scatter_multi.html")
fig.show()
💻 Faceted Scatter — Department Panels:
fig = px.scatter(employees, x="Experience", y="Salary",
color="Gender",
facet_col="Department", # separate panel per department
facet_col_wrap=2, # 2 panels per row
trendline="ols",
opacity=0.6,
title="Salary vs Experience — Per Department",
template="plotly_white",
width=900, height=700
)
fig.write_html("scatter_faceted.html")
fig.show()
📋 px.scatter() Unique Parameters:
| Parameter | Values | Description |
|---|---|---|
trendline | "ols","lowess" | Automatic regression line — 1 line mein! |
marginal_x/y | "histogram","box","violin","rug" | Marginal distributions dikhana |
facet_col | column name | Separate panel per category |
size_max | 15, 20, 30 | Maximum bubble size |
animation_frame | column name | Animated scatter over time! 🎬 |
4. px.histogram() — Interactive Histogram
🔍 Kya Hai: Plotly histogram mein hover se bin range aur count dikhta hai, marginal distributions add ho sakte hain, aur overlay/stack modes mein groups compare ho sakte hain — sab interactive.
fig = px.histogram(employees, x="Salary",
color="Department",
nbins=30, # number of bins
barmode="overlay", # "overlay","stack","group","relative"
opacity=0.6, # transparency for overlay
marginal="box", # "box","violin","rug" on top
histnorm="", # "","percent","probability","density","probability density"
cumulative=False, # True = cumulative histogram
labels={"Salary": "Salary (₹)"},
title="Salary Distribution by Department",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.Set2,
width=900, height=550
)
fig.write_html("histogram.html")
fig.show()
# ===== 2D Histogram (Heatmap Style) =====
fig2 = px.density_heatmap(employees, x="Experience", y="Salary",
nbinsx=20, nbinsy=20,
color_continuous_scale="YlOrRd",
marginal_x="histogram",
marginal_y="histogram",
title="Experience vs Salary — 2D Density",
template="plotly_white"
)
fig2.write_html("density_heatmap.html")
fig2.show()
5. px.pie() — Interactive Pie & Donut Charts
🔍 Kya Hai: Plotly pie chart mein hover se exact value aur percentage dikhta hai, click se slice pull-out hota hai, aur hole parameter se donut chart banta hai — sab interactive aur animated.
dept_counts = employees["Department"].value_counts().reset_index()
dept_counts.columns = ["Department", "Count"]
# ===== PIE CHART =====
fig = px.pie(dept_counts, values="Count", names="Department",
title="Employee Distribution",
color_discrete_sequence=px.colors.qualitative.Set2,
hover_data=["Count"],
template="plotly_white",
width=700, height=500
)
fig.update_traces(
textposition="inside", # "inside","outside","auto","none"
textinfo="percent+label", # "label","percent","value","label+percent"
textfont_size=13,
pull=[0.05, 0, 0, 0], # explode first slice
marker_line_width=2,
marker_line_color="white",
rotation=90 # start angle
)
fig.write_html("pie_chart.html")
fig.show()
# ===== DONUT CHART =====
fig2 = px.pie(dept_counts, values="Count", names="Department",
hole=0.4, # donut hole size (0-1)
title="Employee Distribution (Donut)",
color_discrete_sequence=px.colors.qualitative.Pastel
)
fig2.update_traces(textinfo="percent+label")
# Center text in donut
fig2.add_annotation(text=f"Total
{dept_counts[0].sum()}",
font_size=18, showarrow=False)
fig2.write_html("donut_chart.html")
fig2.show()
6. px.box() — Interactive Box Plot
🔍 Kya Hai: Plotly box plot mein hover se Q1, median, Q3, whiskers exact values dikhte hain, individual outlier points par hover karke actual data dikhta hai, aur points="all" se har data point visible hota hai.
fig = px.box(employees, x="Department", y="Salary",
color="Gender",
points="outliers", # "all","outliers","suspectedoutliers",False
notched=True, # confidence interval notch
hover_data=["Name", "Experience"],
labels={"Salary": "Salary (₹)"},
title="Salary Distribution by Department & Gender",
template="plotly_white",
color_discrete_sequence=["#3498db", "#e74c3c"],
width=900, height=550
)
fig.update_traces(
marker_size=4, # outlier dot size
marker_opacity=0.5, # dot transparency
boxmean="sd" # True=show mean, "sd"=mean+std band
)
fig.write_html("boxplot.html")
fig.show()
7. px.violin() — Interactive Violin Plot
🔍 Kya Hai: Plotly violin mein hover se density values dikhte hain, box overlay built-in hai, aur points parameter se individual data points bhi dikh sakte hain — distribution shape + details ek chart mein.
fig = px.violin(employees, x="Department", y="Salary",
color="Gender",
box=True, # show box inside violin
points="all", # show all data points
hover_data=["Name", "Rating"],
violinmode="group", # "group" or "overlay"
labels={"Salary": "Salary (₹)"},
title="Salary Distribution Shape by Department",
template="plotly_white",
color_discrete_sequence=["#3498db", "#e74c3c"],
width=950, height=550
)
fig.update_traces(
meanline_visible=True, # show mean line
scalemode="count", # "width"=equal width, "count"=proportional
jitter=0.05, # point jitter amount
pointpos=-0.8 # points position relative to violin
)
fig.write_html("violin.html")
fig.show()
8. px.area() — Interactive Stacked Area Chart
🔍 Kya Hai: Plotly area chart mein hover se stacked values dikhte hain, zoom se specific time ranges explore kar sakte hain, aur legend toggle se specific categories on/off kar sakte hain — cumulative trend analysis interactive ho jaata hai.
fig = px.area(df, x="Month", y="Revenue",
color="Department",
line_group="Department",
groupnorm="", # "" = absolute, "percent" = 100% stacked
markers=True,
hover_data=["Employees"],
labels={"Revenue": "Revenue (₹)"},
title="Revenue Trend — Stacked Area",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.Set2,
width=900, height=500
)
fig.update_traces(
line_width=1.5,
marker_size=6
)
fig.write_html("area_chart.html")
fig.show()
# ===== 100% STACKED AREA (Percentage) =====
fig2 = px.area(df, x="Month", y="Revenue",
color="Department",
line_group="Department",
groupnorm="percent", # 100% stacked — shows composition %
title="Revenue Share % — 100% Stacked Area",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.Pastel
)
fig2.write_html("area_percent.html")
fig2.show()
📋 Plotly Express — Common Parameters (All Charts)
| Parameter | Type | Description |
|---|---|---|
data_frame | DataFrame | Source data |
x / y | column name | X aur Y axis data |
color | column name | Category-wise color split |
hover_name | column name | Bold title on hover tooltip |
hover_data | list / dict | Extra data in hover tooltip |
labels | dict | Axis/legend labels rename |
title | string | Chart title |
template | "plotly_white","plotly_dark","seaborn","ggplot2" | Chart theme |
color_discrete_sequence | list / px.colors.* | Custom color palette |
facet_col / facet_row | column name | Multi-panel faceted charts |
animation_frame | column name | Animated chart — play button! |
width / height | pixels | Figure size in pixels |
🎨 Available Templates (Themes)
# All available templates
import plotly.io as pio
print(pio.templates)
# Popular ones:
template = "plotly" # default — light blue bg
template = "plotly_white" # ✅ clean white (MOST POPULAR)
template = "plotly_dark" # dark mode
template = "seaborn" # seaborn style
template = "ggplot2" # R ggplot style
template = "simple_white" # minimal white
template = "presentation" # large fonts for slides
template = "xgridoff" # no x-grid
template = "ygridoff" # no y-grid
template = "gridon" # all grids on
# Set default template globally
pio.templates.default = "plotly_white"
# ===== COLOR PALETTES =====
px.colors.qualitative.Set1 # bold distinct
px.colors.qualitative.Set2 # pastel professional ✅
px.colors.qualitative.Pastel # light pastel
px.colors.qualitative.Dark2 # dark bold
px.colors.qualitative.Plotly # default plotly colors
px.colors.sequential.Viridis # sequential gradient
px.colors.diverging.RdBu # diverging
Quick Reference: Plotly vs Matplotlib vs Seaborn
| Feature | Matplotlib | Seaborn | Plotly |
|---|---|---|---|
| Interactive? | ❌ Static | ❌ Static | ✅ Hover, Zoom, Pan |
| Code complexity | High | Medium | Low (px = 1 line!) |
| Web export | PNG only | PNG only | ✅ HTML (interactive) |
| 3D Charts | Basic | ❌ No | ✅ Excellent |
| Maps | ❌ No | ❌ No | ✅ Built-in (choropleth, geo) |
| Animation | Complex | ❌ No | ✅ animation_frame param |
| Dashboard | subplots | FacetGrid | ✅ Dash framework |
| Best for | Research papers | Statistical EDA | Dashboards, Web apps |
Next Post: Part 2
Next part mein hum cover karenge: Advanced Plotly Charts — 3D Scatter, Sunburst, Treemap, Funnel, Geographic Maps, aur Graph Objects ke saath complete dashboard creation.
Happy Interactive Visualizing! 📊🚀
💬 Comments (0)
Loading comments...