Advanced Charts, Graph Objects And Export in Plotly
Advanced Charts, Graph Objects & Export in Plotly: Complete Guide
3D plots, Geographic maps, Sunbursts, Treemaps, Funnels — aur Graph Objects se pixel-level control. Plus complete styling, layout customization aur export guide — sab ek final masterclass mein.
📑 Is Guide Mein 3 Sections Cover Honge:
- Section A — Advanced PX Charts: 3D Scatter, 3D Line, Sunburst, Treemap, Funnel, Choropleth, Scatter Geo
- Section B — Graph Objects: go.Figure, go.Scatter, go.Bar, go.Heatmap, make_subplots
- Section C — Styling & Export: update_layout, update_traces, Templates, HTML/Image export
Section A — Advanced Plotly Express Charts
1. px.scatter_3d() — 3D Interactive Scatter Plot
🔍 Kya Hai: 3D scatter plot mein mouse se rotate, zoom, pan kar sakte hain — 3 continuous variables ka relationship ek interactive 3D space mein dikhta hai. Color aur size se 5 dimensions tak visualize ho sakte hain.
fig = px.scatter_3d(employees,
x="Experience", # x-axis
y="Age", # y-axis
z="Salary", # z-axis (vertical)
color="Department", # 4th dimension — color
size="Rating", # 5th dimension — bubble size
symbol="Gender", # 6th dimension — marker shape
hover_name="Name",
hover_data={"Salary": "₹,.0f"},
size_max=15,
opacity=0.7,
labels={
"Experience": "Exp (Years)",
"Salary": "Salary (₹)",
"Age": "Age (Years)"
},
title="3D: Experience × Age × Salary",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.Set2,
width=900, height=700
)
fig.update_layout(
scene=dict( # 3D scene settings
xaxis_title="Experience",
yaxis_title="Age",
zaxis_title="Salary",
camera=dict(eye=dict(x=1.5, y=1.5, z=0.8)) # initial camera angle
)
)
fig.write_html("scatter_3d.html")
fig.show()
2. px.line_3d() — 3D Line Chart
🔍 Kya Hai: 3D line chart trajectories dikhata hai — time series ko 3D space mein trace karna, spiral paths, aur multi-variable trends ke liye.
# Spiral 3D Line
t = np.linspace(0, 10, 200)
spiral = pd.DataFrame({
"X": np.cos(t * 2) * t,
"Y": np.sin(t * 2) * t,
"Z": t,
"Time": t
})
fig = px.line_3d(spiral, x="X", y="Y", z="Z",
color="Time", # color gradient over time
title="3D Spiral Trajectory",
template="plotly_dark",
width=800, height=600
)
fig.write_html("line_3d.html")
fig.show()
3. px.sunburst() — Hierarchical Sunburst Chart
🔍 Kya Hai: Sunburst chart nested pie chart jaisa hai — center se bahar ki taraf hierarchy dikhti hai. Company → Department → Gender → Rating jaisi multi-level breakdowns ke liye perfect. Click karke drill-down ho jaata hai!
fig = px.sunburst(employees,
path=["Department", "Gender", "Rating"], # hierarchy levels (inside → outside)
values="Salary", # size of each segment
color="Department", # color by top level
hover_data={"Salary": "₹,.0f"},
title="Company Hierarchy — Sunburst",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.Set2,
width=750, height=750
)
fig.update_traces(
textinfo="label+percent parent", # show label + % of parent
insidetextorientation="radial" # "horizontal","radial","tangential","auto"
)
fig.write_html("sunburst.html")
fig.show()
4. px.treemap() — Hierarchical Treemap
🔍 Kya Hai: Treemap nested rectangles se hierarchy dikhata hai — bada rectangle = badi value. Sunburst jaisa hi hai lekin rectangular layout mein. Space utilization better hai aur large hierarchies mein zyada readable hai.
fig = px.treemap(employees,
path=[px.Constant("Company"), "Department", "Gender"], # px.Constant = root label
values="Salary",
color="Salary", # color by salary (continuous)
color_continuous_scale="RdYlGn", # gradient colorscale
color_continuous_midpoint=employees["Salary"].mean(),
hover_data={"Salary": "₹,.0f"},
title="Company Salary Structure — Treemap",
template="plotly_white",
width=900, height=600
)
fig.update_traces(
textinfo="label+value+percent parent",
textfont_size=12
)
fig.write_html("treemap.html")
fig.show()
5. px.funnel() — Sales/Conversion Funnel
🔍 Kya Hai: Funnel chart step-by-step conversion/drop-off dikhata hai — website visitors → sign-ups → purchases jaisi pipeline. Har stage par kitne log drop hue clearly dikhta hai.
funnel_data = pd.DataFrame({
"Stage": ["Website Visits", "Product Views", "Add to Cart",
"Checkout", "Payment", "Delivered"],
"Count": [15000, 8500, 4200, 2800, 2100, 1950]
})
fig = px.funnel(funnel_data, x="Count", y="Stage",
text="Count", # data labels
title="E-Commerce Sales Funnel",
template="plotly_white",
color_discrete_sequence=px.colors.sequential.Blues_r,
width=800, height=500
)
fig.update_traces(textinfo="value+percent initial")
fig.write_html("funnel.html")
fig.show()
# ===== FUNNEL AREA (Smooth) =====
fig2 = px.funnel_area(funnel_data, names="Stage", values="Count",
title="Funnel Area — Smooth Version",
color_discrete_sequence=px.colors.sequential.Sunset
)
fig2.write_html("funnel_area.html")
fig2.show()
6. px.choropleth() — Geographic Heatmap (World Map)
🔍 Kya Hai: Choropleth map countries/regions ko values ke basis par color-code karta hai — GDP, population, sales by region jaise geographic data visualization ke liye. Hover se country-wise details dikhte hain, zoom aur pan support hai.
# Using built-in Plotly dataset
gapminder = px.data.gapminder()
latest = gapminder[gapminder["year"] == 2007]
fig = px.choropleth(latest,
locations="iso_alpha", # country ISO codes
color="gdpPercap", # color by GDP per capita
hover_name="country", # country name on hover
hover_data={"pop": ",.0f", "lifeExp": ":.1f"},
color_continuous_scale="Viridis", # colorscale
projection="natural earth", # map projection
title="World GDP Per Capita (2007)",
labels={"gdpPercap": "GDP/Capita ($)"},
template="plotly_white",
width=1000, height=550
)
fig.write_html("choropleth.html")
fig.show()
# ===== ANIMATED MAP (Over Years!) =====
fig2 = px.choropleth(gapminder,
locations="iso_alpha",
color="gdpPercap",
hover_name="country",
animation_frame="year", # ANIMATED over years! 🎬
color_continuous_scale="Viridis",
projection="natural earth",
title="GDP Growth Animation (1952-2007)",
range_color=[0, 50000]
)
fig2.write_html("choropleth_animated.html")
fig2.show()
7. px.scatter_geo() — Geographic Scatter (Dots on Map)
🔍 Kya Hai: Scatter geo map par dots plot karta hai — har dot ek city/location represent karta hai. Dot ka size aur color variables se map hota hai. Office locations, customer distribution, event locations visualize karne ke liye.
fig = px.scatter_geo(latest,
locations="iso_alpha",
color="continent",
size="pop", # bubble size = population
hover_name="country",
hover_data={"pop": ",.0f", "gdpPercap": "$,.0f"},
size_max=40,
projection="natural earth",
title="World Population by Country (Bubble Map)",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.Set2,
width=1000, height=550
)
fig.write_html("scatter_geo.html")
fig.show()
Section B — Graph Objects (Advanced Control)
8. go.Figure() + go.Scatter() — Full Control Line/Scatter
🔍 Kya Hai: Graph Objects (go) Plotly ka low-level API hai — px se zyada verbose lekin pixel-level control milta hai. Multiple traces (lines/bars/areas) ek figure mein manually add kar sakte hain. Complex dashboards aur custom charts ke liye essential.
import plotly.graph_objects as go
months = ["Jan","Feb","Mar","Apr","May","Jun"]
revenue_2023 = [45,52,48,61,55,67]
revenue_2024 = [50,58,53,69,62,75]
fig = go.Figure()
# Trace 1: 2023 Line
fig.add_trace(go.Scatter(
x=months, y=revenue_2023,
name="2023",
mode="lines+markers", # "lines","markers","lines+markers","text"
line=dict(color="#3498db", width=3, dash="solid"), # "solid","dash","dot","dashdot"
marker=dict(size=10, symbol="circle",
line=dict(width=2, color="white")),
hovertemplate="Month: %{x}<br>Revenue: ₹%{y}K<extra></extra>",
fill="none" # "none","tozeroy","tonexty","toself"
))
# Trace 2: 2024 Line with fill
fig.add_trace(go.Scatter(
x=months, y=revenue_2024,
name="2024",
mode="lines+markers",
line=dict(color="#e74c3c", width=3, dash="dash"),
marker=dict(size=10, symbol="diamond"),
fill="tonexty", # fill area between this and previous trace
fillcolor="rgba(231,76,60,0.1)"
))
# Reference line
fig.add_hline(y=60, line_dash="dot", line_color="gray",
annotation_text="Target: ₹60K", annotation_position="top right")
fig.update_layout(
title="Revenue Comparison: 2023 vs 2024",
template="plotly_white",
hovermode="x unified",
width=900, height=500
)
fig.write_html("go_scatter.html")
fig.show()
9. go.Bar() — Advanced Bar with Multiple Traces
departments = ["IT","HR","Finance","Marketing"]
salary_2023 = [78,52,70,58]
salary_2024 = [85,58,76,64]
fig = go.Figure()
fig.add_trace(go.Bar(
name="2023", x=departments, y=salary_2023,
marker_color="#3498db",
marker_line=dict(width=1.5, color="white"),
text=[f"₹{v}K" for v in salary_2023],
textposition="outside",
textfont_size=12,
opacity=0.85,
hovertemplate="%{x}: ₹%{y}K<extra>2023</extra>"
))
fig.add_trace(go.Bar(
name="2024", x=departments, y=salary_2024,
marker_color="#2ecc71",
marker_line=dict(width=1.5, color="white"),
text=[f"₹{v}K" for v in salary_2024],
textposition="outside",
textfont_size=12,
opacity=0.85
))
fig.update_layout(
barmode="group",
title="Salary Comparison: 2023 vs 2024",
template="plotly_white",
bargap=0.2, # gap between groups
bargroupgap=0.1, # gap within group
width=800, height=500
)
fig.write_html("go_bar.html")
fig.show()
10. go.Heatmap() — Interactive Heatmap
# Correlation heatmap
corr = employees.select_dtypes(include=["number"]).corr().round(2)
fig = go.Figure(go.Heatmap(
z=corr.values,
x=corr.columns,
y=corr.columns,
colorscale="RdBu_r", # diverging colorscale
zmid=0, # center value
zmin=-1, zmax=1,
text=corr.values, # show values in cells
texttemplate="%{text:.2f}", # format
textfont_size=12,
hovertemplate="%{x} vs %{y}: %{z:.3f}<extra></extra>",
colorbar=dict(title="Correlation", thickness=15)
))
fig.update_layout(
title="Interactive Correlation Heatmap",
template="plotly_white",
width=700, height=600
)
fig.write_html("heatmap_plotly.html")
fig.show()
11. make_subplots() — Interactive Dashboard
🔍 Kya Hai: make_subplots() se multiple interactive charts ek figure mein arrange hote hain — har chart independently hover, zoom, pan support karta hai. Production dashboards ka foundation.
from plotly.subplots import make_subplots
fig = make_subplots(
rows=2, cols=2,
subplot_titles=("Revenue Trend", "Department Split",
"Salary Distribution", "Experience vs Salary"),
specs=[[{"type": "scatter"}, {"type": "pie"}],
[{"type": "histogram"}, {"type": "scatter"}]],
vertical_spacing=0.12,
horizontal_spacing=0.1
)
# Chart 1: Line
fig.add_trace(go.Scatter(
x=months, y=revenue_2024, mode="lines+markers",
line=dict(color="#3498db", width=3),
marker=dict(size=8), name="Revenue"
), row=1, col=1)
# Chart 2: Pie
dept_counts = employees["Department"].value_counts()
fig.add_trace(go.Pie(
labels=dept_counts.index, values=dept_counts.values,
hole=0.4, marker_colors=px.colors.qualitative.Set2
), row=1, col=2)
# Chart 3: Histogram
fig.add_trace(go.Histogram(
x=employees["Salary"], nbinsx=25,
marker_color="#9b59b6", opacity=0.7, name="Salary"
), row=2, col=1)
# Chart 4: Scatter
fig.add_trace(go.Scatter(
x=employees["Experience"], y=employees["Salary"],
mode="markers", marker=dict(size=4, color="#e74c3c", opacity=0.4),
name="Exp vs Sal"
), row=2, col=2)
fig.update_layout(
title_text="🏢 Company Analytics Dashboard",
title_font_size=22,
showlegend=False,
template="plotly_white",
height=800, width=1100
)
fig.write_html("dashboard_plotly.html")
fig.show()
Section C — Styling, Layout & Export
12. fig.update_layout() — Complete Layout Control
fig.update_layout(
# ===== TITLE =====
title=dict(
text="Revenue Analysis",
font=dict(size=22, family="Arial", color="#2c3e50"),
x=0.5, # center title (0=left, 0.5=center, 1=right)
y=0.95
),
# ===== AXES =====
xaxis=dict(
title="Month",
title_font_size=14,
tickfont_size=12,
showgrid=True,
gridcolor="#ecf0f1",
gridwidth=0.5,
showline=True,
linecolor="#bdc3c7",
tickangle=-45, # rotate tick labels
range=[0, 100] # axis limits
),
yaxis=dict(
title="Revenue (₹)",
title_font_size=14,
showgrid=True,
gridcolor="#ecf0f1",
zeroline=True,
zerolinecolor="#bdc3c7"
),
# ===== LEGEND =====
legend=dict(
title="Year",
font_size=12,
bgcolor="rgba(255,255,255,0.8)",
bordercolor="#bdc3c7",
borderwidth=1,
x=1.02, y=1, # position
orientation="v" # "v"=vertical, "h"=horizontal
),
# ===== BACKGROUND =====
plot_bgcolor="white", # plot area background
paper_bgcolor="#f8fafc", # entire figure background
# ===== HOVER =====
hovermode="x unified", # "x","y","closest","x unified","y unified"
hoverlabel=dict(
bgcolor="white",
font_size=12,
font_family="Arial"
),
# ===== MARGINS =====
margin=dict(l=60, r=30, t=80, b=60),
# ===== SIZE =====
width=900, height=500,
# ===== TEMPLATE =====
template="plotly_white"
)
13. fig.update_traces() — Trace-Level Styling
# ===== LINE TRACES =====
fig.update_traces(
line_width=3,
line_color="#3498db",
line_dash="solid", # "solid","dash","dot","dashdot","longdash"
marker_size=10,
marker_symbol="circle", # "circle","square","diamond","cross","star","triangle-up"
opacity=0.85,
selector=dict(type="scatter") # apply only to scatter traces
)
# ===== BAR TRACES =====
fig.update_traces(
marker_color="#2ecc71",
marker_line_width=1.5,
marker_line_color="white",
textposition="outside",
textfont_size=12,
selector=dict(type="bar")
)
# ===== PIE TRACES =====
fig.update_traces(
textinfo="percent+label",
textfont_size=13,
pull=[0.05, 0, 0, 0],
marker_line_width=2,
marker_line_color="white",
selector=dict(type="pie")
)
# ===== CUSTOM HOVERTEMPLATE =====
fig.update_traces(
hovertemplate=(
"<b>%{x}</b><br>"
"Revenue: ₹%{y:,.0f}<br>"
"<extra></extra>" # removes trace name box
)
)
14. Annotations, Shapes & Reference Lines
# ===== REFERENCE LINES (Shortcut) =====
fig.add_hline(y=50, line_dash="dash", line_color="red", line_width=1.5,
annotation_text="Target", annotation_position="top left")
fig.add_vline(x="Mar", line_dash="dot", line_color="gray")
fig.add_hrect(y0=45, y1=55, fillcolor="red", opacity=0.1, line_width=0) # shaded region
# ===== ANNOTATION (Arrow + Text) =====
fig.add_annotation(
x="Jun", y=75, # arrow points here
text="Peak Month! 🎉",
showarrow=True,
arrowhead=2, # arrowhead style (0-8)
arrowsize=1.5,
arrowwidth=2,
arrowcolor="#e74c3c",
ax=-60, ay=-40, # arrow offset (text position relative)
font=dict(size=14, color="#e74c3c"),
bgcolor="#fadbd8",
bordercolor="#e74c3c",
borderwidth=1,
borderpad=4
)
# ===== SHAPE (Rectangle, Circle, Line) =====
fig.add_shape(
type="rect", # "rect","circle","line","path"
x0="Apr", x1="Jun", y0=60, y1=80,
fillcolor="rgba(52,152,219,0.1)",
line=dict(color="#3498db", dash="dash")
)
15. Export — HTML, PNG, JPG, SVG, PDF
# ===== INTERACTIVE HTML (Best for web/sharing) =====
fig.write_html("chart.html",
include_plotlyjs=True, # embed plotly.js (standalone file)
full_html=True, # complete HTML document
auto_open=False # don't auto-open in browser
)
# Smaller file — CDN link instead of embedding
fig.write_html("chart_cdn.html", include_plotlyjs="cdn")
# ===== STATIC IMAGES (Requires kaleido) =====
# pip install kaleido
fig.write_image("chart.png", scale=2) # PNG (scale=2 for retina)
fig.write_image("chart.jpg", quality=95) # JPG with quality
fig.write_image("chart.svg") # SVG (vector — scalable)
fig.write_image("chart.pdf") # PDF (print quality)
# Custom size for export
fig.write_image("chart_large.png", width=1920, height=1080, scale=2)
# ===== DISPLAY OPTIONS =====
fig.show() # Jupyter notebook
fig.show(renderer="browser") # open in browser
fig.show(renderer="png") # static PNG in notebook
fig.show(renderer="svg") # static SVG in notebook
# Set default renderer
import plotly.io as pio
pio.renderers.default = "notebook" # Jupyter
pio.renderers.default = "browser" # External browser
📋 Export Format Comparison:
| Format | Interactive? | Best For | Requires |
|---|---|---|---|
.html | ✅ Yes | Web, sharing, dashboards | Nothing extra |
.png | ❌ Static | Blog, reports | kaleido |
.svg | ❌ Static | Presentations (scalable) | kaleido |
.pdf | ❌ Static | Print, papers | kaleido |
Master Reference: Complete Plotly Function Guide
| Category | Function | Purpose |
|---|---|---|
| Basic PX | px.line/bar/scatter | Core interactive charts |
px.histogram/box/violin | Distribution charts | |
px.pie/area | Composition charts | |
px.density_heatmap | 2D density | |
| Advanced PX | px.scatter_3d/line_3d | 3D interactive plots |
px.sunburst/treemap/funnel | Hierarchical & pipeline | |
px.choropleth/scatter_geo | Geographic maps | |
| Graph Objects | go.Figure + go.Scatter/Bar | Custom multi-trace charts |
go.Heatmap | Interactive heatmap | |
make_subplots | Multi-chart dashboard | |
| Styling | update_layout() | Global figure styling |
update_traces() | Individual trace styling | |
add_annotation/hline/shape | Annotations & references | |
| Export | write_html() | Interactive HTML export |
write_image() | Static PNG/SVG/PDF |
🎉 Plotly Masterclass Complete!
Congratulations! Aapne 2 comprehensive parts mein 25+ Plotly functions cover kiye hain — Basic interactive charts se lekar 3D plots, Geographic maps, Graph Objects, Dashboards aur Export tak. Ab aap production-grade interactive visualizations confidently create kar sakte hain.
Happy Interactive Visualizing! 📊🚀
💬 Comments (0)
Loading comments...