1.4.8Python & Scientific Computing

Matplotlib and Seaborn visualization

3,142 words14 min readdifficulty · medium

Overview

Data visualization transforms numerical arrays into visual insights. Matplotlib is Python's foundational plotting library (MATLAB-like API), while Seaborn is a statistical visualization layer built on top of Matplotlib with better defaults and statistical functions.


Core Concepts


Matplotlib Fundamentals

The Object-Oriented Pattern (WHY/HOW)

WHY use the OO interface?

  • Explicit control: You know which Axes you're drawing on (critical for subplots)
  • Reproducibility: No hidden global state
  • Composability: Functions can accept ax as an argument

HOW the anatomy works:

import matplotlib.pyplot as plt
import numpy as np
 
# Create container and plot area
fig, ax = plt.subplots(figsize=(8, 6))  # figure size in inches
 
# Generate data
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
 
# Plot on the Axes object
ax.plot(x, y, label='sin(x)', color='blue', linewidth=2)
 
# Customize the Axes
ax.set_xlabel('Radians', fontsize=12)
ax.set_ylabel('Amplitude', fontsize=12)
ax.set_title('Sine Wave Demonstration', fontsize=14, fontweight='bold')
ax.legend(loc='upper right')
ax.grid(True, alpha=0.3)
 
plt.tight_layout()  # Prevent label clipping
plt.show()

Why this step?

  • fig, ax = plt.subplots(): Unpacks a Figure and a single Axes. For 2×2 grid: fig, axes = plt.subplots(2, 2) gives you axes[0,0], axes[0,1], etc.
  • ax.plot(): Draws on this specific Axes, not some global state
  • tight_layout(): Auto-adjusts spacing so labels don't overlap

Seaborn: Statistical Visualization

Distribution Plots

Relationship Plots

Categorical Plots


Common Mistakes & Fixes


Advanced Techniques


Memory Aid


Active Recall Questions

Recall Explain Matplotlib to a 12-year-old

Imagine you have a blank poster board (that's the Figure). You tape a grid paper onto it (that's the Axes). Now you draw a line graph of your test scores over time—the line is an Artist (something visible).

You could tape multiple grid papers one poster (subplots). Each grid has its own graph.

Matplotlib = the tools to draw. Seaborn = a smart assistant that draws common patterns for you (like "draw me a graph showing if taller people weigh more, and add a best-fit line automatically").


Connections


#flashcards/ai-ml

What are the two main interfaces in Matplotlib and when should you use each? :: pyplot (state-machine) like plt.plot() for quick REPL sketches. Object-oriented like fig, ax = plt.subplots(); ax.plot() for production code because you have explicit control over which Axes you're modifying, enabling reproducibility and composability.

What is the difference between a Figure and an Axes in Matplotlib?
Figure is the entire canvas/window. Axes (note: plural, not "axis") is a single plot area within the figure with its own coordinate system. One Figure can contain multiple Axes (subplots).
Why use ax.set_yscale('log') when plotting training loss?
Loss often decreases exponentially during training. A log scale makes the tail of the curve (small improvements in later epochs) visible instead of being compressed near zero.
What does density=True do in ax.hist() and why use it?
Normalizes the histogram so the total area equals 1, converting it to a probability density. This allows you to overlay theoretical PDF curves for comparison.
In Seaborn's regplot(), what does the shaded region around the regression line represent?
The 95% confidence interval for the regression line. It shows: "If we resampled the data many times, 95% of fitted lines would pass through this band." Wide bands indicate high uncertainty.
Why is a violin plot better than a boxplot?
Violin plots show the full distribution shape (is it bimodal? skewed? uniform?) while boxplots only show quartiles, potentially hiding important distribution characteristics like multiple peaks.
When should a bar chart NOT start at zero?
For interval scales (accuracy, temperature) where zero is not a meaningful baseline. Example: comparing models at 89%, 90%, 91% accuracy—starting at 0 makes differences invisible. Ratio scales (revenue, count) should start at 0.
Why avoid the'jet' colormap?
(1) Not perceptually uniform—yellow appears "brighter" than red even at same intensity. (2) Not colorblind-safe—8% of men can't distinguish red/green. (3) Loses structure when printed in grayscale. Use'viridis' or 'plasma' instead.
What's the difference between plt.plot() and ax.plot() in terms of code safety?
plt.plot() modifies global implicit state ("current" Axes), causing bugs in functions and loops. ax.plot() explicitly specifies which Axes to draw on, making code reproducible and composable.
What does transform=ax.transAxes do when placing text?
Places text in Axes coordinates (0-1 normalized within the plot area) instead of data coordinates. Example: ax.text(0.5, 0.9, 'Title', transform=ax.transAxes) puts text at top-center regardless of data range.
What DPI should you use when saving figures for publication?
300 DPI (dots per inch) is the standard for print publications. Also use bbox_inches='tight' to remove excess whitespace: plt.savefig('plot.png', dpi=300, bbox_inches='tight').
Why use sns.heatmap() for confusion matrices?
Instantly reveals which classes are confused (off-diagonal cells). Color intensity shows error magnitude. annot=True overlays exact counts, combining visual and numerical information.
What does kde=True add to a histogram in Seaborn?
Overlays a Kernel Density Estimate—a smooth curve showing the underlying probability distribution estimated by placing a Gaussian kernel at each data point and summing them.
How do you make a plot colorblind-accessible?
Use perceptually-uniform colormaps: 'viridis', 'plasma', 'cividis' (all colorblind-safe). For categorical data, use 'Set2' or 'tab10'. Avoid red-green combinations. Test with a colorblind simulator.
What's the purpose of plt.tight_layout()?
Automatically adjusts subplot spacing and margins to prevent labels, titles, and tick marks from overlapping or being clipped at figure edges.

Concept Map

implemented by

foundational library

built on top of

hierarchical model

contains

holds

interface 1

interface 2

explicit control of

adds

enables

returns

Data Visualization

Matplotlib

Seaborn

Figure fig

Axes ax

Artist

pyplot state-machine

Object-Oriented interface

Statistical defaults

DataFrame integration

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, yeh note basically yeh samjha raha hai ki data ko sirf numbers me dekhna kaafi nahi hota. Socho tumhare paas ek neural network hai jo 1000x10 ka probability matrix output karta hai — us raw numbers ke matrix ko dekh ke tumhe kuch samajh nahi aayega. Lekin agar tum usko plot bana ke visual form me dekho, toh patterns turant samajh aa jaate hain — jaise data balanced hai ya nahi, loss smoothly kam ho raha hai ya nahi, model kahan fail kar raha hai. Isiliye visualization ko "debugging with your visual cortex" kehte hain, kyunki humans graphs me outliers aur trends spreadsheet ke comparison me 1000 guna fast pakad lete hain.

Ab tools ki baat karein toh do main libraries hain — Matplotlib jo foundation hai (MATLAB jaisa API), aur Seaborn jo Matplotlib ke upar built ek statistical layer hai jisme better defaults aur ready-made statistical functions hote hain. Matplotlib ka structure hierarchical hai: sabse bada container hai Figure (poora canvas), uske andar hoti hai Axes (ek plot area — dhyan rahe yeh "axis" se alag hai), aur har visible cheez (line, text) ko Artist kehte hain. Do interface milte hain — ek plt.plot() wala pyplot style jo quick aur easy hai lekin global state modify karta hai, aur doosra Object-Oriented style (fig, ax = plt.subplots()) jo explicit aur reproducible hai. Industry me OO style hi standard hai kyunki tum exactly control kar sakte ho ki kaunse Axes pe draw ho raha hai — especially jab multiple subplots ho.

Ek important cheez jo yeh note highlight karta hai woh hai coordinate systems. Matplotlib me data coordinates (actual values), Axes coordinates (0 se 1 tak normalized), Figure coordinates, aur display (pixels) — sab alag hote hain. Iska practical fayda yeh hai ki agar tumhe text ko "20% left se, 80% bottom se" fixed jagah pe rakhna hai chahe data range kuch bhi ho, toh tum transform=ax.transAxes use karte ho. Yeh chhoti si baat exam aur real projects dono me kaam aati hai, kyunki without proper transform tumhara text screen se bahar ja sakta hai. Overall, yeh topic tumhare liye foundation hai — kyunki aage har ML project me tum data explore karne, results dikhane, aur models debug karne ke liye yehi visualization skills baar-baar use karoge.

Go deeper — visual, from zero

Test yourself — Python & Scientific Computing

Connections