Your First Chart
python
import matplotlib.pyplot as plt
months = ["Jan","Feb","Mar","Apr","May","Jun"]
sales = [45000,52000,48000,61000,58000,72000]
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(months, sales, marker="o", linewidth=2.5, color="#3b82f6", markersize=8)
ax.set_title("Monthly Sales 2024", fontsize=15, fontweight="bold", pad=15)
ax.set_xlabel("Month", fontsize=12)
ax.set_ylabel("Sales (EGP)", fontsize=12)
ax.grid(True, alpha=0.3, linestyle="--")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.savefig("sales_chart.png", dpi=150, bbox_inches="tight")
plt.show()
Figure Anatomy
python
# Figure = the whole canvas
# Axes = the plot area (can have multiple per figure)
# Axis = x-axis or y-axis
fig, ax = plt.subplots(figsize=(10,5))
# Annotations
ax.plot(months, sales, "bo-")
ax.annotate("Peak!", xy=(5,72000), xytext=(4,68000),
arrowprops=dict(arrowstyle="->",color="red"), color="red", fontsize=11)
# Add horizontal reference line
ax.axhline(y=sum(sales)/len(sales), color="orange",
linestyle="--", label=f"Avg: {sum(sales)/len(sales):,.0f}")
ax.legend()
plt.show()
💡 Tip: Always use fig, ax = plt.subplots() — gives full control and handles multiple subplots easily.
🎯 TASKPractice: Matplotlib Basics
Create a professional line chart of weekly website traffic for 8 weeks. Add: trend line, average reference line, peak annotation, and proper styling.
Starter code:
python
import matplotlib.pyplot as plt
import numpy as np
weeks = [f"W{i}" for i in range(1,9)]
visitors = [1200,1850,1600,2100,1900,2400,2200,2800]
fig, ax = plt.subplots(figsize=(11, 6))
ax.plot(weeks, visitors, "o-", color="#3b82f6", linewidth=2.5, markersize=8, label="Visitors")
# Add average line
avg = sum(visitors)/len(visitors)
ax.axhline(y=avg, color="orange", linestyle="--", alpha=0.8, label=f"Avg: {avg:,.0f}")
# Annotate peak
peak_idx = visitors.index(max(visitors))
ax.annotate(f"Peak: {max(visitors):,}", xy=(peak_idx, max(visitors)),
xytext=(peak_idx-1, max(visitors)-200),
arrowprops=dict(arrowstyle="->",color="red"),
color="red", fontweight="bold")
# Add trend line
x_num = np.arange(len(weeks))
z = np.polyfit(x_num, visitors, 1)
p = np.poly1d(z)
ax.plot(weeks, p(x_num), "--", color="green", alpha=0.7, label="Trend")
ax.set_title("Weekly Website Traffic", fontsize=14, fontweight="bold")
ax.set_xlabel("Week"); ax.set_ylabel("Visitors")
ax.legend(); ax.grid(True, alpha=0.3)
ax.spines["top"].set_visible(False); ax.spines["right"].set_visible(False)
plt.tight_layout(); plt.show()
Bar Charts
python
import matplotlib.pyplot as plt
import numpy as np
regions = ["Cairo","Alex","Giza","Port Said","Aswan"]
sales = [450000,280000,195000,120000,87000]
colors = ["#3b82f6","#06b6d4","#8b5cf6","#f59e0b","#10b981"]
fig, ax = plt.subplots(figsize=(10,6))
bars = ax.bar(regions, sales, color=colors, width=0.6,
edgecolor="white", linewidth=0.5)
# Value labels on bars
for bar, val in zip(bars, sales):
ax.text(bar.get_x() + bar.get_width()/2, val + 8000,
f"{val/1000:.0f}K", ha="center", va="bottom",
fontsize=10, fontweight="bold")
ax.set_title("Sales by Region — Q4 2024", fontsize=14, fontweight="bold")
ax.set_ylabel("Sales (EGP)")
ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x,_: f"{x/1000:.0f}K"))
ax.grid(axis="y", alpha=0.3, linestyle="--")
ax.spines["top"].set_visible(False); ax.spines["right"].set_visible(False)
plt.tight_layout(); plt.show()
Grouped & Stacked Bar Charts
python
# Grouped bar chart
q1 = [450,280,195]; q2 = [510,310,220]; regions = ["Cairo","Alex","Giza"]
x = np.arange(len(regions)); w = 0.35
fig, axes = plt.subplots(1,2,figsize=(14,5))
# Grouped
axes[0].bar(x-w/2, q1, w, label="Q1",color="#3b82f6")
axes[0].bar(x+w/2, q2, w, label="Q2",color="#06b6d4")
axes[0].set_xticks(x); axes[0].set_xticklabels(regions)
axes[0].legend(); axes[0].set_title("Grouped")
# Stacked
axes[1].bar(regions, q1, label="Q1", color="#3b82f6")
axes[1].bar(regions, q2, bottom=q1, label="Q2", color="#06b6d4")
axes[1].legend(); axes[1].set_title("Stacked")
plt.tight_layout(); plt.show()
🎯 TASKPractice: Bar & Line Charts
Create a horizontal bar chart showing top 10 products by revenue. Add value labels, color by performance tier, and include a reference line for the average.
Starter code:
python
import matplotlib.pyplot as plt
import numpy as np
products = ["Laptop Pro","iPhone 15","Samsung TV","MacBook","iPad","Dell Monitor",
"AirPods","Sony Camera","Kindle","HP Printer"]
revenue = [120000,95000,87000,115000,72000,68000,45000,58000,32000,41000]
# Sort by revenue
paired = sorted(zip(revenue,products), reverse=True)
revenue = [p[0] for p in paired]
products = [p[1] for p in paired]
avg = sum(revenue)/len(revenue)
colors = ["#10b981" if r>avg else "#3b82f6" for r in revenue]
fig, ax = plt.subplots(figsize=(10,7))
bars = ax.barh(products, revenue, color=colors, edgecolor="white", height=0.7)
# Value labels
for bar, val in zip(bars, revenue):
ax.text(val+500, bar.get_y()+bar.get_height()/2,
f"{val/1000:.0f}K", va="center", fontsize=9)
ax.axvline(x=avg, color="orange", linestyle="--",
label=f"Avg: {avg/1000:.1f}K")
ax.set_title("Top 10 Products by Revenue", fontsize=14, fontweight="bold")
ax.set_xlabel("Revenue (EGP)")
ax.legend(); ax.invert_yaxis()
ax.grid(axis="x", alpha=0.3); plt.tight_layout(); plt.show()
Histograms — Distribution
python
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
salaries = np.random.normal(9000, 2000, 500)
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# Basic histogram
axes[0].hist(salaries, bins=30, color="#3b82f6", alpha=0.7, edgecolor="white")
axes[0].axvline(salaries.mean(), color="red", linestyle="--",
linewidth=2, label=f"Mean: {salaries.mean():,.0f}")
axes[0].axvline(np.median(salaries), color="green", linestyle="--",
linewidth=2, label=f"Median: {np.median(salaries):,.0f}")
axes[0].set_title("Salary Distribution"); axes[0].legend()
# KDE (smooth density)
from scipy.stats import gaussian_kde
kde = gaussian_kde(salaries)
x = np.linspace(salaries.min(), salaries.max(), 300)
axes[1].plot(x, kde(x), color="#3b82f6", linewidth=2)
axes[1].fill_between(x, kde(x), alpha=0.3, color="#3b82f6")
axes[1].set_title("KDE (Smooth Distribution)")
plt.tight_layout(); plt.show()
Scatter Plots
python
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
n = 100
marketing = np.random.normal(5000, 1000, n)
sales = marketing * 8 + np.random.normal(0, 5000, n)
sizes = np.random.randint(50, 300, n) # Bubble size
fig, ax = plt.subplots(figsize=(9,6))
sc = ax.scatter(marketing, sales, c=sales, cmap="viridis",
s=sizes, alpha=0.7, edgecolors="white", linewidth=0.5)
plt.colorbar(sc, ax=ax, label="Sales")
# Regression line
z = np.polyfit(marketing, sales, 1)
p = np.poly1d(z)
ax.plot(np.sort(marketing), p(np.sort(marketing)), "r--", linewidth=2, label="Trend")
ax.set_title("Marketing Spend vs Sales"); ax.legend()
ax.set_xlabel("Marketing (EGP)"); ax.set_ylabel("Sales (EGP)")
plt.tight_layout(); plt.show()
🎯 TASKPractice: Histograms & Scatter Plots
Create a side-by-side comparison: distribution of sales before and after a marketing campaign. Show histogram, KDE, and summary statistics.
Starter code:
python
import matplotlib.pyplot as plt, numpy as np
from scipy.stats import gaussian_kde, ttest_ind
np.random.seed(42)
before = np.random.normal(45000, 10000, 100)
after = np.random.normal(52000, 11000, 100)
fig, axes = plt.subplots(1, 2, figsize=(14,5))
fig.suptitle("Sales Distribution: Before vs After Campaign", fontsize=14, fontweight="bold")
for ax, data, label, color in zip(
axes, [before, after], ["Before","After"], ["#ef4444","#10b981"]
):
ax.hist(data, bins=20, color=color, alpha=0.5, edgecolor="white", density=True)
x = np.linspace(data.min(), data.max(), 200)
ax.plot(x, gaussian_kde(data)(x), color=color, linewidth=2)
ax.axvline(data.mean(), color="black", linestyle="--",
label=f"Mean: {data.mean():,.0f}")
ax.set_title(f"{label} Campaign")
ax.set_xlabel("Sales (EGP)"); ax.legend()
t, p = ttest_ind(before, after)
print(f"T-test p-value: {p:.4f}")
print(f"Mean increase: {after.mean()-before.mean():,.0f} ({(after.mean()/before.mean()-1)*100:.1f}%)")
plt.tight_layout(); plt.show()
Pie Charts
python
import matplotlib.pyplot as plt
products = ["Laptop","Phone","Tablet","Monitor","Other"]
sales = [45, 30, 15, 8, 2]
colors = ["#3b82f6","#06b6d4","#8b5cf6","#f59e0b","#94a3b8"]
explode = [0.05, 0.05, 0, 0, 0] # Slightly pull out top slices
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
# Pie chart
axes[0].pie(sales, labels=products, colors=colors, explode=explode,
autopct="%1.1f%%", pctdistance=0.85, startangle=90,
wedgeprops=dict(edgecolor="white", linewidth=2))
axes[0].set_title("Market Share by Product")
# Donut chart (pie with hole)
axes[1].pie(sales, colors=colors, autopct="%1.1f%%",
startangle=90, wedgeprops=dict(edgecolor="white",width=0.6))
axes[1].set_title("Donut Chart")
centre = plt.Circle((0,0), 0.40, fc="white")
axes[1].add_patch(centre)
plt.tight_layout(); plt.show()
Area Charts
python
import matplotlib.pyplot as plt, numpy as np
months = range(1, 13)
product_sales = {
"Laptop": [45,52,48,61,58,72,65,59,71,78,82,95],
"Phone": [30,35,32,41,38,49,44,40,48,52,56,62],
"Tablet": [15,18,16,20,19,25,22,20,24,27,29,34],
}
fig, ax = plt.subplots(figsize=(12,6))
colors = ["#3b82f6","#06b6d4","#8b5cf6"]
bottom = np.zeros(12)
for (product, values), color in zip(product_sales.items(), colors):
ax.fill_between(months, bottom, bottom + np.array(values),
alpha=0.8, color=color, label=product)
bottom += np.array(values)
ax.set_title("Sales by Product (Stacked Area)", fontsize=14)
ax.set_xlabel("Month"); ax.set_ylabel("Sales (thousands)")
ax.legend(loc="upper left"); plt.tight_layout(); plt.show()
🎯 TASKPractice: Pie & Area Charts
Create a dashboard with 3 charts: pie for product mix, area chart for monthly trend, and a donut for regional split.
Starter code:
python
import matplotlib.pyplot as plt, numpy as np
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
fig.suptitle("Sales Dashboard — 2024", fontsize=15, fontweight="bold")
# 1. Pie — product mix
products = ["Laptop","Phone","Tablet","Monitor"]
shares = [35, 28, 22, 15]
colors1 = ["#3b82f6","#06b6d4","#8b5cf6","#f59e0b"]
axes[0].pie(shares, labels=products, colors=colors1, autopct="%1.0f%%",
startangle=90, wedgeprops=dict(edgecolor="white"))
axes[0].set_title("Product Mix")
# 2. Area — monthly trend
months = range(1,13)
sales = [45,52,48,61,58,72,65,59,71,78,82,95]
axes[1].fill_between(months, sales, alpha=0.4, color="#3b82f6")
axes[1].plot(months, sales, "o-", color="#3b82f6", linewidth=2)
axes[1].set_title("Monthly Sales Trend")
axes[1].set_xlabel("Month"); axes[1].grid(True, alpha=0.3)
# 3. Donut — regional split
regions = ["Cairo","Alex","Giza","Other"]
reg_sales = [45, 28, 18, 9]
colors3 = ["#10b981","#3b82f6","#f59e0b","#94a3b8"]
axes[2].pie(reg_sales, colors=colors3, autopct="%1.0f%%",
startangle=90, wedgeprops=dict(edgecolor="white", width=0.5))
axes[2].set_title("Regional Split")
plt.tight_layout(); plt.show()
Why Seaborn?
Seaborn creates beautiful statistical charts with minimal code. Built on Matplotlib with smart defaults.
python
import seaborn as sns, matplotlib.pyplot as plt, pandas as pd, numpy as np
np.random.seed(42)
sns.set_theme(style="whitegrid", palette="muted")
df = pd.DataFrame({
"Sales": np.random.normal(50000,15000,200),
"Region": np.random.choice(["Cairo","Alex","Giza"],200),
"Product":np.random.choice(["Laptop","Phone","Tablet"],200),
"Quarter":np.random.choice(["Q1","Q2","Q3","Q4"],200),
})
fig, axes = plt.subplots(2, 2, figsize=(14,10))
# Boxplot — distribution + outliers
sns.boxplot(data=df, x="Region", y="Sales", ax=axes[0,0], palette="Blues")
axes[0,0].set_title("Sales Distribution by Region")
# Violin plot — distribution shape
sns.violinplot(data=df, x="Product", y="Sales", ax=axes[0,1], palette="Set2")
axes[0,1].set_title("Sales Distribution by Product")
# Strip/swarm plot — individual points
sns.stripplot(data=df, x="Region", y="Sales", ax=axes[1,0],
palette="Set1", alpha=0.5, jitter=True)
axes[1,0].set_title("Individual Sales Points")
# Bar plot (with confidence intervals)
sns.barplot(data=df, x="Quarter", y="Sales", ax=axes[1,1],
palette="rocket", errorbar="sd")
axes[1,1].set_title("Average Sales by Quarter")
plt.tight_layout(); plt.show()
💡 Tip: Seaborn themes: 'darkgrid', 'whitegrid', 'dark', 'white', 'ticks'. Palettes: 'Blues', 'Set2', 'rocket', 'muted', 'deep'.
🎯 TASKPractice: Seaborn Charts
Create a seaborn analysis dashboard: boxplot, violin, and a point plot showing quarterly trends per region.
Starter code:
python
import seaborn as sns, matplotlib.pyplot as plt, pandas as pd, numpy as np
np.random.seed(42)
sns.set_theme(style="whitegrid")
df = pd.DataFrame({
"Region": np.random.choice(["Cairo","Alex","Giza"],120),
"Quarter": np.random.choice(["Q1","Q2","Q3","Q4"],120),
"Sales": np.random.normal(50000,12000,120).round(0),
})
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
fig.suptitle("Regional Sales Analysis", fontsize=14, fontweight="bold")
# Boxplot
sns.boxplot(data=df, x="Region", y="Sales",
palette=["#3b82f6","#06b6d4","#8b5cf6"], ax=axes[0])
axes[0].set_title("Distribution by Region")
# Violin
sns.violinplot(data=df, x="Region", y="Sales",
palette="Set2", inner="quart", ax=axes[1])
axes[1].set_title("Violin: Shape of Distribution")
# Point plot — quarterly trend per region
sns.pointplot(data=df, x="Quarter", y="Sales",
hue="Region", palette="Set1", ax=axes[2],
markers=["o","s","^"], linestyles=["-","--","-."])
axes[2].set_title("Quarterly Trend by Region")
axes[2].legend(title="Region")
plt.tight_layout(); plt.show()
Heatmaps
python
import seaborn as sns, matplotlib.pyplot as plt, pandas as pd, numpy as np
np.random.seed(42)
df = pd.DataFrame(np.random.normal(50000,15000,(4,4)),
index=["Cairo","Alex","Giza","Aswan"],
columns=["Q1","Q2","Q3","Q4"])
fig, axes = plt.subplots(1,2,figsize=(14,5))
# Sales heatmap
sns.heatmap(df, annot=True, fmt=".0f", cmap="YlOrRd",
linewidths=0.5, ax=axes[0])
axes[0].set_title("Sales Heatmap (Region × Quarter)")
# Correlation heatmap
data = pd.DataFrame({
"Sales": np.random.normal(50000,10000,100),
"Marketing": np.random.normal(5000,1000,100),
"Staff": np.random.randint(5,30,100),
"Price": np.random.normal(8000,2000,100),
})
data["Sales"] += data["Marketing"] * 4 # Add correlation
corr = data.corr()
mask = np.triu(np.ones_like(corr, dtype=bool)) # Upper triangle
sns.heatmap(corr, mask=mask, annot=True, fmt=".2f",
cmap="coolwarm", center=0, square=True,
linewidths=0.5, ax=axes[1])
axes[1].set_title("Correlation Matrix")
plt.tight_layout(); plt.show()
Pair Plots
python
# Pair plot — scatterplot matrix
pair_df = pd.DataFrame({
"Sales": np.random.normal(50000,10000,100),
"Marketing": np.random.normal(5000,1000,100),
"Staff": np.random.randint(5,30,100),
"Region": np.random.choice(["Cairo","Alex","Giza"],100),
})
pair_df["Sales"] += pair_df["Marketing"] * 4
g = sns.pairplot(pair_df, hue="Region", diag_kind="kde",
plot_kws={"alpha":0.6})
g.fig.suptitle("Pair Plot — Sales Analysis", y=1.02)
plt.show()
🎯 TASKPractice: Heatmaps & Pair Plots
Create a heatmap showing monthly sales performance by product, a correlation heatmap with mask, and annotate the strongest correlations.
Starter code:
python
import seaborn as sns, matplotlib.pyplot as plt, pandas as pd, numpy as np
np.random.seed(42)
# Monthly sales by product
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
products = ["Laptop","Phone","Tablet","Monitor"]
data = pd.DataFrame(
np.random.normal(50000,15000,(len(months),len(products))).round(0),
index=months, columns=products
)
fig, axes = plt.subplots(1,2,figsize=(16,5))
# Sales heatmap
sns.heatmap(data, annot=True, fmt=".0f", cmap="RdYlGn",
linewidths=0.5, ax=axes[0], cbar_kws={"label":"Sales"})
axes[0].set_title("Monthly Sales by Product")
# Correlation heatmap
multi_df = pd.DataFrame({
"Sales": np.random.normal(50000,10000,200),
"Marketing": np.random.normal(5000,1000,200),
"Traffic": np.random.normal(10000,2000,200),
"Staff": np.random.randint(5,30,200),
"Price": np.random.normal(8000,2000,200),
})
multi_df["Sales"] += multi_df["Marketing"]*4 + multi_df["Traffic"]*2
corr = multi_df.corr()
mask = np.triu(np.ones_like(corr,dtype=bool))
sns.heatmap(corr,mask=mask,annot=True,fmt=".2f",
cmap="coolwarm",center=0,square=True,ax=axes[1])
axes[1].set_title("Correlation Matrix")
plt.tight_layout(); plt.show()
print("Strongest corr with Sales:")
print(corr["Sales"].drop("Sales").abs().sort_values(ascending=False).round(3))
Creating Subplots
python
import matplotlib.pyplot as plt, numpy as np
fig = plt.figure(figsize=(14, 10))
# Grid layout: 2 rows × 3 columns
ax1 = fig.add_subplot(2,3,1) # Row 1, Col 1
ax2 = fig.add_subplot(2,3,2) # Row 1, Col 2
ax3 = fig.add_subplot(2,3,3) # Row 1, Col 3
ax4 = fig.add_subplot(2,1,2) # Row 2, full width
# GridSpec for complex layouts
from matplotlib.gridspec import GridSpec
gs = GridSpec(2, 3, figure=fig, hspace=0.4, wspace=0.3)
ax1 = fig.add_subplot(gs[0,0]) # Row 0, Col 0
ax2 = fig.add_subplot(gs[0,1:]) # Row 0, Cols 1-2
ax3 = fig.add_subplot(gs[1,:2]) # Row 1, Cols 0-1
ax4 = fig.add_subplot(gs[1,2]) # Row 1, Col 2
plt.show()
Complete Dashboard Example
python
import matplotlib.pyplot as plt, numpy as np
np.random.seed(42)
months = ["Jan","Feb","Mar","Apr","May","Jun"]
sales = [45000,52000,48000,61000,58000,72000]
regions = ["Cairo","Alex","Giza","Aswan"]
reg_s = [450,280,195,87]
fig, axes = plt.subplots(2,2,figsize=(14,10))
fig.suptitle("Q1-Q2 Business Dashboard", fontsize=16, fontweight="bold")
axes[0,0].plot(months,sales,"o-",color="#3b82f6",linewidth=2.5)
axes[0,0].fill_between(months,sales,min(sales),alpha=0.15,color="#3b82f6")
axes[0,0].set_title("Monthly Sales Trend")
axes[0,1].barh(regions,reg_s,color=["#3b82f6","#06b6d4","#8b5cf6","#f59e0b"])
axes[0,1].set_title("Sales by Region")
axes[1,0].hist(np.random.normal(50000,10000,200),bins=20,color="#3b82f6",alpha=0.7)
axes[1,0].set_title("Sales Distribution")
axes[1,1].pie([35,28,22,15],labels=["Laptop","Phone","Tablet","Other"],
autopct="%1.0f%%",colors=["#3b82f6","#06b6d4","#8b5cf6","#94a3b8"])
axes[1,1].set_title("Product Mix")
plt.tight_layout(); plt.savefig("dashboard.png",dpi=150); plt.show()
🎯 TASKPractice: Subplots & Dashboards
Build a complete executive dashboard: 6-panel layout with KPI indicators, trend, regional comparison, product mix, distribution, and correlation.
Starter code:
python
import matplotlib.pyplot as plt, numpy as np, pandas as pd
np.random.seed(42)
# Data
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
sales_m = [45,52,48,61,58,72,65,59,71,78,82,95]
regions = ["Cairo","Alex","Giza","Aswan"]
reg_s = [450,280,195,120]
products = ["Laptop","Phone","Tablet","Monitor"]
prod_s = [35,28,22,15]
fig = plt.figure(figsize=(18,12))
fig.suptitle("Annual Business Dashboard — 2024", fontsize=18, fontweight="bold", y=0.98)
from matplotlib.gridspec import GridSpec
gs = GridSpec(3, 4, figure=fig, hspace=0.5, wspace=0.4)
# 1. KPI Cards (text plots)
kpis = [("Total Revenue","₤14.2M","+18%"),("Avg Monthly","₤1.18M","+12%"),
("Best Month","₤950K","Dec"),("Regions","4","Active")]
for i,(label,val,sub) in enumerate(kpis):
ax = fig.add_subplot(gs[0,i])
ax.text(0.5,0.6,val,ha="center",va="center",fontsize=20,fontweight="bold",
color="#3b82f6",transform=ax.transAxes)
ax.text(0.5,0.85,label,ha="center",va="center",fontsize=10,
color="gray",transform=ax.transAxes)
ax.text(0.5,0.25,sub,ha="center",va="center",fontsize=12,
color="#10b981",transform=ax.transAxes)
ax.axis("off"); ax.set_facecolor("#f8fafc")
# 2. Sales trend (wide)
ax2 = fig.add_subplot(gs[1,:3])
ax2.plot(months,sales_m,"o-",color="#3b82f6",linewidth=2.5)
ax2.fill_between(range(12),sales_m,min(sales_m),alpha=0.15,color="#3b82f6")
ax2.set_title("Monthly Sales Trend (Thousands EGP)",fontsize=12)
ax2.grid(True,alpha=0.3); ax2.set_xlim(-0.5,11.5)
ax2.set_xticks(range(12)); ax2.set_xticklabels(months,rotation=45)
# 3. Pie (right)
ax3 = fig.add_subplot(gs[1,3])
ax3.pie(prod_s,labels=products,autopct="%1.0f%%",startangle=90,
colors=["#3b82f6","#06b6d4","#8b5cf6","#f59e0b"],
wedgeprops=dict(edgecolor="white"))
ax3.set_title("Product Mix",fontsize=12)
# 4. Bar chart
ax4 = fig.add_subplot(gs[2,:2])
bars = ax4.bar(regions,reg_s,color=["#3b82f6","#06b6d4","#8b5cf6","#f59e0b"],width=0.6)
for bar,val in zip(bars,reg_s): ax4.text(bar.get_x()+bar.get_width()/2,val+5,f"{val}K",ha="center",fontsize=10)
ax4.set_title("Sales by Region (Thousands EGP)",fontsize=12)
ax4.grid(axis="y",alpha=0.3)
# 5. Distribution
ax5 = fig.add_subplot(gs[2,2:])
data = np.random.normal(58000,12000,200)
ax5.hist(data,bins=25,color="#3b82f6",alpha=0.7,edgecolor="white",density=True)
ax5.axvline(data.mean(),color="red",linestyle="--",label=f"Mean: {data.mean():,.0f}")
ax5.set_title("Daily Sales Distribution",fontsize=12)
ax5.legend()
plt.savefig("executive_dashboard.png",dpi=150,bbox_inches="tight")
plt.show()
print("Dashboard saved!")
Why Plotly?
Plotly creates interactive charts — zoom, pan, hover for details, click to filter. Perfect for web dashboards and reports.
python
import plotly.express as px
import pandas as pd, numpy as np
np.random.seed(42)
df = pd.DataFrame({
"Month": pd.date_range("2024-01",periods=12,freq="ME"),
"Sales": np.random.normal(50000,10000,12).round(0),
"Region": np.random.choice(["Cairo","Alex","Giza"],12),
"Product": np.random.choice(["Laptop","Phone","Tablet"],12),
})
# Interactive line chart
fig = px.line(df, x="Month", y="Sales",
title="Monthly Sales — Interactive",
labels={"Sales":"Revenue (EGP)"},
template="plotly_dark")
fig.update_traces(line_width=2.5, marker_size=8, mode="lines+markers")
fig.show() # Opens in browser (or Jupyter)
# Interactive scatter
fig2 = px.scatter(df, x="Month", y="Sales",
color="Region", size="Sales", hover_data=["Product"],
title="Sales by Region")
fig2.show()
Interactive Dashboard
python
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=2,
subplot_titles=["Monthly Trend","By Region","Distribution","Product Mix"])
months = ["Jan","Feb","Mar","Apr","May","Jun"]
sales = [45000,52000,48000,61000,58000,72000]
# Line chart
fig.add_trace(go.Scatter(x=months,y=sales,mode="lines+markers",
line=dict(color="#3b82f6",width=2.5)), row=1,col=1)
# Bar chart
fig.add_trace(go.Bar(x=["Cairo","Alex","Giza"],
y=[450000,280000,195000],
marker_color=["#3b82f6","#06b6d4","#8b5cf6"]), row=1,col=2)
fig.update_layout(height=600, showlegend=False,
title_text="Interactive Dashboard")
fig.show()
💡 Tip: Save Plotly charts as HTML for easy sharing: fig.write_html('chart.html'). No dependencies needed to view!
🎯 TASKPractice: Plotly — Interactive Charts
Create an interactive Plotly dashboard: line chart of monthly sales, bar chart by region, scatter of marketing vs sales, and a pie chart.
Starter code:
python
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
np.random.seed(42)
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
sales_m = [45,52,48,61,58,72,65,59,71,78,82,95]
regions = ["Cairo","Alex","Giza","Aswan"]
reg_s = [450,280,195,120]
marketing = np.random.normal(5,1,50).round(1)
sales_s = (marketing * 8 + np.random.normal(0,5,50)).round(1)
fig = make_subplots(
rows=2, cols=2,
subplot_titles=["Monthly Sales (K EGP)","Sales by Region",
"Marketing vs Sales","Product Mix"],
specs=[[{"type":"scatter"},{"type":"bar"}],
[{"type":"scatter"},{"type":"pie"}]]
)
# Line chart
fig.add_trace(go.Scatter(x=months,y=sales_m,mode="lines+markers",
line=dict(color="#3b82f6",width=2.5),name="Sales"), row=1,col=1)
# Bar chart
fig.add_trace(go.Bar(x=regions,y=reg_s,
marker_color=["#3b82f6","#06b6d4","#8b5cf6","#f59e0b"],
name="Region"), row=1,col=2)
# Scatter
fig.add_trace(go.Scatter(x=marketing,y=sales_s,mode="markers",
marker=dict(color=sales_s,colorscale="Viridis",size=8),
name="Marketing"), row=2,col=1)
# Pie
fig.add_trace(go.Pie(labels=["Laptop","Phone","Tablet","Monitor"],
values=[35,28,22,15],hole=0.3), row=2,col=2)
fig.update_layout(height=700,title_text="Interactive Business Dashboard",
showlegend=False, template="plotly_white")
fig.show()
print("Interactive dashboard created!")
Matplotlib Styles
python
import matplotlib.pyplot as plt, numpy as np
# Built-in styles
print(plt.style.available[:5]) # Show available styles
# Apply a style
plt.style.use("seaborn-v0_8-whitegrid")
# Create custom color palette
COLORS = {
"primary": "#3b82f6",
"secondary": "#06b6d4",
"accent": "#f59e0b",
"success": "#10b981",
"danger": "#ef4444",
"muted": "#94a3b8",
}
# Custom matplotlib parameters (rcParams)
plt.rcParams.update({
"font.family": "sans-serif",
"font.size": 11,
"axes.titlesize": 14,
"axes.titleweight": "bold",
"axes.spines.top": False,
"axes.spines.right": False,
"axes.grid": True,
"grid.alpha": 0.3,
"grid.linestyle": "--",
"figure.dpi": 120,
})
months = ["Jan","Feb","Mar","Apr","May","Jun"]
sales = [45000,52000,48000,61000,58000,72000]
fig, ax = plt.subplots(figsize=(10,5))
ax.plot(months, sales, "o-", color=COLORS["primary"], linewidth=2.5)
ax.fill_between(months, sales, min(sales), alpha=0.1, color=COLORS["primary"])
ax.set_title("Professional Sales Chart")
plt.tight_layout(); plt.show()
Seaborn Themes
python
import seaborn as sns, matplotlib.pyplot as plt
# Available contexts: "paper","notebook","talk","poster"
sns.set_context("talk") # Larger text for presentations
sns.set_palette("husl") # Color palette
# Color palettes
print(sns.color_palette("Set2").as_hex())
print(sns.color_palette("rocket",5).as_hex())
💡 Tip: For professional reports: use 'whitegrid' or 'white' with muted colors. For presentations: use 'talk' context with bold colors.
🎯 TASKPractice: Chart Styling & Themes
Create the same chart with 4 different styles. Compare: default, seaborn-whitegrid, dark, and a custom professional style.
Starter code:
python
import matplotlib.pyplot as plt, numpy as np
months = ["Jan","Feb","Mar","Apr","May","Jun"]
sales = [45000,52000,48000,61000,58000,72000]
styles_configs = [
("Default", "default", "#1f77b4"),
("Whitegrid", "seaborn-v0_8-whitegrid", "#3b82f6"),
("Dark", "dark_background", "#06b6d4"),
("FiveThirtyEight","fivethirtyeight", "#e74c3c"),
]
fig, axes = plt.subplots(2, 2, figsize=(14,8))
fig.suptitle("Same Data, 4 Different Styles", fontsize=14, fontweight="bold")
for ax, (name, style, color) in zip(axes.flat, styles_configs):
with plt.style.context(style):
ax.plot(months, sales, "o-", color=color, linewidth=2.5)
ax.fill_between(months, sales, min(sales), alpha=0.15, color=color)
ax.set_title(name, fontsize=12)
ax.set_ylabel("Sales")
plt.tight_layout(); plt.show()
Saving High-Quality Images
python
import matplotlib.pyplot as plt, numpy as np
months = ["Jan","Feb","Mar","Apr","May","Jun"]
sales = [45000,52000,48000,61000,58000,72000]
fig, ax = plt.subplots(figsize=(10,5))
ax.plot(months,sales,"o-",color="#3b82f6",linewidth=2.5)
ax.set_title("Monthly Sales Chart")
plt.tight_layout()
# PNG — for web and presentations
plt.savefig("chart.png", dpi=150, bbox_inches="tight",
facecolor="white", edgecolor="none")
# High-res PNG — for printing
plt.savefig("chart_hires.png", dpi=300, bbox_inches="tight")
# PDF — vector format, best for print
plt.savefig("chart.pdf", bbox_inches="tight", format="pdf")
# SVG — vector, editable in Illustrator/Inkscape
plt.savefig("chart.svg", bbox_inches="tight", format="svg")
print("All formats saved!")
plt.close() # Close figure to free memory
Exporting to Excel with Charts
python
import pandas as pd, xlsxwriter
# Create Excel with embedded chart
df = pd.DataFrame({"Month":months,"Sales":sales})
with pd.ExcelWriter("report.xlsx", engine="xlsxwriter") as writer:
df.to_excel(writer, sheet_name="Data", index=False)
wb = writer.book
ws = writer.sheets["Data"]
# Add chart
chart = wb.add_chart({"type":"line"})
chart.add_series({"values":"=Data!$B$2:$B$7","name":"Sales"})
chart.set_title({"name":"Monthly Sales"})
ws.insert_chart("D2", chart)
print("Excel with chart saved!")
💡 Tip: For web sharing: save as PNG/HTML. For print: use PDF or SVG. For Excel reports: use xlsxwriter. Always use bbox_inches='tight' to prevent label cropping.
🎯 TASKPractice: Exporting & Sharing Charts
Create a complete multi-format export pipeline: save a dashboard as PNG, PDF, SVG, and HTML (Plotly), then package all files.
Starter code:
python
import matplotlib.pyplot as plt, numpy as np
import plotly.graph_objects as go
import os
np.random.seed(42)
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
sales = [45,52,48,61,58,72,65,59,71,78,82,95]
regions = ["Cairo","Alex","Giza","Aswan"]
reg_s = [450,280,195,120]
# Create output folder
os.makedirs("exports", exist_ok=True)
# Matplotlib chart
fig, axes = plt.subplots(1,2,figsize=(14,5))
fig.suptitle("Annual Dashboard", fontsize=14, fontweight="bold")
axes[0].plot(months,sales,"o-",color="#3b82f6",linewidth=2.5)
axes[0].set_title("Monthly Trend"); axes[0].grid(True,alpha=0.3)
axes[1].barh(regions,reg_s,color=["#3b82f6","#06b6d4","#8b5cf6","#f59e0b"])
axes[1].set_title("Regional Sales"); axes[1].invert_yaxis()
plt.tight_layout()
# Export multiple formats
for fmt, dpi in [("png",150),("pdf",None),("svg",None)]:
fname = f"exports/dashboard.{fmt}"
if dpi: plt.savefig(fname, dpi=dpi, bbox_inches="tight")
else: plt.savefig(fname, bbox_inches="tight", format=fmt)
print(f"Saved: {fname} ({os.path.getsize(fname)/1024:.1f} KB)")
plt.close()
# Plotly interactive
fig2 = go.Figure()
fig2.add_trace(go.Scatter(x=months,y=sales,mode="lines+markers",name="Sales"))
fig2.update_layout(title="Interactive Sales Chart",template="plotly_white")
fig2.write_html("exports/dashboard.html")
print(f"Saved: exports/dashboard.html ({os.path.getsize('exports/dashboard.html')/1024:.0f} KB)")