Data Visualization: Matplotlib & Seaborn

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 57 of 65 ๐Ÿ“‚ Phase 11: Data Science and AI ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: The Anatomy of a Figure ยท Matplotlib Object-Oriented Interface ยท Line & Bar Charts ยท Histograms & Distributions ยท Scatter & Box Plots ยท Seaborn Heatmaps
Master visual data storytelling in Python: the structural anatomy of Matplotlib figures (Figure vs Axes), rendering professional Line charts, Bar charts, Histograms, and Scatter plots, and creating statistical heatmaps with Seaborn.
1The Anatomy of a Plot: Figure vs Axes in Matplotlib

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 PLOT ANATOMY โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ FIGURE (Top-level canvas created via fig, ax = plt.subplots()) โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ Title: "Monthly Revenue & Growth Rate (2026)" โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ Y-Axis Label: Revenue (โ‚น) โ”‚ โ”‚ โ”‚ โ”‚ โ–ฒ โ”‚ โ”‚ โ”‚ โ”‚ 10kโ”‚ โ€ข โ”‚ โ”‚ โ”‚ โ”‚ 8kโ”‚ / \ โ€ข โ”‚ โ”‚ โ”‚ โ”‚ 6kโ”‚ โ€ข \ / \ Legend: [โ”€โ”€ Revenue 2026] โ”‚ โ”‚ โ”‚ โ”‚ 4kโ”‚ โ€ข \ โ€ข โ€ข โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ X-Axis Label: Month โ”‚ โ”‚ โ”‚ โ”‚ Jan Feb Mar Apr May โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
๐Ÿ’ป Blueprint: Matplotlib Object-Oriented Interface Configuration
# 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.")
๐Ÿ” Why use fig, ax = plt.subplots() instead of plt.plot()?

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.

2Core Chart Types & Seaborn Statistical Enhancements

Choosing the correct chart type is essential for effective data storytelling:

Chart TypeBest Used ForMatplotlib / Seaborn Method
Line ChartContinuous trends over time (time series)ax.plot() / sns.lineplot()
Bar ChartComparing discrete categorical metricsax.bar() / sns.barplot()
HistogramInspecting data distribution and skewnessax.hist() / sns.histplot()
Scatter PlotDetecting correlation between 2 numeric variablesax.scatter() / sns.scatterplot()
Box PlotVisualizing quartiles, median, and outliersax.boxplot() / sns.boxplot()
HeatmapCorrelation matrices between all featuressns.heatmap(df.corr(), annot=True)
๐Ÿ’ป Example 2: 5-Number Distribution Summary for Box Plot Visualizations
# 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}")
๐Ÿ” Outlier Formula:

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.

โš ๏ธ Common Developer Pitfall: Using 3D Pie Charts or Unlabeled Color Scales

3D pie charts distort visual angles, misleading human perception of relative area. Always use clean 2D bar charts or donut charts with labeled percentages.

๐Ÿ’ป Hands-on Interactive Practice Challenge

Simulate generating correlation data for a heatmap: compute the Pearson correlation between advertising spend and sales revenue.

Python 3 Practice Challenge โ–ถ Run in Compiler
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! ๐Ÿš€)")
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

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.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026