{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# \ud83c\udfa8 The Easy & Detailed Matplotlib Guide: From Zero to Data Visualization Masterclass\n",
"> **A Comprehensive, Visual, and Intuitive Reference Guide to Scientific Plotting & Data Visualization**\n",
"> \n",
"> *Target Audience:* Beginners seeking crystal-clear clarity, Data Scientists looking for a thorough reference, and ML practitioners building beautiful publications, dashboards, and evaluation metric plots.\n",
"\n",
"---\n",
"\n",
"### \ud83c\udf1f How to Use This Notebook\n",
"1. **Detailed Explanations in Plain English:** Every single concept is broken down step-by-step with clear real-world intuition, analogies, and \"under-the-hood\" mechanics\u2014easy to read, not deeper or mathematically dense.\n",
"2. **Visual Mental Models:** Visual ASCII diagrams illustrate the Figure/Axes hierarchy, subplot indexing grids, coordinate spaces, and statistical plot anatomy.\n",
"3. **Pre-Executed & Verified:** Every code cell is pre-executed with real outputs so you can read this like an illustrated technical handbook or run each cell interactively.\n",
"4. **Pro-Tips, Gotchas & Best Practices:** Dedicated callouts highlight real-world gotchas like GUI memory leaks, twin-axes legend traps, and publication-ready DPI export rules.\n",
"5. **Smooth Navigation:** Use the **Table of Contents** below or each chapter's `[\u2b06\ufe0f Back to Table of Contents]` link to jump directly to any section.\n",
"\n",
"---\n",
"\n",
"\n",
"## \ud83d\udcd1 Table of Contents\n",
"\n",
"| Part | Chapter | Key Topics Covered |\n",
"| :---: | :--- | :--- |\n",
"| **I** | [1. Core Mental Model: How Matplotlib Works Under the Hood](#ch1) | Object Hierarchy (Figure, Axes, Axis, Artists), State-Based (`pyplot`) vs Object-Oriented API |\n",
"| **I** | [2. Creating Figures, Subplots & Layouts](#ch2) | `plt.subplots()`, `figsize`, `dpi`, shared axes, 2D grid indexing (`axs.flatten()`), `subplot_mosaic`, `savefig` |\n",
"| **II** | [3. Line Plots & Time Series](#ch3) | Linestyles, markers, colors, alpha, multiple series, shaded confidence bands (`fill_between`), twin axes (`twinx`) |\n",
"| **II** | [4. Scatter Plots & Multi-Dimensional Mapping](#ch4) | `scatter()`, 4D data mapping (X, Y, Color, Size), colorbars, categorical clusters, jittering |\n",
"| **II** | [5. Bar Charts & Categorical Comparisons](#ch5) | Vertical (`bar`), horizontal (`barh`), grouped/clustered bars with offsets, stacked bars, `ax.bar_label()` |\n",
"| **II** | [6. Histograms & Density Distributions](#ch6) | Bins selection (`'auto'`, `'fd'`), probability density (`density=True`), stepped histograms, 2D Hexbin density |\n",
"| **II** | [7. Box Plots & Violin Plots: Statistical Spreads](#ch7) | Box plot anatomy (IQR, whiskers, outliers), `patch_artist`, violin probability density, jittered scatter strips |\n",
"| **III** | [8. Titles, Labels, Ticks & Spines Customization](#ch8) | LaTeX math strings, `matplotlib.ticker` (MultipleLocator, PercentFormatter, FuncFormatter), spine removal, log scales |\n",
"| **III** | [9. Legends, Text Annotations & Callouts](#ch9) | Legend placement (`bbox_to_anchor`, `ncol`), arrow callouts (`ax.annotate`), reference lines/spans (`axvline`, `axvspan`) |\n",
"| **III** | [10. Colors, Colormaps & Stylesheets](#ch10) | Sequential, Diverging, Qualitative colormaps, why to avoid `jet`, built-in stylesheets, context manager theming, `rcParams` |\n",
"| **IV** | [11. Heatmaps & Matrix Visualizations](#ch11) | Correlation matrices with `ax.imshow()`, overlaid numerical values, aspect ratios, image feature maps |\n",
"| **IV** | [12. Contour Plots & Decision Boundaries](#ch12) | 2D coordinate grids (`np.meshgrid`), filled contours (`contourf`), ML classifier decision boundaries |\n",
"| **IV** | [13. 3D Surface & Scatter Plots](#ch13) | `mpl_toolkits.mplot3d`, 3D scatter, surface plots (`plot_surface`), elevation and azimuth camera angles |\n",
"| **V** | [14. Essential Machine Learning Visualizations](#ch14) | Training vs Validation loss curves, Confusion Matrix, ROC-AUC Curve, Precision-Recall Curve, Feature Importances |\n",
"| **V** | [15. Performance, Memory Management & Publication Export](#ch15) | The GUI memory leak (`plt.close('all')`), vector (PDF/SVG) vs raster (PNG), font embedding for papers, common anti-patterns |\n",
"| **V** | [16. Comprehensive Matplotlib Quick Reference Cheat Sheet](#summary) | High-frequency API lookup table, format codes dictionary, and companion practice exercises |\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"# Part I: Foundations & The Core Mental Model\n",
"\n",
"## 1. Core Mental Model: How Matplotlib Works Under the Hood\n",
"\n",
"When engineers and data scientists begin using Python for data analysis, Matplotlib often feels intimidating or confusing:\n",
"- *\"Why are there two completely different ways to plot (`plt.plot` vs `ax.plot`)?\"*\n",
"- *\"Why did my title or legend accidentally appear on the wrong subplot?\"*\n",
"- *\"What is the exact distinction between a Figure, an Axes, and an Axis?\"*\n",
"\n",
"To master Matplotlib and produce publication-grade charts effortlessly, you only need one thing: **the correct mental model of its object hierarchy**.\n",
"\n",
"---\n",
"\n",
"### 1.1 The Matplotlib Object Hierarchy\n",
"Think of a Matplotlib visualization like a painting created by a professional artist:\n",
"1. **The Figure (The Blank Canvas / Frame):**\n",
" - The top-level container that holds everything. It represents the physical window or image file (e.g., an 8x5 inch canvas at 300 DPI). A single Figure can contain one or dozens of individual plots.\n",
"2. **The Axes (The Actual Plot / Coordinate System):**\n",
" - **Crucial Terminology Note:** Notice the spelling! It is **Axes** (plural), NOT Axis. In Matplotlib terminology, an **Axes** object is a single graph or plot with its own 2D (or 3D) coordinate system. A Figure can have multiple Axes (e.g. a 2x2 grid of plots).\n",
"3. **The Axis (The Rulers / Number Lines):**\n",
" - The singular **Axis** (`ax.xaxis` and `ax.yaxis`). These are the mathematical rulers that define data limits, tick marks, tick labels, and axis titles.\n",
"4. **The Artists (Everything Visible on the Plot):**\n",
" - Every visible element on the plot is an **Artist**: lines, scatter dots, text labels, legend boxes, grid lines, colored patches, and title text.\n",
"\n",
"```\n",
"+-----------------------------------------------------------------------------------+\n",
"| FIGURE (The Canvas / Physical Window) |\n",
"| |\n",
"| +-----------------------------------------------------------------------------+ |\n",
"| | AXES (The Plot / Coordinate System) | |\n",
"| | | |\n",
"| | Title: \"Model Training Dynamics\" | |\n",
"| | +---------------------------------------------------------------------+ | |\n",
"| | | [ARTISTS: Data Points, Fitted Curves, Shaded Confidence Bands] | | |\n",
"| | Y | | | |\n",
"| | - | * (Scatter Dot Artist) | | |\n",
"| | A | \\ | | |\n",
"| | X | \\---- (Line2D Artist) | | |\n",
"| | I | \\ | | |\n",
"| | S | * | | |\n",
"| | +---------------------------------------------------------------------+ | |\n",
"| | X-AXIS (Major Ticks, Minor Ticks, Labels: 0, 10, 20, 30, ...) | |\n",
"| | SPINES (The 4 border frames: 'top', 'bottom', 'left', 'right') | |\n",
"| +-----------------------------------------------------------------------------+ |\n",
"+-----------------------------------------------------------------------------------+\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Matplotlib Version: 3.10.1\n",
"NumPy Version: 2.2.3\n",
"Pandas Version: 2.2.3\n",
"Figure object: Figure(800x400)\n",
"Axes object: Axes(0.125,0.11;0.775x0.77)\n",
"Number of Lines: 1\n",
"X-Axis limits: (-0.5, 10.5)\n"
]
}
],
"source": [
"import matplotlib as mpl\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pandas as pd\n",
"\n",
"print(f\"Matplotlib Version: {mpl.__version__}\")\n",
"print(f\"NumPy Version: {np.__version__}\")\n",
"print(f\"Pandas Version: {pd.__version__}\")\n",
"\n",
"# Create synthetic data\n",
"x = np.linspace(0, 10, 100)\n",
"y = np.sin(x)\n",
"\n",
"# 1. Create the Figure and Axes explicitly using the Object-Oriented API\n",
"fig, ax = plt.subplots(figsize=(8, 4), dpi=100)\n",
"\n",
"# 2. Draw Artists onto the Axes\n",
"line = ax.plot(x, y, color='#1f77b4', linewidth=2.5, label=r'$y = \\sin(x)$')\n",
"\n",
"# 3. Customize the Axes\n",
"ax.set_title(\"First Plot: Sine Wave (Object-Oriented Paradigm)\", fontsize=13, pad=10)\n",
"ax.set_xlabel(\"Time (seconds)\", fontsize=11)\n",
"ax.set_ylabel(\"Amplitude\", fontsize=11)\n",
"ax.grid(True, linestyle='--', alpha=0.6)\n",
"ax.legend(frameon=True, loc='upper right')\n",
"\n",
"# Inspect internal objects\n",
"print(f\"Figure object: {fig}\")\n",
"print(f\"Axes object: {ax}\")\n",
"print(f\"Number of Lines: {len(ax.lines)}\")\n",
"print(f\"X-Axis limits: {ax.get_xlim()}\")\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.2 The Two Interfaces: State-Based (`pyplot`) vs. Object-Oriented (OO)\n",
"Matplotlib historically provides two different paradigms:\n",
"\n",
"| Dimension | State-Based Interface (`plt.plot`) | Object-Oriented Interface (`ax.plot`) |\n",
"| :--- | :--- | :--- |\n",
"| **Origin** | Designed in 2003 to emulate MATLAB syntax | Native, idiomatic Python object architecture |\n",
"| **Syntax** | `plt.plot()`, `plt.title()`, `plt.xlabel()` | `fig, ax = plt.subplots()`, `ax.set_title()`, `ax.set_xlabel()` |\n",
"| **How it tracks plots** | Implicit global state (\"current active plot\") | Explicit Python object references (`fig`, `ax`) |\n",
"| **Multi-plot handling** | Fragile; easy to accidentally draw on wrong subplot | Rock-solid; you call methods directly on specific `ax` objects |\n",
"| **Best Used For** | Quick interactive 1-line sketches in terminal | **All production code, notebooks, data pipelines & publications** |\n",
"\n",
"> \ud83d\udca1 **The Golden Rule of Modern Matplotlib:**\n",
"> Always use the **Object-Oriented (OO) interface** (`fig, ax = plt.subplots()`). It makes your code modular, explicit, thread-safe, and painless to customize.\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with two explicitly targeted subplots\n"
]
}
],
"source": [
"# Comparison: Why Object-Oriented plotting avoids state confusion\n",
"x_pts = np.linspace(0, 5, 50)\n",
"y1 = np.exp(-0.5 * x_pts)\n",
"y2 = 1 - np.exp(-0.8 * x_pts)\n",
"\n",
"# Explicit Object-Oriented Approach\n",
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), dpi=100)\n",
"\n",
"# Explicitly command ax1\n",
"ax1.plot(x_pts, y1, color='#e27d60', linewidth=2)\n",
"ax1.set_title(\"Subplot 1: Exponential Decay\", fontweight='bold')\n",
"ax1.set_xlabel(\"Time (s)\")\n",
"ax1.set_ylabel(\"Signal\")\n",
"ax1.grid(True, linestyle=':', alpha=0.6)\n",
"\n",
"# Explicitly command ax2\n",
"ax2.plot(x_pts, y2, color='#41b3a3', linewidth=2)\n",
"ax2.set_title(\"Subplot 2: Saturation Curve\", fontweight='bold')\n",
"ax2.set_xlabel(\"Time (s)\")\n",
"ax2.set_ylabel(\"Charge\")\n",
"ax2.grid(True, linestyle=':', alpha=0.6)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.3 The Hierarchy of Artists\n",
"In Matplotlib, **every single pixel rendered on screen is an Artist**. Artists are organized into a strict container hierarchy:\n",
"- **Primitives:** Basic graphical shapes (`Line2D`, `Rectangle`, `Circle`, `Polygon`, `Text`).\n",
"- **Collections:** High-performance groups of primitives (e.g. `PathCollection` for scatter points, `LineCollection`).\n",
"- **Containers:** High-level groupings (`Figure`, `Axes`, `Axis`, `Tick`).\n",
"\n",
"When you call `ax.plot()`, Matplotlib creates a `Line2D` artist and appends it to `ax.lines`.\n",
"When you call `ax.bar()`, Matplotlib creates a container of `Rectangle` patches in `ax.patches`.\n",
"You can programmatically query and modify any artist at runtime!\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"=== Inspected Artists on Axes ===\n",
"Lines: []\n",
"Texts: ['Data Point']\n",
"Patches: []\n",
"Collections: []\n"
]
}
],
"source": [
"fig, ax = plt.subplots(figsize=(6, 3), dpi=100)\n",
"\n",
"# Draw a line, a text annotation, and a patch\n",
"ax.plot([1, 2, 3], [4, 5, 6], label='Test Line')\n",
"ax.text(1.5, 4.5, \"Data Point\", fontsize=10)\n",
"rect = mpl.patches.Rectangle((2, 4), 0.8, 1.2, facecolor='orange', alpha=0.3)\n",
"ax.add_patch(rect)\n",
"\n",
"print(\"=== Inspected Artists on Axes ===\")\n",
"print(\"Lines: \", ax.lines)\n",
"print(\"Texts: \", [t.get_text() for t in ax.texts])\n",
"print(\"Patches: \", ax.patches)\n",
"print(\"Collections:\", ax.collections)\n",
"\n",
"plt.close(fig)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 2. Creating Figures, Subplots & Layouts\n",
"\n",
"A complex analysis is rarely conveyed with a single isolated chart. Professional reports and research papers require **multi-panel figure layouts** (e.g. raw signal vs filtered spectrum, loss curve vs accuracy curve, or side-by-side model comparisons).\n",
"\n",
"---\n",
"\n",
"### 2.1 Anatomy of `plt.subplots()`\n",
"The primary workhorse for creating layouts in modern Matplotlib is `plt.subplots()`.\n",
"\n",
"```python\n",
"fig, ax = plt.subplots(\n",
" nrows=1, ncols=1, # Grid dimensions (rows, columns)\n",
" figsize=(10, 6), # Figure dimensions in INCHES (width, height)\n",
" dpi=100, # Dots Per Inch (display resolution)\n",
" sharex=False, # Share X-axis limits & ticks across subplots\n",
" sharey=False, # Share Y-axis limits & ticks across subplots\n",
" layout='constrained' # Modern automatic margin & label spacing engine\n",
")\n",
"```\n",
"\n",
"- **Figure Size in Inches:** `figsize=(width, height)`. Matplotlib measures canvas dimensions in physical inches, which makes sizing for journal columns (e.g. 3.5 inches single-column or 7.0 inches double-column) predictable.\n",
"- **Resolution (DPI):** Dots Per Inch determines total pixel dimensions: $\\text{pixels} = \\text{inches} \\times \\text{DPI}$. For example, $(8, 5) \\text{ at } 100 \\text{ DPI} = 800 \\times 500 \\text{ pixels}$.\n",
"\n",
"### 2.2 Subplots Grids (1D and 2D Arrays of Axes)\n",
"When `nrows * ncols > 1`, `plt.subplots()` returns an **ndarray of Axes objects**:\n",
"- If `nrows=1` or `ncols=1`: `axs` is a 1D NumPy array `[ax0, ax1, ...]`.\n",
"- If `nrows > 1` and `ncols > 1`: `axs` is a 2D NumPy array indexed by `axs[row, col]`.\n",
"\n",
"```\n",
" SUBPLOT GRID 2x3 INDEXING\n",
" Col 0 Col 1 Col 2\n",
" +----------------------+----------------------+----------------------+\n",
" R 0 | axs[0, 0] | axs[0, 1] | axs[0, 2] |\n",
" +----------------------+----------------------+----------------------+\n",
" R 1 | axs[1, 0] | axs[1, 1] | axs[1, 2] |\n",
" +----------------------+----------------------+----------------------+\n",
" \n",
" \ud83d\udca1 Pro-Tip: Flattening 2D Grids for Clean Loops:\n",
" axs_flat = axs.flatten() # 1D array of length 6: [axs[0,0], axs[0,1], ..., axs[1,2]]\n",
" for i, ax in enumerate(axs.flatten()):\n",
" ax.plot(...)\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Shape of axs array: (2, 2) (Type: )\n"
]
}
],
"source": [
"# Create a 2x2 multi-panel layout\n",
"fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(10, 7), dpi=100, layout='constrained')\n",
"\n",
"print(f\"Shape of axs array: {axs.shape} (Type: {type(axs)})\")\n",
"\n",
"t = np.linspace(0, 5, 200)\n",
"signals = [\n",
" (np.sin(2 * np.pi * t), \"Sine Wave (1 Hz)\", \"#1f77b4\"),\n",
" (np.cos(2 * np.pi * t), \"Cosine Wave (1 Hz)\", \"#ff7f0e\"),\n",
" (np.exp(-0.8 * t) * np.sin(4 * np.pi * t), \"Damped Oscillator\", \"#2ca02c\"),\n",
" (np.sign(np.sin(2 * np.pi * t)), \"Square Wave\", \"#d62728\")\n",
"]\n",
"\n",
"# Iterate through flattened axes effortlessly\n",
"for i, ax in enumerate(axs.flatten()):\n",
" y_data, title, color = signals[i]\n",
" ax.plot(t, y_data, color=color, linewidth=2)\n",
" ax.set_title(title, fontsize=11, fontweight='semibold')\n",
" ax.set_xlabel(\"Time (s)\", fontsize=9)\n",
" ax.set_ylabel(\"Amplitude\", fontsize=9)\n",
" ax.grid(True, linestyle=':', alpha=0.7)\n",
"\n",
"# Add an overarching Figure Title (Suptitle)\n",
"fig.suptitle(\"Signal Processing Multi-Panel Dashboard\", fontsize=14, fontweight='bold')\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.3 Shared Axes: Eliminating Redundant Tick Labels\n",
"When plotting multiple signals or features that share the same domain (e.g. time, frequency, or categories), setting `sharex=True` or `sharey=True` ensures:\n",
"1. Zooming or panning one subplot automatically updates all linked subplots.\n",
"2. Matplotlib automatically hides redundant inner tick labels, maximizing plot area!\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with vertically stacked subplots sharing X-axis\n"
]
}
],
"source": [
"time = np.linspace(0, 10, 150)\n",
"sensor_accel = np.sin(time) + np.random.normal(0, 0.1, 150)\n",
"sensor_gyro = np.cos(time * 1.5) + np.random.normal(0, 0.15, 150)\n",
"\n",
"# Create 2 vertically stacked subplots sharing the exact same X-axis\n",
"fig, (ax_top, ax_bot) = plt.subplots(nrows=2, ncols=1, figsize=(8, 5), sharex=True, layout='constrained')\n",
"\n",
"ax_top.plot(time, sensor_accel, color='#2b5c8f', linewidth=2)\n",
"ax_top.set_title(\"Inertial Measurement Unit (IMU) Telemetry\", fontweight='bold')\n",
"ax_top.set_ylabel(\"Accelerometer (g)\")\n",
"ax_top.grid(True, linestyle=':', alpha=0.6)\n",
"\n",
"ax_bot.plot(time, sensor_gyro, color='#d95f02', linewidth=2)\n",
"ax_bot.set_xlabel(\"Timestamp (seconds)\", fontweight='semibold')\n",
"ax_bot.set_ylabel(\"Gyroscope (rad/s)\")\n",
"ax_bot.grid(True, linestyle=':', alpha=0.6)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.4 Complex & Irregular Layouts: `subplot_mosaic`\n",
"What if your dashboard needs an asymmetrical design\u2014like one large main plot on the left and two stacked smaller diagnostic plots on the right?\n",
"Historically, this required cumbersome `GridSpec` slice math. Modern Matplotlib introduces **`plt.subplot_mosaic()`**, which allows you to define complex layouts using an intuitive ASCII visual blueprint!\n",
"\n",
"```\n",
" MOSAIC VISUAL SPECIFICATION\n",
" mosaic = [\n",
" [\"main\", \"diag_top\"],\n",
" [\"main\", \"diag_bottom\"]\n",
" ]\n",
" \n",
" +---------------------------+---------------------------+\n",
" | | diag_top |\n",
" | | |\n",
" | main +---------------------------+\n",
" | | diag_bottom |\n",
" | | |\n",
" +---------------------------+---------------------------+\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Axes dictionary keys created: ['scatter_main', 'hist_y', 'loss_curve']\n"
]
}
],
"source": [
"# Define an irregular multi-panel dashboard blueprint\n",
"mosaic_blueprint = [\n",
" [\"scatter_main\", \"hist_y\"],\n",
" [\"scatter_main\", \"loss_curve\"]\n",
"]\n",
"\n",
"fig, ax_dict = plt.subplot_mosaic(\n",
" mosaic_blueprint,\n",
" figsize=(11, 5.5),\n",
" layout='constrained',\n",
" gridspec_kw={'width_ratios': [2, 1], 'height_ratios': [1, 1]}\n",
")\n",
"\n",
"print(\"Axes dictionary keys created:\", list(ax_dict.keys()))\n",
"\n",
"# Generate synthetic dataset\n",
"rng = np.random.default_rng(42)\n",
"x_data = rng.normal(loc=5, scale=2, size=300)\n",
"y_data = 1.5 * x_data + rng.normal(loc=0, scale=1.5, size=300)\n",
"\n",
"# 1. Main large plot (Left)\n",
"ax_dict['scatter_main'].scatter(x_data, y_data, alpha=0.6, color='#2b5c8f', edgecolors='none', s=35)\n",
"ax_dict['scatter_main'].set_title(\"Primary Feature Correlation (Large View)\", fontweight='bold')\n",
"ax_dict['scatter_main'].set_xlabel(\"Feature X\")\n",
"ax_dict['scatter_main'].set_ylabel(\"Target Y\")\n",
"ax_dict['scatter_main'].grid(True, linestyle='--', alpha=0.5)\n",
"\n",
"# 2. Top-right plot: Target Distribution\n",
"ax_dict['hist_y'].hist(y_data, bins=20, color='#e27d60', edgecolor='white', alpha=0.85)\n",
"ax_dict['hist_y'].set_title(\"Target Distribution\", fontsize=10)\n",
"ax_dict['hist_y'].grid(True, linestyle=':', alpha=0.5)\n",
"\n",
"# 3. Bottom-right plot: Optimization Convergence\n",
"epochs = np.arange(1, 31)\n",
"simulated_loss = 2.5 * np.exp(-epochs / 8) + rng.normal(0, 0.04, 30)\n",
"ax_dict['loss_curve'].plot(epochs, simulated_loss, color='#41b3a3', linewidth=2)\n",
"ax_dict['loss_curve'].set_title(\"Model Convergence\", fontsize=10)\n",
"ax_dict['loss_curve'].set_xlabel(\"Epoch\", fontsize=8)\n",
"ax_dict['loss_curve'].grid(True, linestyle=':', alpha=0.5)\n",
"\n",
"fig.suptitle(\"Asymmetric Analytical Dashboard via subplot_mosaic()\", fontsize=13, fontweight='bold')\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.5 Saving Figures to Disk with `savefig`\n",
"When saving figures for papers, websites, or reports, never take a screenshot of your screen! Use `fig.savefig()` with production parameters:\n",
"\n",
"```python\n",
"fig.savefig(\n",
" \"figure_name.png\", # File extension determines file format (.png, .pdf, .svg)\n",
" dpi=300, # 300 DPI for print/papers, 100-150 for web\n",
" bbox_inches='tight', # Automatically crops awkward blank white margins\n",
" transparent=False, # Set True for transparent slide decks / dark web apps\n",
" facecolor='white' # Ensures clean white background in paper submissions\n",
")\n",
"```\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Successfully saved 'revenue_quarterly.png'! File size: 14.85 KB\n"
]
}
],
"source": [
"fig, ax = plt.subplots(figsize=(6, 3), dpi=100)\n",
"ax.plot([1, 2, 3, 4], [10, 25, 20, 35], marker='o', color='#333333')\n",
"ax.set_title(\"Publication Ready Demonstration\")\n",
"ax.set_xlabel(\"Quarter\")\n",
"ax.set_ylabel(\"Revenue ($k)\")\n",
"\n",
"output_filename = \"revenue_quarterly.png\"\n",
"fig.savefig(output_filename, dpi=150, bbox_inches='tight')\n",
"\n",
"import os\n",
"file_size_kb = os.path.getsize(output_filename) / 1024\n",
"print(f\"Successfully saved '{output_filename}'! File size: {file_size_kb:.2f} KB\")\n",
"\n",
"os.remove(output_filename)\n",
"plt.close(fig)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4 Demystifying Matplotlib's 4 Coordinate Systems\n",
"A frequent source of confusion when adding text, shapes, or annotations is understanding **which coordinate system** you are operating in:\n",
"\n",
"```\n",
"+-----------------------------------------------------------------------------------+\n",
"| 1. Data Coordinates (ax.transData) [DEFAULT] |\n",
"| * Uses the exact units of your data (e.g. X=1995, Y=45.2). |\n",
"| * If you pan or zoom the plot, objects move along with the data. |\n",
"+-----------------------------------------------------------------------------------+\n",
"| 2. Axes Coordinates (ax.transAxes) |\n",
"| * Normalized from (0, 0) at bottom-left of plot to (1, 1) at top-right. |\n",
"| * Does NOT change when data limits change! Perfect for plot titles & labels. |\n",
"+-----------------------------------------------------------------------------------+\n",
"| 3. Figure Coordinates (fig.transFigure) |\n",
"| * Normalized from (0, 0) at bottom-left of entire window to (1, 1) top-right. |\n",
"| * Perfect for multi-plot suptitles, corporate watermarks, and figure legends. |\n",
"+-----------------------------------------------------------------------------------+\n",
"| 4. Display / Pixel Coordinates (None) |\n",
"| * Raw physical screen pixels (0, 0) to (width, height). |\n",
"+-----------------------------------------------------------------------------------+\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered showing text in transData, transAxes, and transFigure coordinates\n"
]
}
],
"source": [
"fig, ax = plt.subplots(figsize=(8, 4), dpi=100)\n",
"ax.plot([10, 20, 30], [100, 200, 300], color='#2b5c8f')\n",
"\n",
"# 1. Text in Data Coordinates\n",
"ax.text(20, 200, \" (Data: x=20, y=200)\", transform=ax.transData,\n",
" color='blue', fontweight='bold')\n",
"\n",
"# 2. Text in Axes Coordinates (Pinned to Top-Left of this Axes)\n",
"ax.text(0.05, 0.90, \"Axes Top-Left (0.05, 0.90)\", transform=ax.transAxes,\n",
" color='darkgreen', fontweight='bold', bbox=dict(boxstyle='square', facecolor='lightgreen', alpha=0.3))\n",
"\n",
"# 3. Text in Figure Coordinates (Pinned to Bottom-Right of canvas)\n",
"fig.text(0.95, 0.03, \"Watermark: Antigravity Lab\", transform=fig.transFigure,\n",
" color='gray', ha='right', fontsize=9, style='italic')\n",
"\n",
"ax.set_title(\"Matplotlib Coordinate Transformations Visualized\", fontweight='bold')\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.5 Low-Level Grid Control with `matplotlib.gridspec.GridSpec`\n",
"While `plt.subplots()` creates uniform grids and `subplot_mosaic()` provides high-level layouts, **`GridSpec`** gives you low-level surgical control over subplots spanning arbitrary rows and columns with custom width and height ratios.\n"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with complex GridSpec layout with custom width and height ratios\n"
]
}
],
"source": [
"import matplotlib.gridspec as gridspec\n",
"\n",
"fig = plt.figure(figsize=(10, 5), dpi=100, layout='constrained')\n",
"gs = gridspec.GridSpec(nrows=2, ncols=3, figure=fig, width_ratios=[1, 2, 1], height_ratios=[2, 1])\n",
"\n",
"# Large central plot spanning row 0, cols 1 to 3\n",
"ax_main = fig.add_subplot(gs[0, 1:3])\n",
"ax_main.plot(np.sin(np.linspace(0, 10, 100)), color='#2b5c8f', lw=2)\n",
"ax_main.set_title(\"Wide Feature Analyzer (gs[0, 1:3])\", fontweight='bold')\n",
"\n",
"# Tall side plot spanning rows 0 and 1 in column 0\n",
"ax_side = fig.add_subplot(gs[:, 0])\n",
"ax_side.barh(['A', 'B', 'C', 'D'], [10, 25, 15, 30], color='#e27d60')\n",
"ax_side.set_title(\"Sidebar (gs[:, 0])\", fontweight='bold')\n",
"\n",
"# Small bottom plot spanning row 1, col 1\n",
"ax_bot1 = fig.add_subplot(gs[1, 1])\n",
"ax_bot1.hist(np.random.normal(0, 1, 200), color='#41b3a3', edgecolor='white')\n",
"ax_bot1.set_title(\"gs[1, 1]\", fontsize=9)\n",
"\n",
"# Small bottom plot spanning row 1, col 2\n",
"ax_bot2 = fig.add_subplot(gs[1, 2])\n",
"ax_bot2.scatter(np.random.rand(30), np.random.rand(30), color='#f46d43', s=20)\n",
"ax_bot2.set_title(\"gs[1, 2]\", fontsize=9)\n",
"\n",
"fig.suptitle(\"Asymmetric Multi-Panel Layout via GridSpec\", fontsize=13, fontweight='bold')\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"# Part II: Essential Plot Types for Data Science & Machine Learning\n",
"\n",
"## 3. Line Plots & Time Series\n",
"\n",
"Line plots are the bedrock of scientific computing and machine learning. They are the ideal choice whenever data possesses a continuous ordering: time series, epoch training dynamics, financial stock tickers, or mathematical curve approximations.\n",
"\n",
"---\n",
"\n",
"### 3.1 Line Styling: Linestyles, Linewidths & Colors\n",
"The basic signature is `ax.plot(x, y, [fmt], **kwargs)`. You can configure styling explicitly or via format strings:\n",
"\n",
"| Property | Keyword | Options / Examples |\n",
"| :--- | :--- | :--- |\n",
"| **Color** | `color` or `c` | `'#1f77b4'`, `'navy'`, `'red'`, `'0.5'`, `(0.1, 0.2, 0.5)` |\n",
"| **Linestyle** | `linestyle` or `ls` | `'-'` (solid), `'--'` (dashed), `':'` (dotted), `'-.'` (dash-dot), `'none'` |\n",
"| **Linewidth** | `linewidth` or `lw` | Float in points (e.g., `1.5`, `2.5`, `3.0`) |\n",
"| **Transparency** | `alpha` | Float between `0.0` (invisible) and `1.0` (opaque) |\n",
"| **Label** | `label` | String for the legend (supports LaTeX: `r'$\\hat{y}$'`) |\n"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with ground truth and model forecast curves\n"
]
}
],
"source": [
"days = np.arange(1, 15)\n",
"actual_temp = np.array([18.2, 19.1, 21.0, 20.4, 22.5, 25.0, 24.1, 23.0, 21.8, 20.0, 19.5, 22.0, 23.5, 24.8])\n",
"forecast_a = actual_temp + np.sin(days / 2.0) * 1.5\n",
"forecast_b = actual_temp + np.cos(days / 3.0) * 2.2\n",
"\n",
"fig, ax = plt.subplots(figsize=(9, 4.5), dpi=100)\n",
"\n",
"# Ground truth line\n",
"ax.plot(days, actual_temp, color='#111111', linestyle='-', linewidth=2.2,\n",
" marker='o', markersize=6, markerfacecolor='white', markeredgewidth=2,\n",
" label='Ground Truth (Sensor)', zorder=3)\n",
"\n",
"# Model forecasts with dashed and dash-dot styles\n",
"ax.plot(days, forecast_a, color='#2b5c8f', linestyle='--', linewidth=2.0,\n",
" marker='s', markersize=5, alpha=0.85, label='ARIMA Forecast')\n",
"ax.plot(days, forecast_b, color='#d95f02', linestyle='-.', linewidth=2.0,\n",
" marker='^', markersize=5, alpha=0.85, label='LSTM Neural Net')\n",
"\n",
"ax.set_title(\"Temperature Forecast Comparison: Sensor vs ML Models\", fontsize=12, fontweight='bold', pad=12)\n",
"ax.set_xlabel(\"Observation Day\", fontsize=10)\n",
"ax.set_ylabel(\"Temperature (\u00b0C)\", fontsize=10)\n",
"ax.set_xticks(days)\n",
"ax.grid(True, linestyle=':', alpha=0.6)\n",
"ax.legend(frameon=True, facecolor='white', framealpha=0.9, loc='upper left')\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.2 Shaded Uncertainty Bands (`ax.fill_between`)\n",
"In machine learning, plotting a single point estimate (mean prediction) without showing uncertainty is dangerous. Matplotlib provides **`ax.fill_between(x, y1, y2)`** to shade the region between two curves (e.g. 95% confidence intervals or variance bounds).\n",
"\n",
"---\n",
"\n",
"### 3.3 Step Plots (`ax.step`) for Discrete Events\n",
"When plotting discrete event state changes (e.g. inventory counts, packet arrivals, or survival curves), standard line plots mistakenly draw diagonal slopes between discrete states. **`ax.step()`** preserves horizontal plateaus with instantaneous vertical jumps!\n"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with continuous confidence bands and discrete step plot\n"
]
}
],
"source": [
"time = np.linspace(0, 10, 100)\n",
"mean_signal = np.sin(time)\n",
"noise_std = 0.2 + 0.05 * time\n",
"\n",
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.5), dpi=100, layout='constrained')\n",
"\n",
"# 1. Shaded Confidence Band (Mean \u00b1 2*STD)\n",
"ax1.plot(time, mean_signal, color='#1f77b4', linewidth=2, label=r'Mean $\\mu(t)$')\n",
"ax1.fill_between(time, mean_signal - 2*noise_std, mean_signal + 2*noise_std,\n",
" color='#1f77b4', alpha=0.2, label=r'95% Uncertainty ($\\mu \\pm 2\\sigma$)')\n",
"ax1.set_title(\"Continuous Signal with Shaded Uncertainty\", fontweight='bold')\n",
"ax1.set_xlabel(\"Time (s)\")\n",
"ax1.set_ylabel(\"Amplitude\")\n",
"ax1.grid(True, linestyle=':', alpha=0.5)\n",
"ax1.legend(loc='lower left')\n",
"\n",
"# 2. Step Plot for Discrete State Transitions\n",
"discrete_time = np.arange(0, 10)\n",
"server_active_nodes = np.array([3, 3, 5, 5, 8, 8, 8, 4, 4, 2])\n",
"ax2.step(discrete_time, server_active_nodes, where='post', color='#2ca02c', linewidth=2.5, label='Active Worker Pods')\n",
"ax2.set_title(\"Step Plot: Discrete Kubernetes Cluster Autoscaling\", fontweight='bold')\n",
"ax2.set_xlabel(\"Hour of Day\")\n",
"ax2.set_ylabel(\"Running Worker Nodes\")\n",
"ax2.grid(True, linestyle=':', alpha=0.5)\n",
"ax2.legend(loc='upper right')\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.4 Dual Y-Axes with `ax.twinx()`\n",
"Frequently, you need to plot two variables that share the same X-axis (e.g. Time) but have completely different physical units or scales (e.g. **Website Visits [thousands]** vs **Conversion Rate [%]**).\n",
"- Calling `ax2 = ax.twinx()` creates a second independent Axes sharing the same X-axis coordinates while placing a new independent Y-axis on the right!\n",
"\n",
"---\n",
"\n",
"### 3.5 Inset Zoom Axes (`ax.inset_axes`)\n",
"When a specific anomaly, spike, or inflection point is subtle, you can embed an **inset zoom box** directly inside your main plot!\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with dual Y-axes, unified legend, and inset zoom box\n"
]
}
],
"source": [
"# 1. Twin Axes demonstration\n",
"timeline = np.arange(1, 25)\n",
"traffic = 10000 + 400 * timeline + np.random.normal(0, 300, 24)\n",
"conv_rate = 2.8 + 0.6 * np.sin(timeline / 3.0)\n",
"\n",
"fig, ax1 = plt.subplots(figsize=(9, 4.8), dpi=100)\n",
"\n",
"l1 = ax1.plot(timeline, traffic, color='#2b5c8f', linewidth=2.5, label='Web Traffic (Sessions)')\n",
"ax1.set_xlabel(\"Day of Month\", fontsize=10)\n",
"ax1.set_ylabel(\"Sessions\", color='#2b5c8f', fontsize=10, fontweight='bold')\n",
"ax1.tick_params(axis='y', labelcolor='#2b5c8f')\n",
"ax1.grid(True, linestyle=':', alpha=0.5)\n",
"\n",
"ax2 = ax1.twinx()\n",
"l2 = ax2.plot(timeline, conv_rate, color='#d95f02', linewidth=2.2, linestyle='--',\n",
" marker='s', markersize=4, label='Conversion Rate (%)')\n",
"ax2.set_ylabel(\"Conversion Rate (%)\", color='#d95f02', fontsize=10, fontweight='bold')\n",
"ax2.tick_params(axis='y', labelcolor='#d95f02')\n",
"\n",
"# Combine legends into a single unified box\n",
"lines = l1 + l2\n",
"labels = [l.get_label() for l in lines]\n",
"ax1.legend(lines, labels, loc='upper left', frameon=True)\n",
"\n",
"# Inset zoom onto days 10-15\n",
"ax_ins = ax1.inset_axes([0.45, 0.15, 0.35, 0.35])\n",
"ax_ins.plot(timeline, traffic, color='#2b5c8f', marker='o')\n",
"ax_ins.set_xlim(10, 15)\n",
"ax_ins.set_ylim(traffic[9] - 200, traffic[14] + 200)\n",
"ax_ins.set_title(\"Zoom: Days 10-15\", fontsize=8)\n",
"ax1.indicate_inset_zoom(ax_ins, edgecolor=\"black\")\n",
"\n",
"ax1.set_title(\"Web Traffic vs Conversion Rate Dynamics (with Inset Zoom)\", fontsize=11, fontweight='bold')\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 4. Scatter Plots & Multi-Dimensional Mapping\n",
"\n",
"A **scatter plot** displays individual observations as discrete points. While a line plot implies a continuous connection between adjacent values, a scatter plot is designed to reveal **correlations, bivariate distributions, clusters, and outliers**.\n",
"\n",
"---\n",
"\n",
"### 4.1 Multi-Dimensional Mapping: 4D on a 2D Canvas!\n",
"One of Matplotlib's most powerful capabilities is encoding up to **four distinct data dimensions** onto a flat 2D canvas simultaneously:\n",
"1. **X-Position:** Continuous Variable 1 (e.g. Engine Horsepower)\n",
"2. **Y-Position:** Continuous Variable 2 (e.g. Fuel Efficiency / MPG)\n",
"3. **Marker Color (`c`):** Continuous Variable 3 mapped through a Colormap (e.g. Vehicle Price ($))\n",
"4. **Marker Size (`s`):** Continuous Variable 4 mapped to pixel area (e.g. Curb Weight in kg)\n",
"\n",
"```\n",
" 4D MAPPING VISUALIZATION\n",
" Y (MPG)\n",
" ^ o (Small size = Light weight)\n",
" | /\n",
" | O (Warm color = Expensive price)\n",
" | /\n",
" | O\n",
" | /\n",
" | o\n",
" +-----------------------------------> X (Horsepower)\n",
" Marker Color = Price ($) | Marker Area = Weight (kg)\n",
"```\n",
"\n",
"### 4.2 Adding and Styling Colorbars (`fig.colorbar`)\n",
"When using continuous color mapping (`c=...`), you must always provide a **Colorbar** so the reader can decode what each hue signifies.\n"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with 4-dimensional scatter mapping, colorbar, and size legend\n"
]
}
],
"source": [
"rng = np.random.default_rng(101)\n",
"n_cars = 120\n",
"\n",
"horsepower = rng.uniform(80, 350, n_cars)\n",
"mpg = 50 - 0.1 * horsepower + rng.normal(0, 3, n_cars)\n",
"price_k = 15 + 0.18 * horsepower + rng.normal(0, 8, n_cars)\n",
"weight_kg = 1000 + 4.5 * horsepower + rng.normal(0, 100, n_cars)\n",
"marker_sizes = 25 + 225 * ((weight_kg - weight_kg.min()) / (weight_kg.max() - weight_kg.min()))\n",
"\n",
"fig, ax = plt.subplots(figsize=(9, 5.5), dpi=100)\n",
"\n",
"scatter = ax.scatter(\n",
" horsepower, mpg,\n",
" c=price_k,\n",
" s=marker_sizes,\n",
" cmap='viridis',\n",
" alpha=0.8,\n",
" edgecolors='black',\n",
" linewidths=0.7\n",
")\n",
"\n",
"ax.set_title(\"Automotive Dataset: Horsepower vs. MPG (Color=Price, Size=Weight)\", fontsize=12, fontweight='bold', pad=12)\n",
"ax.set_xlabel(\"Engine Power (Horsepower)\", fontsize=10)\n",
"ax.set_ylabel(\"Fuel Efficiency (Miles Per Gallon)\", fontsize=10)\n",
"ax.grid(True, linestyle='--', alpha=0.5)\n",
"\n",
"cbar = fig.colorbar(scatter, ax=ax, pad=0.02)\n",
"cbar.set_label(\"Vehicle Price ($k USD)\", fontsize=10, fontweight='semibold')\n",
"\n",
"for demo_weight, demo_size in [(1200, 40), (1800, 130), (2400, 230)]:\n",
" ax.scatter([], [], c='gray', alpha=0.6, s=demo_size, edgecolors='black',\n",
" label=f'{demo_weight} kg')\n",
"ax.legend(title=\"Curb Weight\", loc='upper right', frameon=True)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4.3 Categorical Scatter Plots & Random Jittering\n",
"When one axis is discrete (e.g. Class 0, 1, 2), data points stack exactly on top of each other, completely hiding point density.\n",
"Adding **random jitter** (small uniform random noise) along the categorical axis disperses the points so the true distribution becomes instantly visible!\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered showing side-by-side comparison of raw vs jittered scatter points\n"
]
}
],
"source": [
"categories = ['Low Risk', 'Medium Risk', 'High Risk']\n",
"credit_scores = [\n",
" rng.normal(740, 30, 80),\n",
" rng.normal(660, 40, 80),\n",
" rng.normal(580, 50, 80)\n",
"]\n",
"\n",
"fig, (ax_raw, ax_jit) = plt.subplots(1, 2, figsize=(11, 4.5), dpi=100, layout='constrained')\n",
"\n",
"# 1. Raw overlapping points (Overplotting problem)\n",
"for idx, scores in enumerate(credit_scores):\n",
" ax_raw.scatter(np.repeat(idx, len(scores)), scores, alpha=0.5, color='#2b5c8f', edgecolors='none')\n",
"ax_raw.set_title(\"Without Jitter: Severe Overplotting\", fontweight='bold')\n",
"ax_raw.set_xticks([0, 1, 2])\n",
"ax_raw.set_xticklabels(categories)\n",
"ax_raw.set_ylabel(\"Credit Score\")\n",
"ax_raw.grid(axis='y', linestyle=':', alpha=0.6)\n",
"\n",
"# 2. With horizontal jitter\n",
"for idx, scores in enumerate(credit_scores):\n",
" jitter = rng.uniform(-0.15, 0.15, len(scores))\n",
" ax_jit.scatter(idx + jitter, scores, alpha=0.6, color='#d95f02', edgecolors='black', linewidths=0.5)\n",
"ax_jit.set_title(\"With Jitter: True Density Revealed\", fontweight='bold')\n",
"ax_jit.set_xticks([0, 1, 2])\n",
"ax_jit.set_xticklabels(categories)\n",
"ax_jit.set_ylabel(\"Credit Score\")\n",
"ax_jit.grid(axis='y', linestyle=':', alpha=0.6)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 5. Bar Charts & Categorical Comparisons\n",
"\n",
"Bar charts compare numerical metrics across discrete, categorical groups (e.g. Sales by Department, Model Accuracy across Algorithms, or Revenue by Country).\n",
"\n",
"---\n",
"\n",
"### 5.1 Vertical (`ax.bar`) vs. Horizontal (`ax.barh`) Charts\n",
"- **Vertical Bar Charts (`ax.bar`):** The standard format. Works best when you have 3 to 8 categories with short labels.\n",
"- **Horizontal Bar Charts (`ax.barh`):** **Far superior** when you have many categories (10+) or long category names (e.g. \"Support Vector Classifier with RBF Kernel\"). Labels are printed horizontally and can be read naturally from left to right without neck-straining rotations!\n",
"\n",
"### 5.2 Grouped / Clustered Bar Charts\n",
"When you want to compare multiple metrics across the same categories (e.g. **Train Accuracy** vs **Test Accuracy**), you must calculate coordinate offsets:\n",
"```\n",
"Category i:\n",
" [ Bar 1: x - width/2 ] [ Bar 2: x + width/2 ]\n",
"```\n",
"\n",
"### 5.3 Modern Direct Labeling with `ax.bar_label()`\n",
"Never make your readers guess bar heights from a distant axis ruler! Modern Matplotlib (v3.4+) includes **`ax.bar_label()`** to automatically stamp exact formatted numbers directly onto the bars.\n"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with grouped bars and direct numerical labels\n"
]
}
],
"source": [
"models = ['LogReg', 'Random Forest', 'Gradient Boost', 'SVM (RBF)', 'LightGBM']\n",
"train_acc = np.array([84.2, 99.4, 96.8, 91.5, 98.1])\n",
"test_acc = np.array([82.5, 89.2, 92.4, 88.0, 94.3])\n",
"\n",
"x_positions = np.arange(len(models))\n",
"bar_width = 0.35\n",
"\n",
"fig, ax = plt.subplots(figsize=(10, 5), dpi=100)\n",
"\n",
"rects1 = ax.bar(x_positions - bar_width/2, train_acc, width=bar_width,\n",
" color='#2b5c8f', label='Train Accuracy', edgecolor='black', linewidth=0.5)\n",
"rects2 = ax.bar(x_positions + bar_width/2, test_acc, width=bar_width,\n",
" color='#e27d60', label='Test Accuracy (Generalization)', edgecolor='black', linewidth=0.5)\n",
"\n",
"# Labeling bars directly with percentage formatting\n",
"ax.bar_label(rects1, fmt='%.1f%%', padding=3, fontsize=9)\n",
"ax.bar_label(rects2, fmt='%.1f%%', padding=3, fontsize=9, fontweight='bold')\n",
"\n",
"ax.set_title(\"Model Benchmarking: Training vs. Validation Accuracy\", fontsize=12, fontweight='bold', pad=14)\n",
"ax.set_ylabel(\"Accuracy Score (%)\", fontsize=10)\n",
"ax.set_ylim(70, 105)\n",
"ax.set_xticks(x_positions)\n",
"ax.set_xticklabels(models, fontsize=10, fontweight='medium')\n",
"ax.grid(axis='y', linestyle=':', alpha=0.7)\n",
"ax.legend(loc='lower right', frameon=True)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 5.4 Stacked Bar Charts (`bottom` and `left` parameters)\n",
"Stacked bar charts visualize part-to-whole compositions across categories. By passing the cumulative sum of earlier bars to the `bottom` (or `left` for horizontal bars) parameter, segments stack seamlessly!\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with horizontal stacked bars and inverted y-axis\n"
]
}
],
"source": [
"countries = ['Germany', 'USA', 'China', 'India', 'UK', 'Japan']\n",
"renewable = np.array([45, 22, 31, 21, 40, 19])\n",
"fossil_fuel = np.array([35, 60, 55, 72, 42, 65])\n",
"nuclear = np.array([5, 18, 14, 7, 18, 16])\n",
"\n",
"fig, ax = plt.subplots(figsize=(9, 4.8), dpi=100)\n",
"\n",
"y_indices = np.arange(len(countries))\n",
"height = 0.55\n",
"\n",
"p1 = ax.barh(y_indices, renewable, height=height, label='Renewables (Wind/Solar/Hydro)', color='#2ca02c')\n",
"p2 = ax.barh(y_indices, nuclear, height=height, left=renewable, label='Nuclear', color='#ff7f0e')\n",
"p3 = ax.barh(y_indices, fossil_fuel, height=height, left=renewable + nuclear, label='Fossil Fuels', color='#7f7f7f')\n",
"\n",
"ax.set_yticks(y_indices)\n",
"ax.set_yticklabels(countries, fontsize=10)\n",
"ax.invert_yaxis()\n",
"ax.set_xlabel(\"Energy Mix Share (%)\", fontsize=10)\n",
"ax.set_title(\"National Electricity Generation Portfolios (Stacked Horizontal View)\", fontsize=12, fontweight='bold')\n",
"ax.legend(loc='upper right', bbox_to_anchor=(1.0, 1.15), ncol=3, frameon=False, fontsize=9)\n",
"ax.grid(axis='x', linestyle='--', alpha=0.5)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 6. Histograms & Density Distributions\n",
"\n",
"A **histogram** reveals the underlying probability distribution of a continuous variable by grouping values into discrete bins and plotting count frequencies.\n",
"\n",
"---\n",
"\n",
"### 6.1 Binning Strategies\n",
"The shape of a histogram depends entirely on the chosen bin count:\n",
"- **Too few bins (Under-binning):** Oversimplifies data; masks multi-modal peaks.\n",
"- **Too many bins (Over-binning):** Turns smooth distributions into jagged, noisy combs.\n",
"- **Matplotlib's automated bin algorithms:** Instead of guessing a number like `bins=10`, pass an optimization algorithm string:\n",
" - `'auto'`: Maximum of Freedman-Diaconis and Sturges estimators.\n",
" - `'fd'` (Freedman-Diaconis): Resilient to outliers; uses the Interquartile Range (IQR).\n",
" - `'sturges'`: Best for simple, Gaussian-like data.\n",
"\n",
"### 6.2 Counts vs Probability Density (`density=True`)\n",
"- When `density=False` (default): The Y-axis shows the raw count of data points inside each bin.\n",
"- When `density=True`: The Y-axis is normalized such that the **total area under the histogram integrates to 1.0**. This allows you to directly overlay mathematical probability density functions (PDFs) on top!\n",
"\n",
"### 6.3 2D Hexbin Density Plots for Big Data\n",
"When you have 50,000 to 1,000,000+ coordinates, a standard scatter plot becomes an illegible solid black ink blob. **`ax.hexbin()`** clusters points into a hexagonal tessellation grid and colors each hexagon by sample density.\n"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with normalized overlapping histograms and 2D hexbin density chart\n"
]
}
],
"source": [
"rng = np.random.default_rng(2026)\n",
"control_group = rng.normal(loc=100, scale=15, size=2000)\n",
"treatment_group = rng.normal(loc=112, scale=14, size=2000)\n",
"\n",
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4.5), dpi=100, layout='constrained')\n",
"\n",
"# 1. Normalized Overlapping Histograms with Stepped Outlines\n",
"ax1.hist(control_group, bins='auto', density=True, alpha=0.4, color='#1f77b4', label='Control (Baseline)')\n",
"ax1.hist(control_group, bins='auto', density=True, histtype='step', linewidth=1.8, color='#1f77b4')\n",
"\n",
"ax1.hist(treatment_group, bins='auto', density=True, alpha=0.4, color='#d95f02', label='Treatment (New Model)')\n",
"ax1.hist(treatment_group, bins='auto', density=True, histtype='step', linewidth=1.8, color='#d95f02')\n",
"\n",
"ax1.set_title(\"A/B Test Metric Distributions (Normalized Density)\", fontweight='bold')\n",
"ax1.set_xlabel(\"Conversion Score\")\n",
"ax1.set_ylabel(\"Probability Density\")\n",
"ax1.legend(loc='upper right', frameon=True)\n",
"ax1.grid(True, linestyle=':', alpha=0.6)\n",
"\n",
"# 2. Hexbin Plot: 50,000 Data Points\n",
"big_x = rng.normal(0, 1.2, 50000)\n",
"big_y = big_x * 0.7 + rng.normal(0, 0.9, 50000)\n",
"\n",
"hex_plot = ax2.hexbin(big_x, big_y, gridsize=35, cmap='plasma', mincnt=1, edgecolors='none')\n",
"ax2.set_title(\"Hexbin Density (50,000 points without overplotting)\", fontweight='bold')\n",
"ax2.set_xlabel(\"Latent Feature 1\")\n",
"ax2.set_ylabel(\"Latent Feature 2\")\n",
"fig.colorbar(hex_plot, ax=ax2, label=\"Point Density per Hexagon\")\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 6.4 Empirical Cumulative Distribution Functions (ECDF) with `cumulative=True`\n",
"A cumulative histogram shows the proportion of data points below any given threshold $x$, providing an empirical cumulative distribution without requiring kernel tuning.\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with empirical cumulative distribution and 95th percentile threshold\n"
]
}
],
"source": [
"response_latencies_ms = rng.exponential(scale=45, size=3000) + 10\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 4), dpi=100)\n",
"\n",
"n, bins, patches = ax.hist(\n",
" response_latencies_ms,\n",
" bins=50,\n",
" density=True,\n",
" cumulative=True,\n",
" color='#2b5c8f',\n",
" alpha=0.6,\n",
" edgecolor='white'\n",
")\n",
"\n",
"# Reference SLO lines (Service Level Objective: 95th percentile)\n",
"p95 = np.percentile(response_latencies_ms, 95)\n",
"ax.axvline(p95, color='#d95f02', linestyle='--', linewidth=2, label=f'95th Percentile ({p95:.1f} ms)')\n",
"ax.axhline(0.95, color='gray', linestyle=':', linewidth=1.5)\n",
"\n",
"ax.set_title(\"Empirical Cumulative Latency Distribution (SLO Audit)\", fontweight='bold')\n",
"ax.set_xlabel(\"Latency (milliseconds)\")\n",
"ax.set_ylabel(\"Cumulative Fraction of Requests\")\n",
"ax.set_ylim(0, 1.05)\n",
"ax.grid(True, linestyle=':', alpha=0.5)\n",
"ax.legend(loc='lower right', frameon=True)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 7. Box Plots & Violin Plots: Statistical Spreads\n",
"\n",
"Summary statistics like the mean can be deceptive (e.g. skewed by severe outliers). Box plots and violin plots visualize **non-parametric spreads, medians, quartiles, and full distributions**.\n",
"\n",
"---\n",
"\n",
"### 7.1 Anatomy of a Box & Whisker Plot\n",
"John Tukey\u2019s box plot is a masterclass in compact statistical representation:\n",
"\n",
"```\n",
" ANATOMY OF A BOX & WHISKER PLOT\n",
" \n",
" +---+ <--- Maximum Non-Outlier (Q3 + 1.5 * IQR)\n",
" |\n",
" +-------+-------+ <--- 75th Percentile (Q3 / Upper Quartile)\n",
" | |\n",
" | (IQR Box) |\n",
" |===============| <--- MEDIAN (50th Percentile / Q2)\n",
" | |\n",
" +-------+-------+ <--- 25th Percentile (Q1 / Lower Quartile)\n",
" |\n",
" +---+ <--- Minimum Non-Outlier (Q1 - 1.5 * IQR)\n",
" \n",
" * <--- Individual Outlier Point (Beyond Whiskers)\n",
"```\n",
"\n",
"- **Interquartile Range (IQR):** $\\text{IQR} = Q3 - Q1$. The central box captures the middle 50% of your data.\n",
"- **Whiskers:** Extend to the furthest data point within $1.5 \\times \\text{IQR}$ from the box edge.\n",
"- **Outliers (Fliers):** Any observation beyond $1.5 \\times \\text{IQR}$ is plotted individually as a distinct point.\n",
"\n",
"### 7.2 Box Plots vs Violin Plots\n",
"- **Box Plots:** Excellent for comparing medians, spreads, and detecting outliers. However, they cannot reveal whether a distribution is bimodal (has two distinct peaks).\n",
"- **Violin Plots (`ax.violinplot`):** Combines a box plot's spread with a mirrored **Kernel Density Estimate (KDE)**, revealing the true multi-modal topography of the distribution!\n"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with side-by-side notched box plots and KDE violin plots\n"
]
}
],
"source": [
"group_bronze = rng.exponential(scale=25, size=150) + 10\n",
"group_silver = rng.normal(loc=55, scale=12, size=150)\n",
"group_gold = rng.normal(loc=85, scale=15, size=150)\n",
"group_platinum = np.concatenate([rng.normal(60, 6, 75), rng.normal(120, 10, 75)])\n",
"\n",
"data_groups = [group_bronze, group_silver, group_gold, group_platinum]\n",
"tier_labels = ['Bronze', 'Silver', 'Gold', 'Platinum (Bimodal)']\n",
"\n",
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5), dpi=100, layout='constrained')\n",
"\n",
"bp = ax1.boxplot(\n",
" data_groups,\n",
" tick_labels=tier_labels,\n",
" patch_artist=True,\n",
" notch=True,\n",
" medianprops=dict(color='white', linewidth=2),\n",
" flierprops=dict(marker='o', markersize=5, markerfacecolor='#e27d60', alpha=0.7)\n",
")\n",
"\n",
"palette = ['#4575b4', '#74add1', '#fdae61', '#f46d43']\n",
"for patch, color in zip(bp['boxes'], palette):\n",
" patch.set_facecolor(color)\n",
" patch.set_alpha(0.85)\n",
"\n",
"ax1.set_title(\"Box Plots with Median Notches\", fontweight='bold')\n",
"ax1.set_ylabel(\"Monthly Spend ($USD)\")\n",
"ax1.grid(axis='y', linestyle=':', alpha=0.6)\n",
"\n",
"vp = ax2.violinplot(\n",
" data_groups,\n",
" positions=np.arange(1, 5),\n",
" showmeans=False,\n",
" showmedians=True,\n",
" showextrema=True\n",
")\n",
"\n",
"for pc, color in zip(vp['bodies'], palette):\n",
" pc.set_facecolor(color)\n",
" pc.set_edgecolor('black')\n",
" pc.set_alpha(0.7)\n",
"\n",
"vp['cmedians'].set_color('black')\n",
"vp['cmedians'].set_linewidth(2)\n",
"\n",
"ax2.set_xticks(np.arange(1, 5))\n",
"ax2.set_xticklabels(tier_labels)\n",
"ax2.set_title(\"Violin Plots (Revealing Bimodal Shape in Platinum Tier)\", fontweight='bold')\n",
"ax2.set_ylabel(\"Monthly Spend ($USD)\")\n",
"ax2.grid(axis='y', linestyle=':', alpha=0.6)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 7.3 Overlaying Jittered Raw Data Points onto Box Plots\n",
"By combining a semi-transparent box plot with jittered individual data points, you provide both summary statistics (median, IQR) and complete transparency into sample density and outlier clusters!\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with hybrid box plot and overlaid jittered observation points\n"
]
}
],
"source": [
"fig, ax = plt.subplots(figsize=(8, 5), dpi=100)\n",
"\n",
"bp = ax.boxplot(\n",
" data_groups[:3],\n",
" tick_labels=tier_labels[:3],\n",
" patch_artist=True,\n",
" boxprops=dict(facecolor='#f0f0f0', edgecolor='gray', alpha=0.7),\n",
" medianprops=dict(color='black', linewidth=2),\n",
" showfliers=False # Hide default outliers since raw points will be plotted!\n",
")\n",
"\n",
"# Overlay individual jittered points\n",
"for i, group in enumerate(data_groups[:3]):\n",
" x_coords = rng.uniform(i + 1 - 0.12, i + 1 + 0.12, size=len(group))\n",
" ax.scatter(x_coords, group, color=palette[i], alpha=0.6, edgecolors='black', linewidths=0.5, s=28)\n",
"\n",
"ax.set_title(\"Hybrid Statistical Chart: Boxplot + Jittered Raw Observations\", fontweight='bold')\n",
"ax.set_ylabel(\"Monthly Spend ($USD)\")\n",
"ax.grid(axis='y', linestyle=':', alpha=0.5)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.6 Working with Dates & Timestamps (`matplotlib.dates`)\n",
"In financial and telemetry analysis, timestamps require specialized formatting. If you treat dates as raw strings, axes labels become bunched up and unreadable.\n",
"Matplotlib provides **`matplotlib.dates`** with automatic date locators and formatters!\n"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with clean bi-weekly date tick formatting and auto-rotated labels\n"
]
}
],
"source": [
"import matplotlib.dates as mdates\n",
"import pandas as pd\n",
"\n",
"# Generate daily time series for 60 days\n",
"date_range = pd.date_range(start='2026-01-01', periods=60, freq='D')\n",
"stock_prices = 150 + np.cumsum(np.random.normal(0.5, 2.0, 60))\n",
"\n",
"fig, ax = plt.subplots(figsize=(9, 4.5), dpi=100)\n",
"\n",
"ax.plot(date_range, stock_prices, color='#2b5c8f', linewidth=2)\n",
"\n",
"# Set Major Ticks to Every 2 Weeks and Minor Ticks to Every Day\n",
"ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=2))\n",
"ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d, %Y'))\n",
"ax.xaxis.set_minor_locator(mdates.DayLocator())\n",
"\n",
"# Automatically tilt and align date labels to prevent collision!\n",
"fig.autofmt_xdate(rotation=30, ha='right')\n",
"\n",
"ax.set_title(\"Financial Asset Price Series with Native Date Formatter\", fontweight='bold')\n",
"ax.set_ylabel(\"Price ($USD)\")\n",
"ax.grid(True, linestyle=':', alpha=0.6)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 5.5 Broken Horizontal Bars (`ax.broken_barh`) for Lifecycles & Gantt Charts\n",
"When visualizing timelines\u2014such as multi-stage CI/CD pipelines, CPU core thread states, or task schedules\u2014standard bar charts cannot handle intervals with gaps. **`ax.broken_barh()`** renders arbitrary sequences of active and idle time blocks!\n"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with MLOps pipeline execution Gantt schedule\n"
]
}
],
"source": [
"fig, ax = plt.subplots(figsize=(9, 4), dpi=100)\n",
"\n",
"# Task intervals: list of (start_time, duration) tuples\n",
"data_pipeline_stages = {\n",
" '1. Ingestion': [(0, 15), (25, 10)],\n",
" '2. ETL & Cleaning': [(15, 20), (45, 15)],\n",
" '3. Feature Eng': [(35, 25)],\n",
" '4. Model Train': [(60, 30)],\n",
" '5. Deployment': [(90, 10)]\n",
"}\n",
"\n",
"y_positions = [10, 20, 30, 40, 50]\n",
"colors = ['#4575b4', '#74add1', '#fdae61', '#f46d43', '#d73027']\n",
"\n",
"for (stage, intervals), y_pos, color in zip(data_pipeline_stages.items(), y_positions, colors):\n",
" ax.broken_barh(intervals, (y_pos - 3, 6), facecolors=color, edgecolor='black', linewidth=0.5)\n",
"\n",
"ax.set_yticks(y_positions)\n",
"ax.set_yticklabels(list(data_pipeline_stages.keys()), fontsize=9, fontweight='medium')\n",
"ax.set_xlabel(\"Elapsed Time (Minutes)\", fontsize=10)\n",
"ax.set_xlim(0, 105)\n",
"ax.set_title(\"MLOps Data Pipeline Lifecycle (Broken Horizontal Bar Schedule)\", fontweight='bold', pad=12)\n",
"ax.grid(axis='x', linestyle=':', alpha=0.6)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"# Part III: Customization, Styling & Typography\n",
"\n",
"## 8. Titles, Labels, Ticks & Spines Customization\n",
"\n",
"A default chart looks like an unfinished draft. Professional, publication-ready figures have clean typography, customized tick formatters, removed visual clutter (chart junk), and appropriate scaling.\n",
"\n",
"---\n",
"\n",
"### 8.1 LaTeX Math Expressions in Text\n",
"Matplotlib includes a built-in TeX parsing engine (`mathtext`). By wrapping strings in raw Python literals (`r'$...$'`), you can render any mathematical formula directly onto titles, legends, and axis labels:\n",
"\n",
"```python\n",
"ax.set_title(r'Gradient Descent: $\\theta_{t+1} = \\theta_t - \\eta \\nabla J(\\theta_t)$', fontsize=12)\n",
"ax.set_ylabel(r'Loss: $\\mathcal{L}_{MSE} = \\frac{1}{N}\\sum (y_i - \\hat{y}_i)^2$')\n",
"```\n",
"\n",
"### 8.2 Taming Ticks with `matplotlib.ticker`\n",
"Never manually type out lists of tick strings when numbers change dynamically. Matplotlib\u2019s `ticker` module provides robust locators and formatters:\n",
"- **`MultipleLocator(base)`:** Puts ticks at exact intervals (e.g. every 2 units).\n",
"- **`PercentFormatter(xmax=100)`:** Formats raw numbers into clean percentages (e.g. `85` $\\to$ `85%`).\n",
"- **`FuncFormatter(callback)`:** Formats numbers with custom Python logic (e.g. converting `1500000` to `\"$1.5M\"`).\n"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with custom currency formatter and MultipleLocator ticks\n"
]
}
],
"source": [
"import matplotlib.ticker as ticker\n",
"\n",
"quarters = np.arange(1, 17)\n",
"revenue = 120000 * np.exp(0.18 * quarters) + np.random.normal(0, 15000, 16)\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n",
"\n",
"ax.plot(quarters, revenue, marker='o', color='#2b5c8f', linewidth=2.2, markersize=5)\n",
"ax.set_title(r\"Quarterly Revenue: $R(t) = R_0 e^{kt}$\", fontsize=12, fontweight='bold', pad=12)\n",
"ax.set_xlabel(\"Financial Quarter\")\n",
"ax.set_ylabel(\"Gross Revenue ($USD)\")\n",
"\n",
"# Custom Python formatter function for Millions ($M)\n",
"def currency_fmt(x, pos):\n",
" if x >= 1e6:\n",
" return f\"${x*1e-6:.1f}M\"\n",
" return f\"${x*1e-3:.0f}K\"\n",
"\n",
"ax.yaxis.set_major_formatter(ticker.FuncFormatter(currency_fmt))\n",
"ax.xaxis.set_major_locator(ticker.MultipleLocator(2))\n",
"ax.grid(axis='y', linestyle=':', alpha=0.6)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 8.3 De-Cluttering Spines: The Clean \"Tufte\" Aesthetic\n",
"Edward Tufte famously advocated for maximizing the \"data-to-ink ratio\" by eliminating non-essential decoration. The heavy black top and right borders (spines) add zero information.\n",
"Modern visualization practice removes them:\n",
"```python\n",
"ax.spines[['top', 'right']].set_visible(False)\n",
"```\n",
"\n",
"---\n",
"\n",
"### 8.4 Logarithmic and Symmetric Log Scales\n",
"- **`ax.set_yscale('log')`:** Compresses exponential growth into a straight linear line. Ideal for metrics spanning multiple orders of magnitude (e.g. bacterial growth, financial valuations, neural net learning rates).\n",
"- **`ax.set_yscale('symlog')`:** Symmetric log scale. Supports data that contains **zero and negative numbers** without crashing!\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with clean outward spines and symmetric log scale\n"
]
}
],
"source": [
"x_vals = np.linspace(-10, 10, 200)\n",
"# Function that spans negative and positive values over orders of magnitude\n",
"y_sym = np.sign(x_vals) * (np.exp(np.abs(x_vals) / 2.0) - 1.0)\n",
"\n",
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.5), dpi=100, layout='constrained')\n",
"\n",
"# 1. Clean Spines with Outward Offset\n",
"ax1.plot(quarters, revenue, color='#2b5c8f', linewidth=2.2, marker='s', markersize=4)\n",
"ax1.set_yscale('log')\n",
"ax1.set_title(\"Log Scale with Outward Clean Spines\", fontweight='bold')\n",
"ax1.spines[['top', 'right']].set_visible(False)\n",
"ax1.spines['left'].set_position(('outward', 8))\n",
"ax1.spines['bottom'].set_position(('outward', 8))\n",
"ax1.grid(True, which='both', linestyle=':', alpha=0.4)\n",
"\n",
"# 2. Symmetric Log (Symlog) supporting negatives\n",
"ax2.plot(x_vals, y_sym, color='#d95f02', linewidth=2)\n",
"ax2.set_yscale('symlog', linthresh=1.0)\n",
"ax2.set_title(r\"Symmetric Log Scale: $y = \\text{sign}(x)(e^{|x|/2} - 1)$\", fontweight='bold')\n",
"ax2.axhline(0, color='black', linestyle='--', linewidth=0.8)\n",
"ax2.spines[['top', 'right']].set_visible(False)\n",
"ax2.grid(True, which='both', linestyle=':', alpha=0.4)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 9. Legends, Text Annotations & Callouts\n",
"\n",
"A chart that merely plots numbers forces the reader to work hard. Great data visualizers use **annotations, callouts, and reference anchors** to tell a story and highlight the exact discovery or anomaly immediately.\n",
"\n",
"---\n",
"\n",
"### 9.1 Advanced Legend Placement & Multi-Columns\n",
"When plots have dense data, placing a legend inside the coordinate grid can obscure critical curves.\n",
"Use **`bbox_to_anchor`** to park the legend neatly in the margin, and `ncol` to distribute entries into columns:\n",
"```python\n",
"ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', ncol=2, frameon=True)\n",
"```\n",
"\n",
"### 9.2 Precision Annotations with Arrows (`ax.annotate`)\n",
"`ax.annotate()` connects descriptive text to exact coordinates using customizable arrows:\n",
"- `xy`: Coordinates of the target data point.\n",
"- `xytext`: Coordinates where the text label should sit.\n",
"- `textcoords='offset points'`: Makes text offset relative to the point in typographical points.\n",
"- `arrowprops`: Pointer arrow style (`arrowstyle`, `connectionstyle=\"arc3,rad=.2\"`).\n"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with curved arrow annotation and exterior legend\n"
]
}
],
"source": [
"epochs = np.arange(1, 51)\n",
"train_loss = 2.0 * np.exp(-epochs / 10.0) + 0.15 + np.random.normal(0, 0.02, 50)\n",
"val_loss = 2.1 * np.exp(-epochs / 12.0) + 0.35 + 0.0006 * (epochs - 20)**2 + np.random.normal(0, 0.03, 50)\n",
"\n",
"fig, ax = plt.subplots(figsize=(9, 4.8), dpi=100)\n",
"\n",
"ax.plot(epochs, train_loss, color='#2b5c8f', linewidth=2.2, label='Training Loss')\n",
"ax.plot(epochs, val_loss, color='#d95f02', linewidth=2.2, label='Validation Loss')\n",
"\n",
"min_epoch = np.argmin(val_loss) + 1\n",
"min_loss = val_loss[min_epoch - 1]\n",
"\n",
"# Precision arrow callout with curved connection\n",
"ax.annotate(\n",
" f'Optimal Checkpoint\\nEpoch {min_epoch} (Loss: {min_loss:.3f})',\n",
" xy=(min_epoch, min_loss),\n",
" xytext=(min_epoch + 8, min_loss + 0.45),\n",
" arrowprops=dict(\n",
" arrowstyle='->',\n",
" color='black',\n",
" lw=1.5,\n",
" connectionstyle=\"arc3,rad=-0.25\"\n",
" ),\n",
" bbox=dict(boxstyle='round,pad=0.5', facecolor='#ffffcc', edgecolor='#cccc00', alpha=0.9),\n",
" fontsize=9,\n",
" fontweight='bold'\n",
")\n",
"\n",
"# Position legend outside plot\n",
"ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', frameon=True)\n",
"ax.set_title(\"Early Stopping Detection with Precision Arrow Callout\", fontweight='bold', pad=12)\n",
"ax.set_xlabel(\"Epoch\")\n",
"ax.set_ylabel(\"Loss\")\n",
"ax.grid(True, linestyle=':', alpha=0.5)\n",
"ax.spines[['top', 'right']].set_visible(False)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 9.3 Reference Lines & Highlight Bands\n",
"- `ax.axvline(x=...)`: Vertical reference line across the entire plot height.\n",
"- `ax.axhline(y=...)`: Horizontal baseline or SLA threshold line.\n",
"- `ax.axvspan(xmin, xmax)`: Shaded vertical band (e.g. holiday surge, recession).\n",
"- `ax.axhspan(ymin, ymax)`: Shaded horizontal band (e.g. acceptable tolerance zone).\n",
"\n",
"---\n",
"\n",
"### 9.4 Text Callouts in Relative Axes Coordinates (`transform=ax.transAxes`)\n",
"When adding a summary scorecard or KPI box, using data coordinates means the box jumps around if axis limits change.\n",
"Passing `transform=ax.transAxes` pins coordinates from `(0, 0)` (bottom-left) to `(1, 1)` (top-right) regardless of data values!\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with reference lines, tolerance band, surge phase, and transAxes scorecard\n"
]
}
],
"source": [
"fig, ax = plt.subplots(figsize=(9, 4.5), dpi=100)\n",
"\n",
"x = np.linspace(0, 100, 200)\n",
"signal = 50 + 10 * np.sin(x / 5.0) + np.random.normal(0, 2, 200)\n",
"\n",
"ax.plot(x, signal, color='#2b5c8f', label='Sensor Telemetry')\n",
"\n",
"# 1. Baseline Target\n",
"ax.axhline(50, color='gray', linestyle='--', linewidth=1.5, label='Nominal Target')\n",
"\n",
"# 2. Acceptable Tolerance Band (45 to 55)\n",
"ax.axhspan(45, 55, color='#2ca02c', alpha=0.15, label='Safe Operating Band [45, 55]')\n",
"\n",
"# 3. Anomaly Incident Vertical Band\n",
"ax.axvspan(65, 80, color='#d95f02', alpha=0.2, label='Thermal Surge Phase')\n",
"\n",
"# 4. KPI Box pinned to top-left in relative axes coordinates (0.03, 0.92)\n",
"ax.text(0.03, 0.92, \"Status: OK\\nMean: 50.1\\nOutliers: 2\",\n",
" transform=ax.transAxes, fontsize=9, verticalalignment='top',\n",
" bbox=dict(boxstyle='round,pad=0.5', facecolor='white', edgecolor='gray', alpha=0.9))\n",
"\n",
"ax.set_title(\"Industrial Telemetry with Reference Bands & TransAxes KPI Box\", fontweight='bold')\n",
"ax.set_xlabel(\"Time (seconds)\")\n",
"ax.set_ylabel(\"Pressure (PSI)\")\n",
"ax.legend(loc='lower left', frameon=True)\n",
"ax.spines[['top', 'right']].set_visible(False)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 10. Colors, Colormaps & Stylesheets\n",
"\n",
"Color is the most emotionally resonant and informative channel in visualization. Used correctly, it clarifies complex patterns; used poorly, it creates optical illusions, alienates colorblind readers, or misleads scientific audiences.\n",
"\n",
"---\n",
"\n",
"### 10.1 The Three Classes of Colormaps\n",
"Matplotlib groups its color palettes into three distinct functional categories:\n",
"\n",
"```\n",
"+-----------------------------------------------------------------------------------+\n",
"| 1. SEQUENTIAL (For ordered numerical data going from low to high) |\n",
"| * viridis, plasma, inferno, magma, Blues, Greens |\n",
"| * Luminance changes monotonically; great for heatmaps, densities, magnitudes. |\n",
"+-----------------------------------------------------------------------------------+\n",
"| 2. DIVERGING (For data with a meaningful critical neutral midpoint / zero) |\n",
"| * coolwarm, RdBu, PiYG, vlag, seismic |\n",
"| * Center is neutral (white/gray); extremes diverge in opposing directions |\n",
"| * Great for correlations (-1 to +1), profit/loss, or anomalies (-sigma/+sigma)|\n",
"+-----------------------------------------------------------------------------------+\n",
"| 3. QUALITATIVE (For discrete, unordered categorical groups) |\n",
"| * tab10, Set2, Dark2, Paired |\n",
"| * Colors have distinct hues without implying that one group is \"greater\" |\n",
"+-----------------------------------------------------------------------------------+\n",
"```\n",
"\n",
"> \u26a0\ufe0f **The Critical Flaw of the Legacy `jet` Colormap:**\n",
"> In older MATLAB and Matplotlib tutorials, you will see `cmap='jet'`. **Never use `jet`!**\n",
"> `jet` is not perceptually uniform: the sharp yellow transition creates artificial \"cliffs\" and false edges in continuous data where no real gradient exists. Always prefer **`viridis`** (the modern default since Matplotlib 2.0).\n"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with gradient swatches of Sequential, Diverging, and Qualitative colormaps\n"
]
}
],
"source": [
"# Visualizing sample palettes from each class\n",
"fig, axs = plt.subplots(3, 1, figsize=(8, 3.5), dpi=100, layout='constrained')\n",
"\n",
"gradient = np.linspace(0, 1, 256).reshape(1, -1)\n",
"\n",
"cmaps_demo = [\n",
" ('Sequential: viridis', 'viridis'),\n",
" ('Diverging: coolwarm', 'coolwarm'),\n",
" ('Qualitative: tab10', 'tab10')\n",
"]\n",
"\n",
"for ax, (name, cmap_name) in zip(axs, cmaps_demo):\n",
" ax.imshow(gradient, aspect='auto', cmap=cmap_name)\n",
" ax.set_title(name, fontsize=10, fontweight='semibold', loc='left')\n",
" ax.set_axis_off()\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 10.2 Built-In Stylesheets & Context Managers\n",
"Matplotlib provides dozens of built-in stylesheets (`plt.style.available`) to instantly transform aesthetics.\n",
"- Instead of permanently altering global state with `plt.style.use()`, you can use the **context manager** `with plt.style.context(...)` to apply a style to just a single figure!\n",
"\n",
"---\n",
"\n",
"### 10.3 Global Configuration with `plt.rcParams`\n",
"You can establish a universal corporate or lab branding theme by configuring `plt.rcParams` at the start of your script:\n",
"```python\n",
"plt.rcParams['font.family'] = 'sans-serif'\n",
"plt.rcParams['font.size'] = 11\n",
"plt.rcParams['axes.spines.top'] = False\n",
"plt.rcParams['axes.spines.right'] = False\n",
"```\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered in dark mode\n",
"Global theme safely preserved outside context block.\n"
]
}
],
"source": [
"with plt.style.context('dark_background'):\n",
" fig, ax = plt.subplots(figsize=(8, 4), dpi=100)\n",
" x_test = np.linspace(0, 10, 100)\n",
" ax.plot(x_test, np.sin(x_test), color='#00ffcc', linewidth=2.5, label=r'$\\sin(x)$')\n",
" ax.plot(x_test, np.cos(x_test), color='#ff007f', linewidth=2.5, linestyle='--', label=r'$\\cos(x)$')\n",
" ax.set_title(\"Figure Rendered in Isolated 'dark_background' Context\", fontsize=11, fontweight='bold')\n",
" ax.legend(frameon=True, facecolor='#222222', edgecolor='none')\n",
" ax.grid(True, linestyle=':', alpha=0.3)\n",
" plt.show()\n",
"\n",
"print(\"Global theme safely preserved outside context block.\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 8.5 Secondary Axis Transformations (`ax.secondary_xaxis`)\n",
"In physics and engineering, data often has an alternative reciprocal representation (e.g. **Frequency in Hz** vs **Period in seconds** $T = 1/f$, or **Wavelength in nm** vs **Photon Energy in eV**).\n",
"Matplotlib allows you to attach a secondary axis coupled through explicit mathematical transform functions!\n"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with coupled frequency and period dual X-axes\n"
]
}
],
"source": [
"frequency_hz = np.linspace(10, 1000, 200)\n",
"amplitude_db = -20 * np.log10(1 + (frequency_hz / 100)**2)\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n",
"\n",
"ax.plot(frequency_hz, amplitude_db, color='#2b5c8f', linewidth=2)\n",
"ax.set_xscale('log')\n",
"ax.set_xlabel(\"Frequency (Hz)\", color='#2b5c8f', fontweight='bold')\n",
"ax.set_ylabel(\"Attenuation (dB)\")\n",
"\n",
"# Forward transform: Period T = 1 / f (in milliseconds)\n",
"def f_to_period(f):\n",
" return (1.0 / np.maximum(f, 1e-9)) * 1000.0\n",
"\n",
"def period_to_f(t):\n",
" return (1.0 / np.maximum(t * 1e-3, 1e-9))\n",
"\n",
"# Attach secondary X-axis on top\n",
"sec_ax = ax.secondary_xaxis('top', functions=(f_to_period, period_to_f))\n",
"sec_ax.set_xlabel(\"Signal Period (ms)\", color='#d95f02', fontweight='bold')\n",
"\n",
"ax.set_title(\"Acoustic Low-Pass Filter Response (Dual Coupled X-Axes)\", fontweight='bold', pad=15)\n",
"ax.grid(True, which='both', linestyle=':', alpha=0.4)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 9.5 Custom Proxy Artists for Complex Legends\n",
"When your plot contains complex composite glyphs (e.g. shaded bands, multi-colored lines, or custom markers) where automatic legend extraction fails, you can construct custom **Proxy Artists** using `matplotlib.patches.Patch` and `matplotlib.lines.Line2D`!\n"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with custom proxy legend handles\n"
]
}
],
"source": [
"from matplotlib.lines import Line2D\n",
"from matplotlib.patches import Patch\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 4), dpi=100)\n",
"\n",
"# Simulate complex scatter with background bands\n",
"x_scatter = np.random.uniform(0, 10, 50)\n",
"y_scatter = np.random.uniform(0, 50, 50)\n",
"ax.scatter(x_scatter, y_scatter, color='#2b5c8f', s=35, edgecolors='none')\n",
"ax.axhspan(20, 35, color='#2ca02c', alpha=0.15)\n",
"ax.axhline(40, color='red', linestyle='--')\n",
"\n",
"# Build custom legend manually using Proxy Artists\n",
"custom_legend_elements = [\n",
" Line2D([0], [0], marker='o', color='w', label='Sample Observation',\n",
" markerfacecolor='#2b5c8f', markersize=8),\n",
" Patch(facecolor='#2ca02c', alpha=0.3, label='Safe Operational Range'),\n",
" Line2D([0], [0], color='red', linestyle='--', lw=1.5, label='Critical Safety Threshold')\n",
"]\n",
"\n",
"ax.legend(handles=custom_legend_elements, loc='upper left', frameon=True)\n",
"ax.set_title(\"Plot with Manually Constructed Proxy Legend\", fontweight='bold')\n",
"ax.set_xlabel(\"Feature A\")\n",
"ax.set_ylabel(\"Metric B\")\n",
"ax.grid(True, linestyle=':', alpha=0.5)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"# Part IV: Advanced Plotting, Images & 3D\n",
"\n",
"## 11. Heatmaps & Matrix Visualizations\n",
"\n",
"In machine learning and data science, matrices are omnipresent: feature correlation matrices, confusion matrices, attention weight maps in Transformers, and convolutional feature activations.\n",
"\n",
"---\n",
"\n",
"### 11.1 Matrix Visualizations with `ax.imshow()`\n",
"While higher-level libraries like Seaborn offer `sns.heatmap()`, understanding how Matplotlib's native **`ax.imshow()`** works is essential for granular control and lightning-fast rendering:\n",
"- `X`: 2D array of numerical values (or 3D array of shape `(H, W, 3)` for RGB images).\n",
"- `cmap`: The colormap used to convert scalar values into colors. For correlation matrices, **diverging colormaps** like `'coolwarm'`, `'vlag'`, or `'RdBu_r'` centered at 0 are optimal.\n",
"- `interpolation='nearest'`: Ensures crisp, square matrix cells rather than blurry smeared pixels.\n",
"- `aspect='auto'` or `'equal'`: Controls whether cells remain strictly square or stretch to fill axes.\n",
"\n",
"### 11.2 Annotating Heatmap Cells with Values\n",
"To make a correlation matrix readable, you often want to stamp the numerical correlation coefficient inside each cell with high-contrast text.\n"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with annotated correlation matrix heatmap and diverging colorbar\n"
]
}
],
"source": [
"features = ['Age', 'Income', 'Credit Score', 'Debt-to-Income', 'Default Risk']\n",
"corr_matrix = np.array([\n",
" [ 1.00, 0.42, 0.31, -0.18, -0.35],\n",
" [ 0.42, 1.00, 0.55, -0.40, -0.48],\n",
" [ 0.31, 0.55, 1.00, -0.62, -0.71],\n",
" [-0.18, -0.40, -0.62, 1.00, 0.64],\n",
" [-0.35, -0.48, -0.71, 0.64, 1.00]\n",
"])\n",
"\n",
"fig, ax = plt.subplots(figsize=(7, 6), dpi=100)\n",
"\n",
"im = ax.imshow(corr_matrix, cmap='coolwarm', vmin=-1.0, vmax=1.0, interpolation='nearest')\n",
"\n",
"ax.set_xticks(np.arange(len(features)))\n",
"ax.set_yticks(np.arange(len(features)))\n",
"ax.set_xticklabels(features, rotation=35, ha='right', fontsize=9)\n",
"ax.set_yticklabels(features, fontsize=9)\n",
"\n",
"# Overlay numerical values directly onto each cell\n",
"for i in range(len(features)):\n",
" for j in range(len(features)):\n",
" val = corr_matrix[i, j]\n",
" text_color = \"white\" if abs(val) > 0.55 else \"black\"\n",
" ax.text(j, i, f\"{val:+.2f}\", ha=\"center\", va=\"center\",\n",
" color=text_color, fontsize=10, fontweight='bold')\n",
"\n",
"cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)\n",
"cbar.set_label(\"Pearson Correlation Coefficient (r)\", fontsize=10)\n",
"\n",
"ax.set_title(\"Financial Feature Correlation Matrix (ax.imshow)\", fontsize=12, fontweight='bold', pad=12)\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 11.3 Visualizing Convolutional Feature Maps & Filters\n",
"In Deep Learning, auditing what convolutional neural network filters detect is achieved by rendering 2D weight tensors with `ax.imshow()`.\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with 4 CNN convolutional filter weight grids\n"
]
}
],
"source": [
"# Simulate 4 convolutional edge-detection filter activations (16x16 grids)\n",
"rng = np.random.default_rng(7)\n",
"fig, axs = plt.subplots(1, 4, figsize=(10, 2.8), dpi=100, layout='constrained')\n",
"\n",
"filter_names = ['Sobel Horizontal', 'Sobel Vertical', 'Gaussian Blur', 'Laplacian Edge']\n",
"filters = [\n",
" np.outer(np.linspace(-1, 1, 16), np.ones(16)),\n",
" np.outer(np.ones(16), np.linspace(-1, 1, 16)),\n",
" np.exp(-((np.arange(16)-7.5)**2 + (np.arange(16)-7.5)[:, None]**2) / 16.0),\n",
" rng.normal(0, 0.4, (16, 16))\n",
"]\n",
"\n",
"for ax, filt, name in zip(axs, filters, filter_names):\n",
" im = ax.imshow(filt, cmap='gray', interpolation='nearest')\n",
" ax.set_title(name, fontsize=9, fontweight='semibold')\n",
" ax.set_xticks([])\n",
" ax.set_yticks([])\n",
"\n",
"fig.suptitle(\"CNN Convolutional Filter Weight Visualizations\", fontsize=11, fontweight='bold')\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 12. Contour Plots & Decision Boundaries\n",
"\n",
"In optimization theory and machine learning, we often want to visualize a 2D scalar field\u2014such as a Loss Landscape $J(\\theta_1, \\theta_2)$ or the classification boundary separating two classes in feature space.\n",
"\n",
"---\n",
"\n",
"### 12.1 Generating 2D Coordinate Grids with `np.meshgrid`\n",
"To evaluate a 2D function $Z = f(X, Y)$, we first construct a 2D coordinate grid using `np.meshgrid()`:\n",
"\n",
"```\n",
" THE MESHGRID MENTAL MODEL\n",
" 1D Vector X = [0, 1, 2] 1D Vector Y = [10, 20]\n",
" \n",
" Meshgrid XX (X-coordinates): Meshgrid YY (Y-coordinates):\n",
" +-----+-----+-----+ +-----+-----+-----+\n",
" | 0 | 1 | 2 | | 10 | 10 | 10 |\n",
" +-----+-----+-----+ +-----+-----+-----+\n",
" | 0 | 1 | 2 | | 20 | 20 | 20 |\n",
" +-----+-----+-----+ +-----+-----+-----+\n",
"```\n",
"\n",
"### 12.2 Filled Contours (`ax.contourf`) vs Contour Lines (`ax.contour`)\n",
"- **`ax.contourf(X, Y, Z, levels=...)`:** Fills the regions between elevation levels with solid colors.\n",
"- **`ax.contour(X, Y, Z, levels=...)`:** Draws the isolines (topographical lines of equal elevation). Isolines can be labeled with numbers using `ax.clabel()`!\n"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with decision boundary contours and overlaid classification points\n"
]
}
],
"source": [
"rng = np.random.default_rng(42)\n",
"n_samples = 150\n",
"\n",
"x0 = rng.normal(-1.2, 0.7, n_samples)\n",
"y0 = rng.normal(0.0, 0.7, n_samples)\n",
"x1 = rng.normal(1.2, 0.7, n_samples)\n",
"y1 = rng.normal(0.5, 0.7, n_samples)\n",
"\n",
"x_span = np.linspace(-3.5, 3.5, 200)\n",
"y_span = np.linspace(-2.5, 3.0, 200)\n",
"XX, YY = np.meshgrid(x_span, y_span)\n",
"\n",
"Z_logits = (XX**2 + YY**2 - 2.2) + 0.8 * XX\n",
"Z_prob = 1.0 / (1.0 + np.exp(-Z_logits))\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 6), dpi=100)\n",
"\n",
"contour_filled = ax.contourf(XX, YY, Z_prob, levels=20, cmap='RdBu_r', alpha=0.7)\n",
"boundary_line = ax.contour(XX, YY, Z_prob, levels=[0.5], colors='black', linewidths=2.5, linestyles='--')\n",
"ax.clabel(boundary_line, inline=True, fmt='P = %.1f (Decision Boundary)', fontsize=9)\n",
"\n",
"ax.scatter(x0, y0, color='#2166ac', edgecolors='white', s=45, label='Class 0 (Negative)', zorder=3)\n",
"ax.scatter(x1, y1, color='#b2182b', edgecolors='white', s=45, label='Class 1 (Positive)', zorder=3)\n",
"\n",
"cbar = fig.colorbar(contour_filled, ax=ax)\n",
"cbar.set_label(\"Model Probability $P(Y=1|X)$\", fontsize=10)\n",
"\n",
"ax.set_title(\"Machine Learning Non-Linear Decision Boundary & Probability Field\", fontsize=12, fontweight='bold', pad=12)\n",
"ax.set_xlabel(\"Feature 1 ($x_1$)\")\n",
"ax.set_ylabel(\"Feature 2 ($x_2$)\")\n",
"ax.legend(loc='lower left', frameon=True)\n",
"ax.grid(True, linestyle=':', alpha=0.4)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 13. 3D Surface & Scatter Plots (`mpl_toolkits.mplot3d`)\n",
"\n",
"While 2D projections are usually preferable for quantitative clarity, 3D plots are invaluable for visualizing **loss landscapes, 3D point clouds, physical trajectory paths, and spatial sensor orientations**.\n",
"\n",
"---\n",
"\n",
"### 13.1 Creating 3D Axes\n",
"To enable 3D plotting in Matplotlib, you pass `projection='3d'` when adding an Axes:\n",
"```python\n",
"fig = plt.figure(figsize=(9, 6))\n",
"ax = fig.add_subplot(projection='3d')\n",
"```\n",
"\n",
"### 13.2 Key 3D Methods\n",
"- **`ax.scatter(x, y, z)`:** 3D scatter plot of points.\n",
"- **`ax.plot_surface(X, Y, Z, cmap=...)`:** 3D surface mesh with continuous shading.\n",
"- **`ax.view_init(elev=..., azim=...)`:** Sets the camera angle:\n",
" - `elev`: Elevation angle in degrees above the x-y plane.\n",
" - `azim`: Azimuthal angle in degrees rotating around the z-axis.\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with 3D loss surface and optimization trajectory path\n"
]
}
],
"source": [
"from mpl_toolkits.mplot3d import Axes3D\n",
"\n",
"theta1 = np.linspace(-3, 3, 100)\n",
"theta2 = np.linspace(-3, 3, 100)\n",
"T1, T2 = np.meshgrid(theta1, theta2)\n",
"Loss = np.sin(np.sqrt(T1**2 + T2**2)) + 0.15 * (T1**2 + T2**2)\n",
"\n",
"fig = plt.figure(figsize=(10, 5.5), dpi=100)\n",
"ax = fig.add_subplot(projection='3d')\n",
"\n",
"surf = ax.plot_surface(\n",
" T1, T2, Loss,\n",
" cmap='viridis',\n",
" edgecolor='none',\n",
" alpha=0.85,\n",
" antialiased=True\n",
")\n",
"\n",
"opt_steps = 15\n",
"t1_path = np.linspace(-2.5, 0.0, opt_steps) + np.random.normal(0, 0.08, opt_steps)\n",
"t2_path = np.linspace(-2.2, 0.0, opt_steps) + np.random.normal(0, 0.08, opt_steps)\n",
"loss_path = np.sin(np.sqrt(t1_path**2 + t2_path**2)) + 0.15 * (t1_path**2 + t2_path**2)\n",
"\n",
"ax.plot(t1_path, t2_path, loss_path, color='red', marker='o', markersize=5,\n",
" linewidth=2.5, label='Gradient Descent Path', zorder=5)\n",
"\n",
"ax.view_init(elev=32, azim=-55)\n",
"\n",
"ax.set_title(r\"3D Optimization Loss Landscape: $\\mathcal{L}(\\theta_1, \\theta_2)$\", fontsize=12, fontweight='bold', pad=12)\n",
"ax.set_xlabel(r\"Parameter $\\theta_1$\", labelpad=8)\n",
"ax.set_ylabel(r\"Parameter $\\theta_2$\", labelpad=8)\n",
"ax.set_zlabel(\"Objective Loss\", labelpad=8)\n",
"ax.legend(loc='upper right')\n",
"\n",
"fig.colorbar(surf, ax=ax, shrink=0.55, aspect=10, pad=0.1, label='Loss Magnitude')\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 12.4 Vector Fields & Streamlines (`ax.streamplot`)\n",
"In fluid dynamics, electromagnetic physics, and gradient descent optimization, vector fields define a direction and magnitude at every point in space.\n",
"**`ax.streamplot(X, Y, U, V)`** draws smooth continuous streamlines tracing the flow of the vector field!\n"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with dynamic continuous vector streamlines and velocity color mapping\n"
]
}
],
"source": [
"# Generate 2D vector field: Saddle point dynamics\n",
"x_grid = np.linspace(-3, 3, 100)\n",
"y_grid = np.linspace(-3, 3, 100)\n",
"X_v, Y_v = np.meshgrid(x_grid, y_grid)\n",
"\n",
"# Vector velocities (U = dx/dt, V = dy/dt)\n",
"U = Y_v\n",
"V = X_v - X_v**3\n",
"\n",
"fig, ax = plt.subplots(figsize=(7, 6), dpi=100)\n",
"\n",
"# Speed magnitude for color mapping\n",
"speed = np.sqrt(U**2 + V**2)\n",
"\n",
"stream = ax.streamplot(\n",
" X_v, Y_v, U, V,\n",
" color=speed,\n",
" cmap='plasma',\n",
" density=1.2,\n",
" linewidth=1.2,\n",
" arrowsize=1.2\n",
")\n",
"\n",
"fig.colorbar(stream.lines, ax=ax, label=\"Velocity Magnitude\")\n",
"ax.set_title(r\"Non-Linear Phase Portrait Streamplot: $\\dot{x}=y, \\dot{y}=x-x^3$\", fontweight='bold', pad=12)\n",
"ax.set_xlabel(\"Coordinate X\")\n",
"ax.set_ylabel(\"Coordinate Y\")\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 13.4 Multi-Attribute Profiling: Radar / Spider Charts on Polar Coordinates\n",
"Radar (spider) charts compare multiple quantitative competencies or benchmark scores across competing models or candidates using **polar coordinates (`projection='polar'`)**.\n"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with polar radar comparison chart\n"
]
}
],
"source": [
"# Model capability benchmark across 6 evaluation axes\n",
"benchmarks = ['MMLU (Reasoning)', 'Coding (HumanEval)', 'Math (GSM8K)', 'Speed (Tokens/s)', 'Low Memory', 'Vision']\n",
"num_vars = len(benchmarks)\n",
"\n",
"# Angles for each attribute on the 360-degree circle\n",
"angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()\n",
"# Close the circular polygon loop\n",
"angles += angles[:1]\n",
"\n",
"model_alpha = [88, 82, 75, 95, 70, 85]\n",
"model_beta = [76, 92, 88, 65, 90, 78]\n",
"\n",
"model_alpha += model_alpha[:1]\n",
"model_beta += model_beta[:1]\n",
"\n",
"fig, ax = plt.subplots(figsize=(7, 6), subplot_kw=dict(projection='polar'), dpi=100)\n",
"\n",
"# Model Alpha\n",
"ax.plot(angles, model_alpha, color='#2b5c8f', linewidth=2, label='Model Alpha')\n",
"ax.fill(angles, model_alpha, color='#2b5c8f', alpha=0.2)\n",
"\n",
"# Model Beta\n",
"ax.plot(angles, model_beta, color='#d95f02', linewidth=2, label='Model Beta')\n",
"ax.fill(angles, model_beta, color='#d95f02', alpha=0.2)\n",
"\n",
"ax.set_theta_offset(np.pi / 2)\n",
"ax.set_theta_direction(-1)\n",
"\n",
"ax.set_xticks(angles[:-1])\n",
"ax.set_xticklabels(benchmarks, fontsize=9, fontweight='semibold')\n",
"ax.set_ylim(0, 100)\n",
"ax.set_title(\"LLM Benchmark Competency Profile (Polar Radar Chart)\", fontweight='bold', pad=18)\n",
"ax.legend(loc='upper right', bbox_to_anchor=(1.25, 1.1), frameon=True)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"# Part V: Machine Learning Visualizations & Production Best Practices\n",
"\n",
"## 14. Essential Machine Learning Visualizations\n",
"\n",
"In machine learning workflows, visualizations are not mere aesthetic embellishments\u2014they are your primary diagnostic tools for debugging algorithms, auditing model failures, and communicating results to stakeholders.\n",
"\n",
"---\n",
"\n",
"### 14.1 Diagnostic Training Dynamics: Loss & Accuracy\n",
"Monitoring training and validation curves side-by-side allows you to instantly diagnose:\n",
"- **Overfitting:** Training loss continues falling while validation loss diverges upwards.\n",
"- **Underfitting:** Both training and validation losses plateau at unacceptable levels.\n",
"- **Learning Rate Too High:** Extreme volatility and oscillation in loss.\n"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with side-by-side Loss and Accuracy curves\n"
]
}
],
"source": [
"epochs = np.arange(1, 31)\n",
"train_loss = 1.8 * np.exp(-epochs / 6.0) + 0.12 + np.random.normal(0, 0.015, 30)\n",
"val_loss = 1.9 * np.exp(-epochs / 8.0) + 0.28 + 0.001 * (epochs - 14)**2 + np.random.normal(0, 0.02, 30)\n",
"\n",
"train_acc = 100 * (1 - 0.7 * np.exp(-epochs / 5.0)) + np.random.normal(0, 0.5, 30)\n",
"val_acc = 100 * (1 - 0.75 * np.exp(-epochs / 7.0)) - 0.015 * (epochs - 14)**2 + np.random.normal(0, 0.7, 30)\n",
"\n",
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.5), dpi=100, layout='constrained')\n",
"\n",
"# 1. Loss Subplot\n",
"ax1.plot(epochs, train_loss, color='#2b5c8f', linewidth=2, label='Train Loss')\n",
"ax1.plot(epochs, val_loss, color='#d95f02', linewidth=2, label='Val Loss')\n",
"ax1.axvline(14, color='#2ca02c', linestyle='--', label='Early Stop Epoch 14')\n",
"ax1.set_title(\"Cross-Entropy Loss Dynamics\", fontweight='bold')\n",
"ax1.set_xlabel(\"Epoch\")\n",
"ax1.set_ylabel(\"Loss\")\n",
"ax1.legend(frameon=True)\n",
"ax1.grid(True, linestyle=':', alpha=0.5)\n",
"ax1.spines[['top', 'right']].set_visible(False)\n",
"\n",
"# 2. Accuracy Subplot\n",
"ax2.plot(epochs, train_acc, color='#2b5c8f', linewidth=2, label='Train Accuracy')\n",
"ax2.plot(epochs, val_acc, color='#d95f02', linewidth=2, label='Val Accuracy')\n",
"ax2.axvline(14, color='#2ca02c', linestyle='--', label='Optimal Epoch 14')\n",
"ax2.set_title(\"Model Accuracy (%)\", fontweight='bold')\n",
"ax2.set_xlabel(\"Epoch\")\n",
"ax2.set_ylabel(\"Accuracy (%)\")\n",
"ax2.legend(frameon=True)\n",
"ax2.grid(True, linestyle=':', alpha=0.5)\n",
"ax2.spines[['top', 'right']].set_visible(False)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 14.2 Multi-Class Confusion Matrix Heatmap\n",
"A confusion matrix summarizes multi-class classification accuracy by contrasting **Actual Ground Truth** (rows) with **Predicted Classes** (columns).\n",
"\n",
"---\n",
"\n",
"### 14.3 ROC and Precision-Recall Curves\n",
"- **ROC Curve:** True Positive Rate ($\\text{Sensitivity}$) vs False Positive Rate ($1 - \\text{Specificity}$) across all classification thresholds. The **AUC (Area Under Curve)** score measures class separability ($1.0$ is perfect, $0.5$ is random guessing).\n",
"- **Precision-Recall Curve:** Essential for heavily imbalanced datasets (e.g. Fraud Detection 0.1% positive rate), where ROC AUC can look deceptively optimistic!\n"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with Confusion Matrix heatmap and ROC-AUC curve\n"
]
}
],
"source": [
"classes = ['Cat', 'Dog', 'Fox']\n",
"cm_raw = np.array([\n",
" [85, 10, 5],\n",
" [ 8, 90, 2],\n",
" [12, 15, 73]\n",
"])\n",
"cm_norm = cm_raw.astype('float') / cm_raw.sum(axis=1)[:, np.newaxis] * 100\n",
"\n",
"fpr = np.linspace(0, 1, 100)\n",
"tpr = 1.0 / (1.0 + np.exp(-6 * (fpr - 0.2)))\n",
"tpr[0] = 0.0\n",
"auc_score = 0.924\n",
"\n",
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5), dpi=100, layout='constrained')\n",
"\n",
"# --- Subplot 1: Confusion Matrix ---\n",
"im = ax1.imshow(cm_norm, cmap='Blues', vmin=0, vmax=100, interpolation='nearest')\n",
"ax1.set_title(\"Multi-Class Confusion Matrix (Normalized %)\", fontweight='bold')\n",
"ax1.set_xticks(np.arange(len(classes)))\n",
"ax1.set_yticks(np.arange(len(classes)))\n",
"ax1.set_xticklabels(classes, fontsize=10)\n",
"ax1.set_yticklabels(classes, fontsize=10)\n",
"ax1.set_xlabel(\"Predicted Label\", fontweight='semibold')\n",
"ax1.set_ylabel(\"True Ground Truth Label\", fontweight='semibold')\n",
"\n",
"for i in range(len(classes)):\n",
" for j in range(len(classes)):\n",
" color = \"white\" if cm_norm[i, j] > 50 else \"black\"\n",
" ax1.text(j, i, f\"{cm_norm[i, j]:.1f}%\\n({cm_raw[i, j]})\",\n",
" ha=\"center\", va=\"center\", color=color, fontsize=10, fontweight='bold')\n",
"fig.colorbar(im, ax=ax1, fraction=0.046, pad=0.04, label=\"Recall Percentage (%)\")\n",
"\n",
"# --- Subplot 2: ROC Curve ---\n",
"ax2.plot(fpr, tpr, color='#2b5c8f', linewidth=2.5, label=f'Model ROC (AUC = {auc_score:.3f})')\n",
"ax2.plot([0, 1], [0, 1], color='#7f7f7f', linestyle='--', linewidth=1.5, label='Random Baseline (AUC = 0.50)')\n",
"ax2.fill_between(fpr, 0, tpr, color='#2b5c8f', alpha=0.15)\n",
"\n",
"ax2.set_title(\"Receiver Operating Characteristic (ROC)\", fontweight='bold')\n",
"ax2.set_xlabel(\"False Positive Rate (1 - Specificity)\")\n",
"ax2.set_ylabel(\"True Positive Rate (Sensitivity / Recall)\")\n",
"ax2.set_xlim(-0.02, 1.02)\n",
"ax2.set_ylim(-0.02, 1.02)\n",
"ax2.grid(True, linestyle=':', alpha=0.6)\n",
"ax2.legend(loc='lower right', frameon=True)\n",
"ax2.spines[['top', 'right']].set_visible(False)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 14.4 Model Explainability: Feature Importance with Variance\n",
"Sorted horizontal bar charts with error bars reveal which variables drive your machine learning predictions most heavily.\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with sorted horizontal feature importances and error bars\n"
]
}
],
"source": [
"feature_names = ['Account Age', 'Annual Spend', 'App Logins', 'Support Tickets', 'Days Inactive', 'NPS Score']\n",
"importances = np.array([0.28, 0.22, 0.18, 0.14, 0.11, 0.07])\n",
"std_errors = np.array([0.03, 0.025, 0.02, 0.018, 0.015, 0.01])\n",
"\n",
"sorted_idx = np.argsort(importances)\n",
"pos = np.arange(len(sorted_idx))\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n",
"\n",
"bars = ax.barh(\n",
" pos,\n",
" importances[sorted_idx],\n",
" xerr=std_errors[sorted_idx],\n",
" align='center',\n",
" color='#2b5c8f',\n",
" edgecolor='black',\n",
" linewidth=0.5,\n",
" capsize=4,\n",
" error_kw={'ecolor': '#d95f02', 'elinewidth': 1.5}\n",
")\n",
"\n",
"ax.set_yticks(pos)\n",
"ax.set_yticklabels([feature_names[i] for i in sorted_idx], fontsize=10)\n",
"ax.set_xlabel(\"Relative Feature Importance (MDI / Gini)\", fontsize=10)\n",
"ax.set_title(\"Random Forest: Feature Importance with Tree-Variance Error Bars\", fontsize=11, fontweight='bold', pad=12)\n",
"ax.spines[['top', 'right']].set_visible(False)\n",
"ax.grid(axis='x', linestyle=':', alpha=0.6)\n",
"\n",
"for bar in bars:\n",
" width = bar.get_width()\n",
" ax.text(width + 0.035, bar.get_y() + bar.get_height()/2.0, f\"{width:.2f}\",\n",
" ha='left', va='center', fontsize=9, fontweight='semibold')\n",
"\n",
"ax.set_xlim(0, 0.38)\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 15. Performance, Memory Management & Publication Export\n",
"\n",
"When moving from interactive notebooks to automated pipelines, batch report generation, or web backends, Matplotlib introduces critical architectural challenges.\n",
"\n",
"---\n",
"\n",
"### 15.1 The Critical GUI Memory Leak Trap\n",
"A major trap in Python data pipelines is running a plotting loop like this:\n",
"\n",
"```python\n",
"# \u274c DANGEROUS MEMORY LEAK:\n",
"for df_chunk in large_data_generator:\n",
" fig, ax = plt.subplots()\n",
" ax.plot(df_chunk)\n",
" fig.savefig(f\"report_{i}.png\")\n",
" # plt.close() was forgotten!\n",
"```\n",
"\n",
"**Why does this leak memory?**\n",
"Matplotlib maintains an internal global GUI figure manager (`matplotlib._pylab_helpers.Gcf`) that retains strong Python references to every Figure created during the session. If you generate 10,000 plots in a loop without closing them, **your machine will run out of RAM and crash!**\n",
"\n",
"**The Solution:** Always explicitly close figures:\n",
"```python\n",
"# \u2705 ROBUST BATCH PATTERN:\n",
"for i, df_chunk in enumerate(large_data_generator):\n",
" fig, ax = plt.subplots()\n",
" try:\n",
" ax.plot(df_chunk)\n",
" fig.savefig(f\"report_{i}.png\")\n",
" finally:\n",
" plt.close(fig) # Immediately frees all buffers and memory!\n",
"```\n",
"\n",
"---\n",
"\n",
"### 15.2 Publication Export Standards: Vector vs. Raster\n",
"Choosing the correct file format when calling `fig.savefig()` is critical:\n",
"\n",
"| Format | Type | File Extension | Infinite Zoom / Scalable? | Best Used For |\n",
"| :--- | :--- | :--- | :--- | :--- |\n",
"| **PDF** | Vector | `.pdf` | **Yes** (Crystal clear at any zoom) | IEEE / ACM / Nature conference submissions |\n",
"| **SVG** | Vector | `.svg` | **Yes** (Crystal clear at any zoom) | Web dashboards, Figma editing, presentations |\n",
"| **PNG** | Raster | `.png` | No (Pixelates if zoomed) | Slack sharing, email reports, web thumbnails |\n",
"| **EPS** | Vector | `.eps` | **Yes** | Legacy scientific typesetting systems |\n",
"\n",
"### 15.3 Font Embedding for Scientific Journals\n",
"Academic publishers (IEEE, Springer, Nature) will reject figures where fonts are not embedded as TrueType vector glyphs.\n",
"Ensure compliance in your global setup:\n",
"```python\n",
"import matplotlib as mpl\n",
"mpl.rcParams['pdf.fonttype'] = 42 # Embed TrueType fonts in PDF (Type 42)\n",
"mpl.rcParams['ps.fonttype'] = 42 # Embed TrueType fonts in PostScript\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Active figures in Matplotlib memory initially: 0\n",
"Active figures after explicit plt.close(): 0 (Zero memory leaked!)\n",
"Publication font embedding standard configured (Type 42 TrueType).\n"
]
}
],
"source": [
"initial_figs = len(plt.get_fignums())\n",
"print(f\"Active figures in Matplotlib memory initially: {initial_figs}\")\n",
"\n",
"for i in range(5):\n",
" fig, ax = plt.subplots()\n",
" ax.plot([1, 2], [3, 4])\n",
" plt.close(fig)\n",
"\n",
"final_figs = len(plt.get_fignums())\n",
"print(f\"Active figures after explicit plt.close(): {final_figs} (Zero memory leaked!)\")\n",
"\n",
"mpl.rcParams['pdf.fonttype'] = 42\n",
"mpl.rcParams['font.sans-serif'] = 'Helvetica'\n",
"print(\"Publication font embedding standard configured (Type 42 TrueType).\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"---\n",
"## 16. Comprehensive Matplotlib Quick Reference Cheat Sheet\n",
"\n",
"Use this reference table for instant lookup during daily data science and machine learning work:\n",
"\n",
"| Visual Goal | Object-Oriented Method | Key Parameters & Keywords |\n",
"| :--- | :--- | :--- |\n",
"| **Figure & Axes Creation** | `fig, ax = plt.subplots()` | `figsize=(w, h)`, `dpi=100`, `layout='constrained'` |\n",
"| **Multi-Panel Mosaic** | `fig, axs = plt.subplot_mosaic()` | Blueprint list `[[\"A\", \"B\"], [\"A\", \"C\"]]` |\n",
"| **Line Plot** | `ax.plot(x, y)` | `color`, `linewidth`, `linestyle`, `marker`, `label` |\n",
"| **Shaded Confidence Band** | `ax.fill_between(x, y1, y2)` | `color`, `alpha=0.2`, `label` |\n",
"| **Scatter Plot** | `ax.scatter(x, y)` | `s` (size), `c` (color), `cmap`, `alpha`, `edgecolors` |\n",
"| **Colorbar** | `fig.colorbar(mappable, ax=ax)` | `pad`, `fraction`, `label`, `shrink` |\n",
"| **Vertical Bar Chart** | `ax.bar(x, height)` | `width`, `color`, `edgecolor`, `bottom` |\n",
"| **Horizontal Bar Chart** | `ax.barh(y, width)` | `height`, `color`, `edgecolor`, `left` |\n",
"| **Direct Bar Labels** | `ax.bar_label(container)` | `fmt='%.1f'`, `padding=3`, `fontweight='bold'` |\n",
"| **Histogram** | `ax.hist(data)` | `bins='auto'`, `density=True`, `histtype='step'` |\n",
"| **2D Hexbin Density** | `ax.hexbin(x, y)` | `gridsize=30`, `cmap='plasma'`, `mincnt=1` |\n",
"| **Box Plot** | `ax.boxplot(data)` | `patch_artist=True`, `notch=True`, `tick_labels` |\n",
"| **Violin Plot** | `ax.violinplot(data)` | `showmeans=False`, `showmedians=True` |\n",
"| **Heatmap / Matrix** | `ax.imshow(matrix)` | `cmap='coolwarm'`, `vmin=-1`, `vmax=1`, `interpolation='nearest'` |\n",
"| **Contour Map** | `ax.contourf(X, Y, Z)` | `levels=20`, `cmap='RdBu_r'`, `alpha=0.8` |\n",
"| **3D Axes** | `fig.add_subplot(projection='3d')` | `ax.scatter()`, `ax.plot_surface()`, `ax.view_init()` |\n",
"| **Twin Axes (Dual Y)** | `ax2 = ax.twinx()` | Share X-axis, independent right Y-axis |\n",
"| **Reference Line (Horiz)** | `ax.axhline(y=0)` | `color='gray'`, `linestyle='--'`, `linewidth=1` |\n",
"| **Reference Line (Vert)** | `ax.axvline(x=target)` | `color='red'`, `linestyle=':'`, `linewidth=1.5` |\n",
"| **Arrow Annotation** | `ax.annotate('text', xy, xytext)` | `arrowprops=dict(arrowstyle='->')` |\n",
"| **Axis Titles & Labels** | `ax.set_title()`, `ax.set_xlabel()` | `fontsize`, `fontweight='bold'`, `pad=10` |\n",
"| **Remove Border Spines** | `ax.spines[['top', 'right']].set_visible(False)` | De-clutter chart junk |\n",
"| **Save Figure** | `fig.savefig('plot.png')` | `dpi=300`, `bbox_inches='tight'`, `transparent=False` |\n",
"| **Free Memory** | `plt.close(fig)` or `plt.close('all')` | Essential inside loops and batch scripts |\n",
"\n",
"---\n",
"\n",
"### \ud83c\udfcb\ufe0f Companion Practice Exercises\n",
"Ready to test your visualization skills and build permanent muscle memory? Proceed to the hands-on companion exercise notebooks:\n",
"1. **Core Fundamentals Exercise:** [`02_matplotlib_exercise_1.ipynb`](02_matplotlib_exercise_1.ipynb) (20 progressive problems)\n",
"2. **Exercise 1 Solutions:** [`03_matplotlib_exercise_1_solutions.ipynb`](03_matplotlib_exercise_1_solutions.ipynb)\n",
"3. **Real-World ML & Analytical Scenarios:** [`04_matplotlib_exercise_2.ipynb`](04_matplotlib_exercise_2.ipynb) (15 production challenges)\n",
"4. **Exercise 2 Solutions:** [`05_matplotlib_exercise_2_solutions.ipynb`](05_matplotlib_exercise_2_solutions.ipynb)\n",
"\n",
"[\u2b06\ufe0f Back to Table of Contents](#table-of-contents)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 14.5 Classifier Calibration: Reliability Diagrams\n",
"A classifier with 90% accuracy might output uncalibrated probabilities (e.g. declaring 99% confidence when its true chance of correctness is only 60%).\n",
"A **Reliability Diagram (Calibration Curve)** plots predicted confidence against empirical observed frequency. A perfectly calibrated model falls exactly along the $y = x$ diagonal!\n"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Plot rendered with classifier calibration curve and diagonal reference\n"
]
}
],
"source": [
"# Predicted probabilities binned into deciles\n",
"prob_pred = np.array([0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95])\n",
"# Model A: Well-calibrated (close to diagonal)\n",
"emp_freq_a = np.array([0.06, 0.14, 0.27, 0.34, 0.48, 0.53, 0.67, 0.76, 0.84, 0.93])\n",
"# Model B: Overconfident (sharp sigmoid deviation)\n",
"emp_freq_b = np.array([0.01, 0.04, 0.10, 0.20, 0.35, 0.65, 0.80, 0.90, 0.96, 0.99])\n",
"\n",
"fig, ax = plt.subplots(figsize=(7, 5), dpi=100)\n",
"\n",
"ax.plot([0, 1], [0, 1], 'k--', label='Perfect Calibration (Diagonal)')\n",
"ax.plot(prob_pred, emp_freq_a, marker='o', color='#2b5c8f', lw=2, label='Calibrated Model A (Brier = 0.03)')\n",
"ax.plot(prob_pred, emp_freq_b, marker='s', color='#d95f02', lw=2, label='Overconfident Model B (Brier = 0.12)')\n",
"\n",
"ax.set_title(\"Probability Calibration Reliability Diagram\", fontweight='bold', pad=12)\n",
"ax.set_xlabel(\"Mean Predicted Probability Confidence\")\n",
"ax.set_ylabel(\"Empirical True Positive Frequency\")\n",
"ax.set_xlim(-0.02, 1.02)\n",
"ax.set_ylim(-0.02, 1.02)\n",
"ax.grid(True, linestyle=':', alpha=0.6)\n",
"ax.legend(loc='upper left', frameon=True)\n",
"ax.spines[['top', 'right']].set_visible(False)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 15.4 Interactive vs Headless Backends (`mpl.use('Agg')`)\n",
"When running automated model evaluation scripts on cloud servers (AWS EC2, Docker containers, CI/CD runners), there is no graphical monitor connected.\n",
"Attempting to open a GUI window causes `TclError: no display name` crashes.\n",
"To run headless without any graphical window server, set the **`Agg`** backend before importing `pyplot`:\n",
"\n",
"```python\n",
"import matplotlib\n",
"matplotlib.use('Agg') # Pure non-interactive raster rendering engine\n",
"import matplotlib.pyplot as plt\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Current active rendering backend: macosx\n",
"Backend is headless-compatible: True\n"
]
}
],
"source": [
"print(f\"Current active rendering backend: {mpl.get_backend()}\")\n",
"print(\"Backend is headless-compatible:\", mpl.get_backend().lower() in ['agg', 'module://matplotlib_inline.backend_inline', 'macosx'])\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}