Advanced Charts, Dashboards And Export in Matplotlib
Advanced Charts, Dashboards & Export in Matplotlib: Complete Guide
Basic charts se aage badhein — Heatmaps, Violin Plots, Dual Axis, Grouped Bars, Waterfall Charts aur production-ready dashboards banana sikhein. Plus complete save & export guide.
📑 Is Guide Mein Cover Hoga:
- Advanced Charts: Heatmap, Violin, Error Bars, Step, Hexbin, Contour
- Dashboard Patterns: Dual Axis, Grouped Bar, Stacked Bar, Waterfall
- Save & Export: PNG, JPG, SVG, PDF — DPI, transparency, bbox control
Advanced Chart Types
1. Heatmap — Color-Coded Matrix
🔍 Kya Hai: Heatmap 2D matrix ko color gradient se visualize karta hai — correlation matrix, confusion matrix, aur time-based patterns dikhane ke liye essential hai.
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# ===== METHOD 1: Pure Matplotlib — plt.imshow() =====
data = np.random.rand(5, 7)
row_labels = ["IT", "HR", "Finance", "Marketing", "Ops"]
col_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
fig, ax = plt.subplots(figsize=(10, 6))
im = ax.imshow(data,
cmap="YlOrRd", # colormap
aspect="auto", # "auto","equal" or number
interpolation="nearest" # no smoothing
)
# Add text annotations in each cell
for i in range(len(row_labels)):
for j in range(len(col_labels)):
ax.text(j, i, f"{data[i,j]:.2f}",
ha="center", va="center",
color="white" if data[i,j] > 0.5 else "black",
fontsize=10, fontweight="bold")
ax.set_xticks(range(len(col_labels)))
ax.set_xticklabels(col_labels)
ax.set_yticks(range(len(row_labels)))
ax.set_yticklabels(row_labels)
plt.colorbar(im, ax=ax, shrink=0.8, label="Intensity")
ax.set_title("Activity Heatmap (imshow)", fontsize=15, fontweight="bold")
plt.savefig("heatmap_imshow.png", dpi=150, bbox_inches="tight")
plt.show()
# ===== METHOD 2: Seaborn Heatmap (Easier & Better) =====
import pandas as pd
df = pd.DataFrame(data, index=row_labels, columns=col_labels)
fig, ax = plt.subplots(figsize=(10, 6))
sns.heatmap(df,
annot=True, # show values in cells
fmt=".2f", # number format
cmap="RdBu_r", # diverging colormap
center=0.5, # center value for diverging
vmin=0, vmax=1, # value range
linewidths=0.5, # cell border width
linecolor="white", # cell border color
square=False, # square cells
cbar_kws={"shrink": 0.8, "label": "Score"},
annot_kws={"size": 11, "weight": "bold"},
ax=ax
)
ax.set_title("Activity Heatmap (Seaborn)", fontsize=15, fontweight="bold", pad=15)
plt.savefig("heatmap_seaborn.png", dpi=150, bbox_inches="tight")
plt.show()
2. Violin Plot — Distribution Shape + Box Plot Combined
🔍 Kya Hai: Violin plot box plot + kernel density estimation combine karta hai — distribution ka actual shape dikhta hai, sirf summary statistics nahi. Bimodal distributions violin mein clearly dikhte hain jo box plot miss karta hai.
np.random.seed(42)
it_salary = np.random.normal(82000, 15000, 300)
hr_salary = np.random.normal(55000, 10000, 300)
fin_salary = np.concatenate([
np.random.normal(50000, 5000, 150),
np.random.normal(90000, 5000, 150) # Bimodal!
])
data = [it_salary, hr_salary, fin_salary]
labels = ["IT", "HR", "Finance\n(Bimodal)"]
# ===== Matplotlib Violin =====
fig, ax = plt.subplots(figsize=(10, 6))
vp = ax.violinplot(data,
showmeans=True, # show mean line
showmedians=True, # show median line
showextrema=True, # show min/max lines
quantiles=[[0.25, 0.75]] * 3 # Q1/Q3 lines
)
# Color each violin
colors = ["#3498db", "#2ecc71", "#e74c3c"]
for body, color in zip(vp["bodies"], colors):
body.set_facecolor(color)
body.set_alpha(0.7)
body.set_edgecolor("#2c3e50")
ax.set_xticks([1, 2, 3])
ax.set_xticklabels(labels, fontsize=12)
ax.set_title("Salary Distribution — Violin Plot", fontsize=15, fontweight="bold")
ax.set_ylabel("Salary (₹)", fontsize=12)
ax.grid(axis="y", linestyle="--", alpha=0.3)
plt.savefig("violin_plot.png", dpi=150, bbox_inches="tight")
plt.show()
3. plt.errorbar() — Error Bars (Uncertainty Visualization)
🔍 Kya Hai: Error bars data mein uncertainty/variability dikhate hain — mean ke saath standard deviation ya confidence interval represent karte hain. Scientific papers aur research reports mein mandatory hai.
departments = ["IT", "HR", "Finance", "Marketing"]
means = [82500, 55800, 75200, 62400]
std_devs = [15000, 10000, 12000, 18000]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))
# ===== Line Chart with Error Bars =====
ax1.errorbar(departments, means, yerr=std_devs,
fmt="o-", # format string (marker + line)
color="#3498db",
linewidth=2,
markersize=8,
capsize=8, # error bar cap width
capthick=2, # cap line thickness
ecolor="#e74c3c", # error bar color
elinewidth=1.5, # error bar line width
alpha=0.9
)
ax1.set_title("Line + Error Bars", fontsize=14, fontweight="bold")
ax1.set_ylabel("Salary (₹)")
ax1.grid(axis="y", linestyle="--", alpha=0.3)
# ===== Bar Chart with Error Bars =====
ax2.bar(departments, means,
yerr=std_devs, # error bars on bars
color="#2ecc71",
width=0.6,
edgecolor="#27ae60",
capsize=6,
error_kw={"ecolor": "#2c3e50", "elinewidth": 1.5, "capthick": 1.5}
)
ax2.set_title("Bar + Error Bars", fontsize=14, fontweight="bold")
ax2.set_ylabel("Salary (₹)")
plt.tight_layout()
plt.savefig("error_bars.png", dpi=150, bbox_inches="tight")
plt.show()
4. plt.step() — Step Chart (Discrete Changes)
🔍 Kya Hai: Step chart abrupt/discrete changes dikhata hai — jahan value ek level par rehti hai phir suddenly change hoti hai. Pricing changes, inventory levels, aur status updates ke liye perfect hai.
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"]
price = [999, 999, 1099, 1099, 1099, 1199, 1199, 1299]
fig, ax = plt.subplots(figsize=(10, 6))
ax.step(months, price,
where="mid", # "pre","post","mid" — step position
color="#e74c3c",
linewidth=2.5,
marker="o",
markersize=8,
markerfacecolor="white",
markeredgecolor="#e74c3c",
markeredgewidth=2,
label="Price"
)
# Annotate price changes
for i in range(1, len(price)):
if price[i] != price[i-1]:
ax.annotate(f"+₹{price[i]-price[i-1]}",
xy=(i, price[i]), xytext=(i, price[i]+40),
fontsize=10, color="#e74c3c", fontweight="bold",
ha="center")
ax.set_title("Product Price Changes (Step Chart)", fontsize=15, fontweight="bold")
ax.set_ylabel("Price (₹)", fontsize=12)
ax.grid(axis="y", linestyle="--", alpha=0.3)
ax.legend()
plt.savefig("step_chart.png", dpi=150, bbox_inches="tight")
plt.show()
5. plt.hexbin() — Hexagonal Density Plot
🔍 Kya Hai: Hexbin scatter plot ka density version hai — jab lakho data points hain tab regular scatter unreadable ho jaata hai. Hexbin hexagonal bins mein count karke density dikhata hai — dense areas dark, sparse areas light.
np.random.seed(42)
x = np.random.normal(50, 15, 10000)
y = x * 1.5 + np.random.normal(0, 20, 10000)
fig, ax = plt.subplots(figsize=(10, 7))
hb = ax.hexbin(x, y,
gridsize=30, # hexagon grid resolution
cmap="YlOrRd", # colormap
mincnt=1, # minimum count to show hex
edgecolors="white", # hex border
linewidths=0.2, # border thickness
alpha=0.9
)
plt.colorbar(hb, ax=ax, shrink=0.8, label="Count")
ax.set_title("Density Plot — 10K Points (Hexbin)", fontsize=15, fontweight="bold")
ax.set_xlabel("Experience", fontsize=12)
ax.set_ylabel("Salary", fontsize=12)
plt.savefig("hexbin.png", dpi=150, bbox_inches="tight")
plt.show()
Dashboard Patterns
6. Dual Axis Chart — Two Y-Axes One Plot
🔍 Kya Hai: Dual axis chart ek hi x-axis par do different scale wale variables dikhata hai — jaise Revenue (₹ lakhs) aur Orders (count) ek hi time axis par. ax.twinx() se doosra y-axis create hota hai.
months = ["Jan","Feb","Mar","Apr","May","Jun"]
revenue = [45, 52, 48, 61, 55, 67]
orders = [1200, 1350, 1100, 1500, 1400, 1650]
fig, ax1 = plt.subplots(figsize=(10, 6))
# LEFT Y-AXIS — Bar chart (Revenue)
bars = ax1.bar(months, revenue, color="#3498db", width=0.5, alpha=0.7, label="Revenue (₹L)", zorder=2)
ax1.set_ylabel("Revenue (₹ Lakhs)", fontsize=12, color="#3498db")
ax1.tick_params(axis="y", labelcolor="#3498db")
# RIGHT Y-AXIS — Line chart (Orders)
ax2 = ax1.twinx() # create second y-axis sharing x-axis
ax2.plot(months, orders, "o-", color="#e74c3c", linewidth=2.5, markersize=8,
markerfacecolor="white", markeredgewidth=2, label="Orders", zorder=3)
ax2.set_ylabel("Number of Orders", fontsize=12, color="#e74c3c")
ax2.tick_params(axis="y", labelcolor="#e74c3c")
# Combined legend
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc="upper left", fontsize=11)
ax1.set_title("Revenue vs Orders (Dual Axis)", fontsize=16, fontweight="bold")
ax1.grid(axis="y", linestyle="--", alpha=0.3)
plt.savefig("dual_axis.png", dpi=150, bbox_inches="tight")
plt.show()
7. Grouped Bar Chart — Side-by-Side Comparison
🔍 Kya Hai: Grouped bar chart multiple categories ko side-by-side compare karta hai — Year-over-Year comparison, A/B test results, aur multi-metric comparison ke liye standard hai.
departments = ["IT", "HR", "Finance", "Marketing"]
salary_2023 = [78000, 52000, 70000, 58000]
salary_2024 = [85000, 58000, 76000, 64000]
x = np.arange(len(departments))
width = 0.35 # bar width
fig, ax = plt.subplots(figsize=(10, 6))
bars1 = ax.bar(x - width/2, salary_2023, width,
label="2023", color="#3498db", edgecolor="white")
bars2 = ax.bar(x + width/2, salary_2024, width,
label="2024", color="#2ecc71", edgecolor="white")
# Data labels on both groups
ax.bar_label(bars1, labels=[f"₹{v//1000}K" for v in salary_2023], padding=3, fontsize=9)
ax.bar_label(bars2, labels=[f"₹{v//1000}K" for v in salary_2024], padding=3, fontsize=9)
ax.set_xticks(x)
ax.set_xticklabels(departments, fontsize=11)
ax.set_title("Salary Comparison: 2023 vs 2024", fontsize=15, fontweight="bold")
ax.set_ylabel("Average Salary (₹)")
ax.legend(fontsize=11)
ax.grid(axis="y", linestyle="--", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.savefig("grouped_bar.png", dpi=150, bbox_inches="tight")
plt.show()
8. Stacked Bar Chart — Composition Breakdown
🔍 Kya Hai: Stacked bars components ko ek upar ek dikhate hain — total aur breakdown dono ek chart mein. Revenue by product category per month — iske liye ideal hai.
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
electronics = [30, 35, 28, 42, 38, 45]
fashion = [20, 22, 25, 28, 30, 35]
grocery = [15, 16, 14, 18, 17, 20]
fig, ax = plt.subplots(figsize=(10, 6))
# Stack using bottom parameter
ax.bar(months, electronics, label="Electronics", color="#3498db", width=0.6)
ax.bar(months, fashion, bottom=electronics, label="Fashion", color="#e74c3c", width=0.6)
bottom_grocery = [e + f for e, f in zip(electronics, fashion)]
ax.bar(months, grocery, bottom=bottom_grocery, label="Grocery", color="#2ecc71", width=0.6)
# Total labels on top
totals = [e+f+g for e,f,g in zip(electronics, fashion, grocery)]
for i, total in enumerate(totals):
ax.text(i, total + 1, f"₹{total}K", ha="center", fontweight="bold", fontsize=10)
ax.set_title("Revenue Breakdown by Category (Stacked)", fontsize=15, fontweight="bold")
ax.set_ylabel("Revenue (₹K)")
ax.legend(loc="upper left")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.savefig("stacked_bar.png", dpi=150, bbox_inches="tight")
plt.show()
9. Waterfall Chart — Incremental Changes
🔍 Kya Hai: Waterfall chart step-by-step incremental changes dikhata hai — starting value se ending value tak kaise pahunche. Financial P&L statements, budget analysis, aur funnel breakdowns ke liye perfect hai.
categories = ["Revenue", "COGS", "Gross\nProfit", "OpEx", "Marketing", "Tax", "Net\nProfit"]
values = [100, -40, 60, -15, -10, -8, 27]
is_total = [True, False, True, False, False, False, True]
# Calculate running total and bottoms
running = 0
bottoms = []
bar_values = []
for i, (val, total) in enumerate(zip(values, is_total)):
if total:
bottoms.append(0)
bar_values.append(val)
running = val
else:
if val >= 0:
bottoms.append(running)
else:
bottoms.append(running + val)
bar_values.append(abs(val))
running += val
colors = []
for val, total in zip(values, is_total):
if total:
colors.append("#3498db") # blue for totals
elif val >= 0:
colors.append("#2ecc71") # green for positive
else:
colors.append("#e74c3c") # red for negative
fig, ax = plt.subplots(figsize=(12, 6))
bars = ax.bar(categories, bar_values, bottom=bottoms, color=colors,
width=0.6, edgecolor="white", linewidth=1.5)
# Value labels
for i, (bar, val) in enumerate(zip(bars, values)):
y_pos = bottoms[i] + bar_values[i] / 2
prefix = "+" if val > 0 and not is_total[i]
else ""
ax.text(i, y_pos, f"{prefix}₹{val}L",
ha="center", va="center", fontsize=11, fontweight="bold", color="white")
# Connector lines
for i in range(len(categories) - 1):
if not is_total[i+1]:
y = bottoms[i] + bar_values[i]
ax.plot([i+0.3, i+0.7], [y, y], color="#7f8c8d", linewidth=1, linestyle="--")
ax.set_title("P&L Waterfall Chart", fontsize=16, fontweight="bold")
ax.set_ylabel("Amount (₹ Lakhs)", fontsize=12)
ax.axhline(y=0, color="black", linewidth=0.8)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.savefig("waterfall.png", dpi=150, bbox_inches="tight")
plt.show()
Save & Export — Complete Guide
10. plt.savefig() — All Formats & Options
# ===== FORMAT OPTIONS =====
# PNG — Best for web/blog (raster, compressed)
plt.savefig("chart.png",
dpi=150, # resolution (72=web, 150=screen, 300=print)
bbox_inches="tight", # remove extra whitespace
facecolor="white", # background color
edgecolor="none", # border color
transparent=False, # transparent background
pad_inches=0.1 # padding around figure
)
# JPG — Smaller file, slight quality loss
plt.savefig("chart.jpg",
dpi=150,
bbox_inches="tight",
quality=95 # JPG quality (1-100)
)
# SVG — Scalable vector (presentations, web)
plt.savefig("chart.svg",
bbox_inches="tight",
format="svg" # vector — infinite zoom, no pixelation
)
# PDF — Print & papers
plt.savefig("chart.pdf",
dpi=300,
bbox_inches="tight",
format="pdf" # vector + embedded fonts
)
# ===== TRANSPARENT BACKGROUND =====
plt.savefig("chart_transparent.png",
dpi=150,
bbox_inches="tight",
transparent=True # no background — overlay on any color!
)
# ===== SAVE BEFORE SHOW =====
# IMPORTANT: savefig() BEFORE plt.show()
# plt.show() clears figure, savefig after it = blank image!
plt.savefig("chart.png", dpi=150, bbox_inches="tight") # ✅ FIRST
plt.show() # ✅ SECOND
📋 Format Comparison:
| Format | Type | Best For | File Size |
|---|---|---|---|
.png | Raster | Blog, web, general use | Medium |
.jpg | Raster | Photos, quick share | Small |
.svg | Vector | Presentations, web | Varies |
.pdf | Vector | Print, research papers | Small-Medium |
11. Complete Production Dashboard — 4 Charts in 1
🔍 Kya Hai: Real-world dashboard jismein multiple charts ek figure mein professionally arranged hain — GridSpec se custom layout, consistent styling, aur production-ready export.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
# Data
months = ["Jan","Feb","Mar","Apr","May","Jun"]
revenue = [45,52,48,61,55,67]
departments = ["IT","HR","Finance","Mkt"]
emp_count = [3200,2400,2000,1500]
np.random.seed(42)
salaries = np.random.normal(65000,15000,500)
# Create dashboard
fig = plt.figure(figsize=(16, 10))
fig.patch.set_facecolor("#f8fafc")
gs = GridSpec(2, 3, figure=fig, hspace=0.35, wspace=0.3)
# Chart 1: Revenue Trend (wide)
ax1 = fig.add_subplot(gs[0, :2])
ax1.plot(months, revenue, "o-", color="#3498db", linewidth=2.5, markersize=8,
markerfacecolor="white", markeredgewidth=2)
ax1.fill_between(months, revenue, alpha=0.1, color="#3498db")
ax1.set_title("📈 Revenue Trend", fontsize=14, fontweight="bold")
ax1.set_ylabel("₹ Lakhs")
ax1.grid(axis="y", linestyle="--", alpha=0.3)
ax1.spines["top"].set_visible(False)
ax1.spines["right"].set_visible(False)
# Chart 2: Department Pie
ax2 = fig.add_subplot(gs[0, 2])
colors_pie = ["#3498db","#2ecc71","#e74c3c","#f39c12"]
ax2.pie(emp_count, labels=departments, colors=colors_pie, autopct="%1.0f%%",
startangle=90, wedgeprops={"width":0.4, "edgecolor":"white"}, pctdistance=0.8)
ax2.set_title("👥 Department Split", fontsize=14, fontweight="bold")
# Chart 3: Salary Distribution
ax3 = fig.add_subplot(gs[1, 0])
ax3.hist(salaries, bins=20, color="#9b59b6", edgecolor="white", alpha=0.8)
ax3.axvline(np.mean(salaries), color="red", linestyle="--", linewidth=1.5)
ax3.set_title("💰 Salary Distribution", fontsize=14, fontweight="bold")
ax3.spines["top"].set_visible(False)
ax3.spines["right"].set_visible(False)
# Chart 4: Department Bar
ax4 = fig.add_subplot(gs[1, 1:])
bars = ax4.barh(departments, emp_count, color=colors_pie, height=0.5, edgecolor="white")
for bar, val in zip(bars, emp_count):
ax4.text(bar.get_width() + 50, bar.get_y() + bar.get_height()/2,
f"{val:,}", va="center", fontweight="bold")
ax4.set_title("📊 Employee Count", fontsize=14, fontweight="bold")
ax4.spines["top"].set_visible(False)
ax4.spines["right"].set_visible(False)
# Main title
fig.suptitle("🏢 Company Analytics Dashboard — Q2 2024",
fontsize=20, fontweight="bold", color="#2c3e50", y=1.02)
plt.savefig("dashboard.png", dpi=150, bbox_inches="tight", facecolor="#f8fafc")
plt.show()
Quick Reference: Advanced Charts Decision Guide
| Purpose | Chart Type | Function |
|---|---|---|
| 2D matrix visualization | Heatmap | sns.heatmap() / plt.imshow() |
| Distribution shape | Violin | plt.violinplot() |
| Uncertainty / variability | Error Bars | plt.errorbar() |
| Discrete jumps | Step Chart | plt.step() |
| Large data density | Hexbin | plt.hexbin() |
| Two scales, one axis | Dual Axis | ax.twinx() |
| Side-by-side comparison | Grouped Bar | ax.bar(x - width/2, ...) |
| Composition breakdown | Stacked Bar | ax.bar(..., bottom=prev) |
| Incremental changes | Waterfall | Custom bar + bottom logic |
| Multi-chart view | Dashboard | GridSpec + subplots |
🎉 Matplotlib Masterclass Complete!
Congratulations! Aapne 3 comprehensive parts mein 40+ chart types, styling options, aur dashboard patterns cover kiye hain. Ab aap professional-grade data visualizations confidently create kar sakte hain.
Happy Visualizing! 📊🚀
💬 Comments (0)
Loading comments...