Data Visualization: Matplotlib & Seaborn
Matplotlib is the foundational 2D plotting library in Python. To master it, you must understand its object-oriented architecture:
- Figure: The top-level canvas/window holding everything (the blank paper).
- Axes (Subplot): The actual plotting region containing data points, x/y-axis ticks, lines, labels, legend, and title. A single Figure can contain multiple Axes (e.g. a $2 \times 2$ grid of charts).
# Matplotlib Blueprint: Object-Oriented Plotting Syntax Reference:
"""
import matplotlib.pyplot as plt
import seaborn as sns
# 1. Create Figure and Axes canvas:
fig, ax = plt.subplots(figsize=(10, 6), dpi=100)
# 2. Plot Data:
months = ["Jan", "Feb", "Mar", "Apr", "May"]
revenue = [45000, 52000, 61000, 58000, 74000]
ax.plot(months, revenue, color="#10b981", marker="o", linewidth=2.5, label="Monthly Revenue (โน)")
# 3. Polish Aesthetics:
ax.set_title("Revenue Growth Trend (2026)", fontsize=14, fontweight="bold", pad=15)
ax.set_xlabel("Financial Month", fontsize=11)
ax.set_ylabel("Gross Revenue (INR)", fontsize=11)
ax.grid(True, linestyle="--", alpha=0.5)
ax.legend()
# 4. Save High-Res Image:
plt.tight_layout()
# fig.savefig("revenue_trend.png", dpi=300)
"""
print("Matplotlib Object-Oriented Plotting Blueprint Configured.")
Using the Object-Oriented (OO) interface gives you explicit control over multiple subplots, axes styling, and secondary y-axes, preventing state pollution in multi-threaded environments.
Choosing the correct chart type is essential for effective data storytelling:
| Chart Type | Best Used For | Matplotlib / Seaborn Method |
|---|---|---|
| Line Chart | Continuous trends over time (time series) | ax.plot() / sns.lineplot() |
| Bar Chart | Comparing discrete categorical metrics | ax.bar() / sns.barplot() |
| Histogram | Inspecting data distribution and skewness | ax.hist() / sns.histplot() |
| Scatter Plot | Detecting correlation between 2 numeric variables | ax.scatter() / sns.scatterplot() |
| Box Plot | Visualizing quartiles, median, and outliers | ax.boxplot() / sns.boxplot() |
| Heatmap | Correlation matrices between all features | sns.heatmap(df.corr(), annot=True) |
# Text-Based Statistical Distribution Visualizer (Histogram & Outlier Summary):
test_scores = [42, 65, 68, 72, 75, 78, 80, 82, 85, 88, 90, 92, 95, 98, 100]
# Compute 5-Number Summary (Box Plot Statistics):
sorted_scores = sorted(test_scores)
n = len(sorted_scores)
min_v = sorted_scores[0]
max_v = sorted_scores[-1]
median_v = sorted_scores[n // 2]
q1 = sorted_scores[n // 4]
q3 = sorted_scores[(3 * n) // 4]
iqr = q3 - q1
print("--- ๐ Statistical 5-Number Summary (Box Plot Equivalent) ---")
print(f"โข Minimum: {min_v}")
print(f"โข Q1 (25th %): {q1}")
print(f"โข Median (50%):{median_v}")
print(f"โข Q3 (75th %): {q3}")
print(f"โข Maximum: {max_v}")
print(f"โข IQR: {iqr}")
Any data point smaller than $Q1 - 1.5 \times \text{IQR}$ or larger than $Q3 + 1.5 \times \text{IQR}$ is statistically classified as an outlier and displayed as an individual dot in Seaborn box plots.
3D pie charts distort visual angles, misleading human perception of relative area. Always use clean 2D bar charts or donut charts with labeled percentages.
Simulate generating correlation data for a heatmap: compute the Pearson correlation between advertising spend and sales revenue.
ad_spend = [10, 20, 30, 40, 50]
sales = [25, 45, 65, 85, 105]
mean_x = sum(ad_spend) / len(ad_spend)
mean_y = sum(sales) / len(sales)
numerator = sum((x - mean_x) * (y - mean_y) for x, y in zip(ad_spend, sales))
denominator = (sum((x - mean_x)**2 for x in ad_spend) * sum((y - mean_y)**2 for y in sales)) ** 0.5
correlation = numerator / denominator
print(f"Correlation Coefficient: {correlation:.2f} (Perfect Linear Correlation! ๐)")
Q What is Seaborn built on top of?
Seaborn is built directly on top of Matplotlib and integrates tightly with Pandas DataFrames, providing elegant modern styling defaults and statistical estimation plots.
Q How do I save a Matplotlib figure as an image file?
Call fig.savefig("chart.png", dpi=300, bbox_inches="tight") to export a publication-quality image with tight margins.
Q What is the purpose of plt.tight_layout()?
plt.tight_layout() automatically adjusts subplot padding, title spacing, and axis labels to prevent overlapping elements.