0% found this document useful (0 votes)
2 views66 pages

Matplotlib AI ML Part1

This document is a comprehensive study guide for using Matplotlib in AI and machine learning, covering the first ten chapters. It introduces Matplotlib as a key Python library for data visualization, explains its installation and setup in various environments, and details basic plotting techniques. The guide is designed for students at different skill levels and emphasizes the importance of visualization in the AI/ML workflow.

Uploaded by

Harinder Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views66 pages

Matplotlib AI ML Part1

This document is a comprehensive study guide for using Matplotlib in AI and machine learning, covering the first ten chapters. It introduces Matplotlib as a key Python library for data visualization, explains its installation and setup in various environments, and details basic plotting techniques. The guide is designed for students at different skill levels and emphasizes the importance of visualization in the AI/ML workflow.

Uploaded by

Harinder Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

📊 MATPLOTLIB
for Artificial Intelligence & Machine Learning
Part 1 of 2 · Chapters 1–10

A Comprehensive Study Guide for AI/ML Students

Part 1 Coverage
Introduction • Setup • Basic Plotting • Line Charts • Bar Graphs
Histograms • Scatter Plots • Pie Charts • Subplots • Customization

Designed for University Semester Preparation & Project Work


Beginner · Intermediate · Advanced Concepts Included

Matplotlib for AI & Machine Learning Page 1


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Table of Contents
TOC \h \o "1-3" \t "Heading 1,1,Heading 2,2,Heading 3,3"

Matplotlib for AI & Machine Learning Page 2


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 1: Introduction to Matplotlib


Matplotlib is the foundation of data visualization in Python. Before you write a single line of machine
learning code, understanding how to visualize your data is one of the most important skills you can
develop. This chapter gives you a solid foundation of what Matplotlib is, why it matters, and how it fits
into the broader AI/ML ecosystem.

1.1 What is Matplotlib?


Matplotlib is an open-source, cross-platform plotting library for Python. It was originally created by John
D. Hunter in 2003, inspired by MATLAB's plotting capabilities. Today, it is the most widely used Python
library for 2D (and limited 3D) data visualization.
Think of Matplotlib as your digital graph paper. Just as a scientist draws charts on paper to understand
data, Matplotlib lets you create those charts programmatically — and much more powerfully.

Key Facts About Matplotlib


• Creator: John D. Hunter (2003)
• Current Maintainer: Matplotlib Development Team (NumFOCUS sponsored)
• Language: Pure Python with optional C extensions for performance
• License: BSD License (free to use in commercial projects)
• Website: [Link]
• Current Stable Version: Matplotlib 3.8+ (as of 2024)
• Dependency: Requires NumPy

📘 NOTE
Matplotlib works hand-in-hand with NumPy and Pandas. In AI/ML projects, you typically import all
three together: import numpy as np, import pandas as pd, import [Link] as plt

1.2 Why Visualization Matters in AI/ML


In machine learning, raw numbers are rarely enough. You need to SEE the data to understand it. Here
is why visualization is critical at every stage of an AI/ML pipeline:

Stage Visualization Purpose Example

Data Collection Understand data structure and size Plot number of records per class

Exploratory Analysis Find patterns, outliers, distributions Histograms, scatter plots

Data Preprocessing Check normalization, missing values Before/after scaling plots

Model Training Monitor learning progress Loss curves, accuracy curves

Model Evaluation Assess performance visually Confusion matrix heatmap

Result Present findings to stakeholders Feature importance bar charts


Communication
Table 1.1 – Role of Visualization in the ML Pipeline

Matplotlib for AI & Machine Learning Page 3


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Why Every AI/ML Engineer Must Know Matplotlib


• Debugging models: When your model performs poorly, visualizing predictions vs actual values
helps identify the problem faster than reading raw numbers.
• Understanding data bias: Class imbalance, feature skewness, and outliers are best detected
through visual inspection — pie charts, histograms, box plots.
• Communicating results: Business stakeholders understand graphs, not matrices of numbers.
Matplotlib helps bridge the gap.
• Research publications: Academic papers require high-quality figures that Matplotlib can
produce with publication-level quality.
• Kaggle competitions: Winners routinely showcase deep data understanding through
visualizations — Matplotlib is a primary tool.

1.3 Features of Matplotlib


Matplotlib is packed with features that make it extremely powerful and flexible:

Feature Category Description

Plot Types Line, bar, scatter, pie, histogram, box plot, area, contour,
heatmap, 3D, polar

Customization Colors, fonts, markers, line styles, fills, transparency (alpha),


annotations

Multiple Axes Subplots, insets, twin axes — display several charts on one
figure

Output Formats PNG, SVG, PDF, EPS, JPEG — vector and raster formats

Interactive Mode Works in Jupyter Notebooks, IPython, standalone GUIs

Backends Agg, TkAgg, Qt5Agg, WebAgg — render to screen or file

Integration Works with NumPy, Pandas, SciPy, Seaborn, Scikit-learn

LaTeX Support Render mathematical equations in titles and labels

Animation Create animated plots with FuncAnimation

Toolkits mpl_toolkits for 3D plots (Axes3D), toolbox extensions


Table 1.2 – Matplotlib Feature Overview

1.4 The Matplotlib Architecture


Matplotlib has a layered architecture with three main layers that work together:

• Backend Layer — The lowest level. Handles rendering to screen or file. Different backends
(Agg, TkAgg, WebAgg) handle different environments.
• Artist Layer — The middle layer. Everything drawn on a figure is an 'Artist' object: Figure, Axes,
Axis, Line2D, Text, Rectangle, etc. This gives fine-grained control.

Matplotlib for AI & Machine Learning Page 4


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

• Scripting Layer (pyplot) — The top-level API we use most. [Link] (usually imported
as plt) provides a MATLAB-like interface that is quick and easy for most use cases.

✅ TIP
For beginners and most AI/ML work, the pyplot (plt) interface is all you need. The Artist layer is
useful for advanced customization in production code or automated report generation.

1.5 Applications of Matplotlib in Data Science


Matplotlib is used across the entire data science spectrum. Here are some real-world applications:

Healthcare & Medical AI


• Plotting patient vital signs over time (time-series line charts)
• Visualizing MRI scan pixel distributions (histograms)
• Showing drug trial outcomes across patient groups (grouped bar charts)

Finance & Algorithmic Trading


• Stock price candlestick charts and trend lines
• Portfolio performance comparison over time
• Risk heatmaps for correlated assets

Natural Language Processing (NLP)


• Word frequency distribution plots (bar charts)
• Sentiment score distributions across datasets
• Training loss curves for transformer models

Computer Vision
• Displaying images with [Link]()
• Plotting bounding box overlays on detection results
• Visualizing feature maps from CNN layers

Chapter 1 Summary
Chapter 1 Key Takeaways
• Matplotlib is Python's most popular 2D plotting library, created in 2003
• Visualization is critical at every stage: EDA, training, evaluation, and communication
• Three layers: Backend, Artist, and Scripting (pyplot) — we mostly use pyplot
• Supports dozens of chart types, rich customization, and multiple output formats
• Used in healthcare, finance, NLP, computer vision, and almost every AI domain

Matplotlib for AI & Machine Learning Page 5


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 2: Installing and Setting Up Matplotlib


Before you can start visualizing data, you need to install Matplotlib and configure your development
environment. This chapter walks you through every setup scenario — local machine, Jupyter Notebook,
and Google Colab.

2.1 Installing via pip


The simplest way to install Matplotlib is using pip, Python's package installer.

Basic Installation
# Install Matplotlib using pip
pip install matplotlib

# Install a specific version


pip install matplotlib==3.8.0

# Upgrade to the latest version


pip install --upgrade matplotlib

# Install with NumPy and Pandas (recommended for ML)


pip install matplotlib numpy pandas

Verify Installation
import matplotlib
print(matplotlib.__version__)

# Expected output:
# 3.8.x (or your installed version)

3.8.2

✅ TIP
Always install Matplotlib inside a virtual environment (venv or conda) to avoid conflicts between
different projects. Use: python -m venv myenv && source myenv/bin/activate (Linux/Mac) or myenv\
Scripts\activate (Windows)

Installing in a Conda Environment (Recommended for ML)


# Create a new conda environment for ML projects
conda create -n mlenv python=3.11

# Activate the environment


conda activate mlenv

# Install Matplotlib via conda-forge (more stable builds)


conda install -c conda-forge matplotlib

# Or install the full scientific stack at once


conda install numpy pandas matplotlib scikit-learn jupyter

Matplotlib for AI & Machine Learning Page 6


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

2.2 Setting Up in Jupyter Notebook


Jupyter Notebook is the most popular environment for data science and machine learning. It allows you
to see plots inline, right below the code cell that generates them.

Install Jupyter
pip install jupyter notebook

# Or with JupyterLab (more modern interface)


pip install jupyterlab

Inline Plotting in Jupyter


# This magic command MUST be at the top of your notebook
# It makes plots appear inline instead of opening a new window
%matplotlib inline

# Now import and plot


import [Link] as plt
import numpy as np

x = [Link](0, 10, 100)


y = [Link](x)

[Link](x, y)
[Link]('Sine Wave')
[Link]()

✅ TIP
Use %matplotlib notebook (instead of inline) for interactive, zoomable plots inside Jupyter. Use
%matplotlib widget in JupyterLab with ipympl installed for even richer interactivity.

Useful Jupyter Magic Commands for Matplotlib


Magic Command Effect

%matplotlib inline Static plot image embedded in notebook (default, recommended)

%matplotlib notebook Interactive plot with zoom/pan inside notebook

%matplotlib widget Interactive plot in JupyterLab (requires ipympl)

%matplotlib qt Opens plot in a separate Qt window

%matplotlib tk Opens plot in a separate Tkinter window


Table 2.1 – Jupyter Matplotlib Magic Commands

Matplotlib for AI & Machine Learning Page 7


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

2.3 Using Matplotlib in Google Colab


Google Colab is a free, cloud-based Jupyter environment. Matplotlib comes pre-installed, so no setup is
needed!

# In Google Colab — Matplotlib is already installed!


# Just import and use directly

import [Link] as plt


import numpy as np

# Create a simple plot


x = [1, 2, 3, 4, 5]
y = [10, 25, 15, 30, 20]

[Link](figsize=(8, 5))
[Link](x, y, color='blue', marker='o', linewidth=2)
[Link]('My First Colab Plot', fontsize=14)
[Link]('X Values')
[Link]('Y Values')
[Link](True)
[Link]()

✅ TIP
Google Colab tip: Use [Link]('[Link]') and then [Link]('[Link]') to save and
download your plots to your local machine.

Saving Plots to Google Drive from Colab


from [Link] import drive
[Link]('/content/drive')

# Save plot directly to Google Drive


[Link]('/content/drive/My Drive/my_plot.png', dpi=300, bbox_inches='tight')
print('Plot saved to Google Drive!')

2.4 Importing pyplot — The Standard Convention


In every Python script and notebook that uses Matplotlib, you'll see the same import at the top.
Understanding these imports is foundational.

# The standard Matplotlib import — ALWAYS use this alias


import [Link] as plt

# Supporting library imports (almost always needed together)


import numpy as np # For numerical arrays
import pandas as pd # For DataFrames

# Optional: Set figure size globally for the entire notebook


[Link]['[Link]'] = (10, 6)

# Optional: Set default font size


[Link]['[Link]'] = 12

Matplotlib for AI & Machine Learning Page 8


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

# Optional: Use a pre-built style


[Link]('seaborn-v0_8-darkgrid')

print('Matplotlib imported successfully!')


print(f'Version: {[Link].__version__}')

Matplotlib imported successfully!


Version: 3.8.2

Understanding rcParams — Global Settings


rcParams (runtime configuration parameters) allow you to set default styles for all plots in a session.
This is very useful in ML notebooks to maintain consistent visual style.

import [Link] as plt

# View ALL available rcParams (there are hundreds!)


# print([Link]) # Uncomment to see all

# Common rcParams settings for ML notebooks


[Link]({
'[Link]': (12, 6), # Default figure size
'[Link]': 100, # Dots per inch (resolution)
'[Link]': 12, # Default font size
'[Link]': 14, # Title font size
'[Link]': 12, # Axis label size
'[Link]': 2, # Default line width
'[Link]': 8, # Default marker size
'[Link]': True, # Show grid by default
'[Link]': 0.3, # Grid transparency
})

print('Global settings applied!')

2.5 Available Plot Styles


Matplotlib includes many built-in styles that instantly transform the look of your plots. This is especially
useful for making professional-looking ML reports.

import [Link] as plt

# List all available styles


print([Link])

['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic',


'dark_background', 'fast', 'fivethirtyeight', 'ggplot',
'grayscale', 'seaborn-v0_8', 'seaborn-v0_8-darkgrid',
'seaborn-v0_8-whitegrid', 'tableau-colorblind10', ...]

# Apply a style — place this BEFORE your plot code


[Link]('ggplot') # R-like ggplot style
[Link]('seaborn-v0_8') # Clean seaborn style
[Link]('dark_background') # Dark theme
[Link]('fivethirtyeight') # FiveThirtyEight journalism style

Matplotlib for AI & Machine Learning Page 9


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

# Reset to default
[Link]('default')

Figure 2.1 – Sine wave plotted with [Link]() in a Jupyter environment

Chapter 2 Summary
Chapter 2 Key Takeaways
• Install with: pip install matplotlib (or conda install matplotlib)
• In Jupyter: use %matplotlib inline magic command for inline plots
• Google Colab: Matplotlib is pre-installed, just import and use
• Standard import: import [Link] as plt
• Use [Link] to set global defaults and [Link]() for themes

Matplotlib for AI & Machine Learning Page 10


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 3: Basic Plotting


In this chapter, you'll learn the fundamental building blocks of every Matplotlib visualization. These core
functions — plot(), figure(), show(), labels, legends, and grids — form the foundation for every chart
type you'll create in AI/ML work.

3.1 Your First Plot — [Link]()


The plot() function is the most basic and versatile plotting function in Matplotlib. It draws a line or a
series of points.

import [Link] as plt


import numpy as np

# Simple line plot — most basic form


x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

[Link](x, y)
[Link]()

>> A simple window appears showing a straight diagonal line from (1,2) to (5,10)

# More complete example with all basic components


import [Link] as plt
import numpy as np

# Generate data
x = [Link](0, 10, 50) # 50 points from 0 to 10
y = x ** 2 # y = x squared

# Create the plot


[Link](x, y, color='steelblue', linewidth=2, linestyle='-')

# Add labels and title


[Link]('Quadratic Function: y = x²', fontsize=16, fontweight='bold')
[Link]('X Values', fontsize=12)
[Link]('Y Values (X squared)', fontsize=12)

# Add grid
[Link](True, alpha=0.3)

# Display
[Link]()

>> A smooth curve going from (0,0) upward to (10,100) — a classic parabola.
>> The grid lines make it easy to read values off the chart.
>> Title appears in bold at the top; axis labels are on each side.

Matplotlib for AI & Machine Learning Page 11


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 3.1 – Quadratic function y = x² plotted with title, axis labels, and grid

3.2 Understanding [Link]()


The figure() function creates a new figure (the blank canvas on which you draw). Always call this before
plotting when you need to control size, resolution, or have multiple separate plots.

import [Link] as plt


import numpy as np

# Create a figure with custom size and resolution


# figsize=(width, height) in INCHES
# dpi = dots per inch (higher = sharper, larger file size)
fig = [Link](figsize=(10, 6), dpi=100)

# Plot on this figure


x = [Link](0, 2*[Link], 100)
[Link](x, [Link](x), label='sin(x)', color='blue')
[Link](x, [Link](x), label='cos(x)', color='red')

[Link]('Sine and Cosine Waves')


[Link]('Angle (radians)')
[Link]('Amplitude')
[Link]()
[Link](True, alpha=0.3)
[Link]()

>> A 10x6 inch figure shows two waves.


>> Blue sine wave oscillates between -1 and +1.
>> Red cosine wave is offset by π/2 from the sine wave.
>> Legend box appears showing 'sin(x)' and 'cos(x)' labels.

Matplotlib for AI & Machine Learning Page 12


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 3.2 – Sine and cosine waves plotted on the same figure with legend

figsize Parameter Use Case

(6, 4) Standard small plot, presentations

(8, 5) Medium plot, Jupyter notebook default

(10, 6) Wide plot, multiple lines

(12, 8) Large detailed chart, publications

(14, 5) Very wide plot, time-series data

(6, 6) Square plot, confusion matrix, heatmap


Table 3.1 – Common Figure Sizes for Different Use Cases

3.3 [Link]() — Displaying the Plot


[Link]() renders and displays the figure. Without it, in script files (.py), the plot won't appear. In
Jupyter with %matplotlib inline, it's optional but recommended for clarity.

import [Link] as plt

# Always call [Link]() after ALL plot commands


[Link]([1, 2, 3], [4, 5, 6])
[Link]('Simple Plot')
[Link]() # <-- This displays AND clears the figure

# After show(), the figure is cleared


# Start fresh for next plot
[Link]([1, 2, 3], [6, 5, 4])
[Link]('Another Plot')

Matplotlib for AI & Machine Learning Page 13


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

[Link]()

💡 IMPORTANT
In .py script files: [Link]() blocks execution until you close the window. In Jupyter: it displays the
plot inline. In automated scripts (e.g., saving plots to disk): replace [Link]() with
[Link]('[Link]') and [Link]().

3.4 Adding Labels and Titles


Labels and titles are essential for making your plots readable and professional. In ML reports, always
label your axes clearly.

import [Link] as plt


import numpy as np

# Training accuracy example (very common in ML)


epochs = [Link](1, 21) # Epochs 1 to 20
train_acc = [0.55, 0.62, 0.68, 0.72, 0.75, 0.78, 0.80, 0.82,
0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.90, 0.91,
0.91, 0.92, 0.92, 0.93]

[Link](figsize=(10, 5))
[Link](epochs, train_acc, color='royalblue', linewidth=2)

# Title — use fontsize, fontweight, pad for spacing


[Link]('Model Training Accuracy Over Epochs',
fontsize=16, fontweight='bold', pad=15)

# Axis labels — always include units or context


[Link]('Epoch Number', fontsize=13, labelpad=10)
[Link]('Accuracy Score (0-1)', fontsize=13, labelpad=10)

# Set axis limits (optional but useful)


[Link](1, 20)
[Link](0.50, 1.00)

[Link](True, alpha=0.3)
plt.tight_layout() # Prevents label clipping
[Link]()

>> A rising accuracy curve from epoch 1 (~0.55) to epoch 20 (~0.93).


>> Bold title at top. Clear axis labels with adequate spacing.
>> Y-axis ranges from 0.50 to 1.00, making the improvement clearly visible.
>> tight_layout() ensures nothing is cut off at the edges.

Title and Label Formatting Parameters


Parameter Description Example Value

fontsize Font size in points 12, 14, 'large', 'x-large'

fontweight Font weight 'normal', 'bold', 'heavy'

fontstyle Font style 'normal', 'italic'

color Text color 'black', '#2E75B6', 'red'

pad / labelpad Padding (space from axis) 10, 15

Matplotlib for AI & Machine Learning Page 14


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

loc Title alignment 'center', 'left', 'right'


Table 3.2 – Text Formatting Parameters for Labels and Titles

3.5 Adding Legends


Legends identify different lines or series on the same plot. In ML, you'll use legends constantly to
distinguish training vs validation curves, different models, or different classes.

import [Link] as plt


import numpy as np

epochs = [Link](1, 21)


train_loss = [0.95, 0.82, 0.71, 0.63, 0.57, 0.52, 0.48, 0.44,
0.41, 0.38, 0.36, 0.34, 0.32, 0.31, 0.30, 0.29,
0.28, 0.27, 0.27, 0.26]
val_loss = [1.02, 0.88, 0.78, 0.71, 0.67, 0.63, 0.60, 0.58,
0.57, 0.56, 0.56, 0.57, 0.58, 0.59, 0.60, 0.61,
0.62, 0.63, 0.64, 0.65]

[Link](figsize=(10, 5))

# label= parameter feeds the legend


[Link](epochs, train_loss, color='steelblue', linewidth=2,
marker='o', markersize=4, label='Training Loss')
[Link](epochs, val_loss, color='tomato', linewidth=2,
marker='s', markersize=4, label='Validation Loss')

[Link]('Training vs Validation Loss', fontsize=15, fontweight='bold')


[Link]('Epoch')
[Link]('Loss')

# Add legend — loc can be: 'upper right', 'lower left', 'best', etc.
[Link](loc='upper right', fontsize=11, framealpha=0.9)

# Highlight overfitting zone (where val loss starts rising)


[Link](x=11, color='orange', linestyle='--', alpha=0.7,
label='Overfitting Starts')
[Link](loc='upper right', fontsize=11) # Re-call to include new item

[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

>> Training loss (blue) decreases steadily across all 20 epochs.


>> Validation loss (red) decreases until ~epoch 11, then starts rising.
>> Orange dashed vertical line marks the overfitting boundary.
>> Legend shows all three items with color-coded labels.

Legend Location Options


loc String Position When to Use

'best' Auto-selects least obstructive General use (default)

'upper right' Top-right corner Curves that start high

'upper left' Top-left corner Curves that start low

Matplotlib for AI & Machine Learning Page 15


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

'lower right' Bottom-right corner Upward-trending curves

'lower left' Bottom-left corner Downward-trending curves

'center' Middle of axes Rarely; obstructs data

'outside right' Outside the plot area When data fills entire area
Table 3.3 – Legend Location Options

3.6 Adding Grids


Grid lines make it easier to read values from charts. They're especially important in loss/accuracy
curves where you want to track specific values.

import [Link] as plt


import numpy as np

x = [Link](0, 10, 100)


y = [Link](x) * [Link](-x/10) # Damped sine wave

fig, axes = [Link](1, 2, figsize=(14, 5))

# Left: No grid
axes[0].plot(x, y, color='navy', linewidth=2)
axes[0].set_title('Without Grid', fontsize=13)
axes[0].set_xlabel('Time')
axes[0].set_ylabel('Amplitude')

# Right: With full grid styling


axes[1].plot(x, y, color='navy', linewidth=2)
axes[1].set_title('With Styled Grid', fontsize=13)
axes[1].set_xlabel('Time')
axes[1].set_ylabel('Amplitude')

# Grid styling options


axes[1].grid(True,
which='major', # 'major', 'minor', or 'both'
axis='both', # 'x', 'y', or 'both'
color='gray',
linestyle='--',
linewidth=0.7,
alpha=0.4)

plt.tight_layout()
[Link]()

>> Left panel: clean plot with no grid — harder to read specific values.
>> Right panel: dashed gray grid lines at 0.4 opacity — easy to read values
>> without distracting from the actual curve.

✅ TIP
Best practice for ML plots: Use alpha=0.3 to 0.5 for grid lines. This keeps grids helpful without
overwhelming the data. Use [Link](True, ls='--', alpha=0.4) as your standard.

Matplotlib for AI & Machine Learning Page 16


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

3.7 Saving Plots


In real AI/ML projects, you'll often need to save plots to files for reports, papers, or dashboards.

import [Link] as plt


import numpy as np

x = [Link](0, 10, 100)


[Link](figsize=(10, 6))
[Link](x, [Link](x), linewidth=2, color='steelblue')
[Link]('Saved Plot Example')
[Link]('X'); [Link]('Y')
[Link](True, alpha=0.3)

# Save to file — BEFORE [Link]()


[Link]('my_plot.png',
dpi=150, # Resolution (72=screen, 150=good, 300=print)
bbox_inches='tight', # Don't clip labels
facecolor='white', # Background color
format='png') # 'png', 'jpg', 'svg', 'pdf'

[Link]()
print('Plot saved as my_plot.png')

Figure 3.3 – tight_layout() demo: three subplots with no overlapping labels

Chapter 3 Summary
Chapter 3 Key Takeaways
• [Link](x, y) — core function for line and point charts
• [Link](figsize=(...)) — set canvas size before plotting
• [Link](), [Link](), [Link]() — always add these for clarity
• [Link]() — required when plotting multiple series (train vs val)
• [Link](True, alpha=0.3) — standard grid for readable ML plots
• [Link]('[Link]', dpi=150, bbox_inches='tight') — save before show()

Matplotlib for AI & Machine Learning Page 17


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 4: Line Charts


Line charts are the bread-and-butter of AI/ML visualization. Training loss curves, accuracy progression,
learning rate schedules, model comparison plots — all are line charts. Master this chapter and you'll
handle 60% of your ML visualization needs.

4.1 Plotting Multiple Lines


Multiple lines on one plot let you compare different models, training runs, or metrics side by side.

import [Link] as plt


import numpy as np

# Simulate 4 different ML model accuracies over 30 epochs


[Link](42)
epochs = [Link](1, 31)

def gen_accuracy(base, noise=0.02):


acc = base + 0.35 * (1 - [Link](-epochs/7))
acc += [Link](0, noise, len(epochs))
return [Link](acc, 0, 1)

acc_lr = gen_accuracy(0.55) # Logistic Regression


acc_dt = gen_accuracy(0.60) # Decision Tree
acc_rf = gen_accuracy(0.68) # Random Forest
acc_nn = gen_accuracy(0.65) # Neural Network

[Link](figsize=(12, 6))

# Multiple plot() calls = multiple lines


[Link](epochs, acc_lr, label='Logistic Regression', linewidth=2)
[Link](epochs, acc_dt, label='Decision Tree', linewidth=2)
[Link](epochs, acc_rf, label='Random Forest', linewidth=2)
[Link](epochs, acc_nn, label='Neural Network', linewidth=2)

[Link]('Model Accuracy Comparison Over Training Epochs',


fontsize=15, fontweight='bold')
[Link]('Epoch Number', fontsize=12)
[Link]('Validation Accuracy', fontsize=12)
[Link](fontsize=11, loc='lower right')
[Link](True, alpha=0.3)
[Link](0.5, 1.0)
plt.tight_layout()
[Link]()

>> Four rising curves, each with slightly different starting points and noise.
>> Random Forest (typically) reaches highest accuracy.
>> Legend in lower right identifies each model line.
>> This exact plot appears in model comparison sections of ML papers.

4.2 Line Styling — Colors, Markers, Widths, Styles


Line styling makes your plots visually distinct and professional. When comparing multiple models,
distinct styling helps readers immediately differentiate lines even in black-and-white printouts.

Matplotlib for AI & Machine Learning Page 18


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

import [Link] as plt


import numpy as np

x = [Link](0, 10, 50)

[Link](figsize=(12, 7))

# Syntax: [Link](x, y, color=..., linestyle=..., linewidth=...,


# marker=..., markersize=..., markerfacecolor=...)

[Link](x, [Link](x), color='#2E75B6', linestyle='-',


linewidth=2.5, marker='o', markersize=5, label='Solid + Circle')

[Link](x, [Link](x)+0.5, color='tomato', linestyle='--',


linewidth=2, marker='s', markersize=6, label='Dashed + Square')

[Link](x, [Link](x)+1.0, color='green', linestyle='-.',


linewidth=2, marker='^', markersize=7, label='Dash-Dot + Triangle')

[Link](x, [Link](x)+1.5, color='purple', linestyle=':',


linewidth=2.5, marker='D', markersize=6, label='Dotted + Diamond')

[Link](x, [Link](x)+2.0, color='orange', linestyle='-',


linewidth=3, marker='*', markersize=9, label='Thick + Star')

[Link]('Line Style Combinations in Matplotlib', fontsize=14,


fontweight='bold')
[Link]('X'); [Link]('Y')
[Link](loc='upper right', fontsize=10)
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

>> Five lines with distinct combinations of color, style, and marker.
>> Each combination remains distinguishable both in color and in black/white.
>> Star markers on orange line stand out visually at key data points.

Complete Reference: Line Styles, Colors, Markers


Property Options / Values Shorthand

linestyle '-' solid, '--' dashed, '-.' dash-dot, ':' dotted, 'None' ls=
no line

linewidth Float value: 0.5 (thin) to 5.0 (thick), default=1.5 lw=

color Name, hex (#RRGGBB), RGB tuple, or shorthand c=


(r,g,b,c,m,y,k,w)

marker 'o' circle, 's' square, '^' triangle, 'D' diamond, '*' star,
'+' plus, 'x' cross, '.' point, ',' pixel

markersize Float value: 3 (small) to 12 (large), default=6 ms=

markerfacecolor Fill color of marker (any color spec) mfc=

markeredgecolor Border color of marker mec=

alpha Transparency: 0.0 (invisible) to 1.0 (opaque)

label String for legend display


Table 4.1 – Line Plot Styling Properties

Matplotlib for AI & Machine Learning Page 19


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

4.3 Color Options in Detail


Matplotlib supports multiple ways to specify colors. Understanding all of them helps you create
consistent, branded visuals for ML projects.

import [Link] as plt

fig, ax = [Link](figsize=(12, 5))

y_positions = range(8)
colors = [
('Named Color', 'steelblue', 'steelblue'),
('Named Color', 'tomato', 'tomato'),
('Hex Code', '#2E75B6', '#2E75B6'),
('Hex Code', '#E87722', '#E87722'),
('Short Code', 'r', 'r = red'),
('Short Code', 'g', 'g = green'),
('RGB Tuple', (0.2, 0.6, 0.9), '(0.2, 0.6, 0.9)'),
('Grayscale', '0.7', '0.7 = light gray'),
]

for i, (ctype, col, label) in enumerate(colors):


[Link]([0, 10], [i, i], color=col, linewidth=6, label=f'{ctype}: {label}')

ax.set_yticks(list(y_positions))
ax.set_title('Matplotlib Color Specification Methods', fontsize=14)
[Link](loc='center right', fontsize=9)
plt.tight_layout()
[Link]()

4.4 Using fmt Shorthand


Matplotlib has a compact format string (fmt) that combines color, marker, and line style into a single
string. This is very convenient for quick exploratory plots.

import [Link] as plt


import numpy as np

x = [Link](0, 10, 20)


y = [Link](x)

# fmt = '[color][marker][linestyle]'
[Link](figsize=(12, 4))

[Link](1, 3, 1); [Link](x, y, 'bo-', linewidth=1.5)


[Link]("'bo-': Blue Circle Solid")

[Link](1, 3, 2); [Link](x, y, 'r^--', linewidth=1.5)


[Link]("'r^--': Red Triangle Dashed")

[Link](1, 3, 3); [Link](x, y, 'gs:', linewidth=1.5)


[Link]("'gs:': Green Square Dotted")

plt.tight_layout()
[Link]()

Matplotlib for AI & Machine Learning Page 20


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

>> Three subplots each showing the sine wave with different fmt combinations.
>> 'bo-': blue circles connected by solid line
>> 'r^--': red triangles connected by dashed line
>> 'gs:': green squares connected by dotted line

4.5 Real ML Example — Learning Rate Comparison


This example shows a real-world ML use case: comparing how different learning rates affect training
loss convergence.

import [Link] as plt


import numpy as np

# Simulate training loss for different learning rates


epochs = [Link](1, 51)

def sim_loss(lr, noise=0.005):


"""Simulate training loss curve for a given learning rate"""
if lr > 0.1: # Too large: unstable
loss = 0.9 * [Link](-epochs * lr * 0.3) + 0.1
loss += [Link](0, 0.05, len(epochs))
else:
loss = 0.85 * [Link](-epochs * lr * 3) + 0.05
loss += [Link](0, noise, len(epochs))
return [Link](loss, 0.01, 1.0)

[Link](0)
lrs = {'lr=0.001 (Too Small)': 0.001,
'lr=0.01 (Good)': 0.01,
'lr=0.1 (Optimal)': 0.1,
'lr=0.5 (Too Large)': 0.5}

colors = ['steelblue', 'green', 'orange', 'red']


linestyles = ['--', '-', '-', ':']

[Link](figsize=(12, 6))
for (name, lr), col, ls in zip([Link](), colors, linestyles):
[Link](epochs, sim_loss(lr), color=col, linestyle=ls,
linewidth=2, label=name)

[Link]('Effect of Learning Rate on Training Loss',


fontsize=15, fontweight='bold')
[Link]('Training Epoch', fontsize=12)
[Link]('Training Loss', fontsize=12)
[Link](fontsize=11, loc='upper right')
[Link]('log') # Log scale for loss is standard in ML
[Link](True, which='both', alpha=0.3)
plt.tight_layout()
[Link]()

>> Four distinct loss curves showing the effect of learning rate.
>> Small LR (blue dashed): slow convergence — still high at epoch 50
>> Good LR (green solid): steady smooth decrease
>> Optimal LR (orange solid): fastest clean convergence
>> Too-large LR (red dotted): noisy, oscillates, may diverge
>> Log scale on Y axis makes small differences at low loss visible.

Matplotlib for AI & Machine Learning Page 21


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 4.5 – Effect of learning rate on training loss (log scale): too small, good, optimal, too large

Chapter 4 Summary
Chapter 4 Key Takeaways
• Multiple lines: call [Link]() multiple times with different label= values
• Line styling: color=, linestyle=, linewidth=, marker=, markersize=
• fmt shorthand: 'bo-' = blue, circle, solid; 'r^--' = red, triangle, dashed
• [Link]('log') — use log scale for loss curves in ML
• Key ML use case: loss curves, accuracy curves, learning rate comparison

Matplotlib for AI & Machine Learning Page 22


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 5: Bar Graphs


Bar graphs are essential for comparing discrete categories — model performance comparison, class
distribution analysis, feature importance ranking, and experiment result presentation. This chapter
covers all bar chart variants used in AI/ML.

5.1 Vertical Bar Charts


import [Link] as plt
import numpy as np

# ML Model Performance Comparison (Vertical Bar)


models = ['Logistic\nRegression', 'Decision\nTree', 'Random\nForest',
'SVM', 'XGBoost', 'Neural\nNetwork']
f1_scores = [0.78, 0.81, 0.89, 0.85, 0.91, 0.88]
bar_colors = ['#4472C4','#ED7D31','#A9D18E','#FFC000','#5B9BD5','#FF0000']

[Link](figsize=(11, 6))

bars = [Link](models, f1_scores,


color=bar_colors,
width=0.6, # Bar width (0-1)
edgecolor='white', # Border between bars
linewidth=1.2)

# Add value labels on top of each bar


for bar, val in zip(bars, f1_scores):
[Link](bar.get_x() + bar.get_width()/2, # X center of bar
bar.get_height() + 0.005, # Just above bar top
f'{val:.2f}', # Format: 2 decimal places
ha='center', va='bottom',
fontsize=11, fontweight='bold')

# Add a reference line for baseline


[Link](y=0.80, color='red', linestyle='--', alpha=0.6, label='Baseline
(0.80)')

[Link]('F1 Score Comparison Across ML Models',


fontsize=15, fontweight='bold', pad=15)
[Link]('Model', fontsize=12)
[Link]('F1 Score', fontsize=12)
[Link](0.6, 1.0) # Start at 0.6 to amplify differences
[Link](fontsize=11)
[Link](True, axis='y', alpha=0.3) # Horizontal grid only
plt.tight_layout()
[Link]()

>> Six colored bars, each for one ML model.


>> F1 score labels float above each bar in bold.
>> Red dashed baseline at 0.80 helps identify above-baseline models.
>> Y-axis starts at 0.6 (not 0) to make differences more visible.
>> Grid lines only on Y axis — cleaner than X+Y grid for bar charts.

5.2 Horizontal Bar Charts


Horizontal bars are better when you have long category names or many categories — like feature
names in feature importance plots.

Matplotlib for AI & Machine Learning Page 23


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

import [Link] as plt


import numpy as np

# Feature Importance (a classic ML horizontal bar chart)


features = ['Age', 'Education', 'Income', 'Credit Score',
'Employment Years', 'Debt Ratio', 'Previous Defaults',
'Number of Accounts', 'Loan Amount', 'Interest Rate']
importance = [0.05, 0.07, 0.12, 0.18, 0.06, 0.14, 0.22, 0.04, 0.09, 0.03]

# Sort by importance for better readability


sorted_idx = [Link](importance) # Ascending sort indices
features_s = [features[i] for i in sorted_idx]
importance_s = [importance[i] for i in sorted_idx]

# Color gradient: low importance = light blue, high = dark blue


colors = [Link]([Link](0.3, 0.9, len(features_s)))

[Link](figsize=(10, 7))
bars = [Link](features_s, importance_s, color=colors,
edgecolor='white', height=0.7)

# Add value labels


for bar, val in zip(bars, importance_s):
[Link](val + 0.003, bar.get_y() + bar.get_height()/2,
f'{val:.2f}', va='center', fontsize=10)

[Link]('Random Forest Feature Importance',


fontsize=14, fontweight='bold', pad=15)
[Link]('Feature Importance Score', fontsize=12)
[Link]('Feature', fontsize=12)
[Link](True, axis='x', alpha=0.3)
plt.tight_layout()
[Link]()

>> Horizontal bars sorted from least important (top) to most important (bottom).
>> 'Previous Defaults' has highest importance (0.22) — rightmost bar.
>> Color gradient from light to dark blue matches low-to-high importance.
>> Long feature names fit perfectly in horizontal layout.

✅ TIP
In ML, feature importance plots are almost always horizontal bar charts because feature names are
long. Sort features by importance (ascending) so the most important is at the bottom and
immediately visible.

5.3 Grouped Bar Charts


Grouped bars compare multiple metrics across the same set of categories — for example, comparing
Precision, Recall, and F1 for each class in a multi-class classification problem.

import [Link] as plt


import numpy as np

# Multi-class classification metrics


classes = ['Class 0\n(Benign)', 'Class 1\n(Malware)', 'Class 2\n(Phishing)']
precision = [0.91, 0.85, 0.88]
recall = [0.88, 0.92, 0.84]

Matplotlib for AI & Machine Learning Page 24


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

f1_score = [0.895, 0.884, 0.860]

x = [Link](len(classes)) # [0, 1, 2]
width = 0.25 # Width of each bar

[Link](figsize=(11, 6))

# Offset each group by width


bars1 = [Link](x - width, precision, width, label='Precision',
color='#4472C4', edgecolor='white')
bars2 = [Link](x, recall, width, label='Recall',
color='#ED7D31', edgecolor='white')
bars3 = [Link](x + width, f1_score, width, label='F1 Score',
color='#A9D18E', edgecolor='white')

# Add value labels


for bars in [bars1, bars2, bars3]:
for bar in bars:
[Link](bar.get_x() + bar.get_width()/2, bar.get_height() + 0.005,
f'{bar.get_height():.2f}', ha='center', va='bottom', fontsize=9)

[Link]('Classification Report Visualization',


fontsize=14, fontweight='bold')
[Link]('Class', fontsize=12)
[Link]('Score', fontsize=12)
[Link](x, classes, fontsize=11)
[Link](0.75, 1.0)
[Link](fontsize=11)
[Link](True, axis='y', alpha=0.3)
plt.tight_layout()
[Link]()

>> Three groups of bars (one per class), each with 3 bars (Precision, Recall,
F1).
>> Class 1 has highest Recall (0.92) — critical for malware detection.
>> This chart directly visualizes sklearn's classification_report output.

5.4 Stacked Bar Charts


Stacked bars show the composition of a total — for example, how a dataset is split across training,
validation, and test sets per class.

import [Link] as plt


import numpy as np

# Dataset split visualization


classes = ['Cats', 'Dogs', 'Birds', 'Fish', 'Horses']
train = [800, 950, 600, 400, 350]
val = [100, 120, 75, 50, 45]
test = [100, 130, 75, 50, 45]

x = [Link](len(classes))

[Link](figsize=(11, 6))

# Stack: each bar starts where the previous ended


p1 = [Link](x, train, color='#4472C4', label='Train',
edgecolor='white', width=0.6)
p2 = [Link](x, val, bottom=train, color='#ED7D31',
label='Validation',

Matplotlib for AI & Machine Learning Page 25


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

edgecolor='white', width=0.6)
p3 = [Link](x, test, bottom=[a+b for a,b in zip(train,val)], color='#A9D18E',
label='Test', edgecolor='white', width=0.6)

# Total labels
totals = [a+b+c for a,b,c in zip(train,val,test)]
for i, total in enumerate(totals):
[Link](i, total+10, str(total), ha='center', fontsize=10,
fontweight='bold')

[Link]('Dataset Split by Class', fontsize=14, fontweight='bold')


[Link]('Animal Class', fontsize=12)
[Link]('Number of Images', fontsize=12)
[Link](x, classes)
[Link](fontsize=11)
[Link](True, axis='y', alpha=0.3)
plt.tight_layout()
[Link]()

>> Each bar shows the total samples per class, split into train/val/test.
>> Blue (train) forms the bulk of each bar.
>> Dogs class has most data (1200 total); Horses has least (440 total).
>> Immediately reveals class imbalance and split ratios.

Figure 5.1 – Vertical bar chart: F1 score comparison across ML models

Matplotlib for AI & Machine Learning Page 26


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 5.2 – Horizontal bar chart: model accuracy ranked

Figure 5.3 – Grouped bar chart: Train vs Validation accuracy by model

Matplotlib for AI & Machine Learning Page 27


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 5.4 – Stacked bar chart: True Positive, False Positive, False Negative proportions

Chapter 5 Summary
Chapter 5 Key Takeaways
• Vertical bars: [Link](x, y) — best for comparing model scores
• Horizontal bars: [Link](y, x) — best for feature importance with long names
• Grouped: offset x by width (x-width, x, x+width) for each metric group
• Stacked: use bottom= parameter to stack multiple bars
• Always add value labels on bars for precise reading in ML reports

Matplotlib for AI & Machine Learning Page 28


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 6: Histograms
Histograms reveal the distribution of a dataset. Before training any ML model, examining feature
distributions helps identify skewness, outliers, normality, and whether preprocessing (like normalization
or log-transformation) is needed.

6.1 Basic Histogram — [Link]()


import [Link] as plt
import numpy as np

# Simulate an age feature from a loan dataset


[Link](42)
ages = [Link]([
[Link](35, 8, 800), # Majority: working age
[Link](60, 5, 200), # Minority: older applicants
])
ages = [Link](ages, 18, 80) # Valid age range

[Link](figsize=(10, 6))

# Basic histogram
n, bins, patches = [Link](ages,
bins=30, # Number of bins
color='steelblue',
edgecolor='white',
alpha=0.8,
density=False) # density=True for probability

# Mean and median lines


[Link]([Link](ages), color='red', linestyle='--', lw=2, label=f'Mean =
{[Link](ages):.1f}')
[Link]([Link](ages), color='orange', linestyle='-', lw=2, label=f'Median
= {[Link](ages):.1f}')

[Link]('Distribution of Applicant Ages in Loan Dataset',


fontsize=14, fontweight='bold')
[Link]('Age (years)', fontsize=12)
[Link]('Frequency (Count)', fontsize=12)
[Link](fontsize=11)
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

>> A bimodal distribution with a large peak at ~35 and a smaller peak at ~60.
>> Red dashed line shows mean (~40), orange solid line shows median (~38).
>> Mean > Median suggests right skew — the older group pulls the mean up.
>> This analysis would guide us to apply age binning or log transformation.

6.2 Understanding the bins Parameter


The bins parameter is the most important parameter in histograms. Too few bins hides structure; too
many bins shows noise. There are several strategies to choose the right bin count.

import [Link] as plt


import numpy as np

Matplotlib for AI & Machine Learning Page 29


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

[Link](42)
data = [Link](50, 15, 500) # Normal distribution, mean=50, std=15

fig, axes = [Link](1, 4, figsize=(16, 4))

bin_settings = [5, 20, 50, 'auto'] # auto uses Sturges/FD rule


titles = ['bins=5\n(Too Few)', 'bins=20\n(Good)', 'bins=50\n(Too Many)',
"bins='auto'\n(Automatic)"]

for ax, bins, title in zip(axes, bin_settings, titles):


[Link](data, bins=bins, color='steelblue', edgecolor='white', alpha=0.8)
ax.set_title(title, fontsize=11)
ax.set_xlabel('Value')
ax.set_ylabel('Count')
[Link](True, alpha=0.3)

[Link]('Effect of bins Parameter on Histogram', fontsize=13,


fontweight='bold', y=1.02)
plt.tight_layout()
[Link]()

>> bins=5: Five wide bars — the bell shape is barely visible.
>> bins=20: Clear bell curve shape — this is usually the sweet spot.
>> bins=50: Very spiky — noise looks like structure.
>> bins='auto': Matplotlib chooses optimally (often similar to bins=20-30).

Bins Parameter Options


bins Value Description When to Use

Integer (e.g., 30) Exact number of equal-width bins When you know your data
range

'auto' Uses best of Sturges and Freedman- General purpose, safe


Diaconis default

'sturges' Log2(n)+1 bins — simple rule Small datasets (n < 200)

'fd' Freedman-Diaconis — uses IQR Larger datasets, robust to


outliers

'scott' Scott's rule — uses std deviation Normally distributed data

Array Custom bin edges: [0,10,20,50,100] Non-uniform bins, domain


knowledge
Table 6.1 – Histogram bins Parameter Options

6.3 Histograms for ML Dataset Analysis


One of the most important uses of histograms in ML is the Exploratory Data Analysis (EDA) phase —
checking distributions of all features before training.

import [Link] as plt


import numpy as np

# Simulate dataset features (like from Pandas DataFrame)

Matplotlib for AI & Machine Learning Page 30


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

[Link](0)
n = 1000

features = {
'Age': [Link](40, 12, n),
'Income (K)': [Link](50, n), # Right-skewed
'Credit Score': [Link](680, 60, n),
'Loan Amount': [Link](10, 0.5, n), # Log-normal
}

fig, axes = [Link](2, 2, figsize=(14, 9))


axes = [Link]() # Easier to iterate

colors = ['#4472C4', '#ED7D31', '#A9D18E', '#FFC000']

for idx, (feature_name, data) in enumerate([Link]()):


ax = axes[idx]
[Link](data, bins='auto', color=colors[idx], edgecolor='white', alpha=0.8)
[Link]([Link](data), color='red', lw=2, ls='--',
label=f'Mean={[Link](data):.1f}')
[Link]([Link](data), color='black', lw=2, ls=':',
label=f'Median={[Link](data):.1f}')
ax.set_title(f'{feature_name} Distribution', fontsize=12, fontweight='bold')
ax.set_xlabel(feature_name)
ax.set_ylabel('Frequency')
[Link](fontsize=9)
[Link](True, alpha=0.3)

[Link]('EDA: Feature Distributions in Loan Dataset',


fontsize=14, fontweight='bold', y=1.01)
plt.tight_layout()
[Link]()

>> 2x2 grid showing all four feature distributions.


>> Age: Normal bell curve — no transformation needed.
>> Income: Heavily right-skewed — log transformation recommended before training.
>> Credit Score: Normal distribution — use as-is or standardize.
>> Loan Amount: Log-normal — log transformation needed.
>> Mean vs Median gap on Income/Loan reveals the skewness clearly.

💡 IMPORTANT
In ML preprocessing, always plot histograms BEFORE and AFTER normalization/standardization to
verify the transformation worked correctly. If mean ≈ median and distribution looks symmetric,
StandardScaler likely worked well.

6.4 Comparing Two Distributions


import [Link] as plt
import numpy as np

[Link](42)
# Fraud detection: transaction amounts for fraud vs legitimate
legitimate = [Link](scale=200, size=2000)
fraudulent = [Link](scale=800, size=200)

[Link](figsize=(11, 6))

# Overlay two histograms with alpha (transparency)


[Link](legitimate, bins=50, alpha=0.6, color='steelblue',
label=f'Legitimate (n={len(legitimate):,})', density=True)

Matplotlib for AI & Machine Learning Page 31


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

[Link](fraudulent, bins=50, alpha=0.6, color='tomato',


label=f'Fraudulent (n={len(fraudulent):,})', density=True)

[Link]('Transaction Amount: Fraud vs Legitimate',


fontsize=14, fontweight='bold')
[Link]('Transaction Amount ($)', fontsize=12)
[Link]('Probability Density', fontsize=12)
[Link](fontsize=11)
[Link]('log') # Log scale — common for financial data
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

>> Two overlapping histograms with 60% transparency.


>> Legitimate transactions (blue): heavily concentrated at low amounts.
>> Fraudulent transactions (red): spread to much higher amounts.
>> density=True normalizes both so they're directly comparable despite different
n.
>> This visualization directly motivates amount as a fraud-predictive feature.

Figure 6.1 – Basic histogram: model prediction score distribution

Figure 6.2 – Effect of bin count on histogram shape (5 / 20 / 50 / 100 bins)

Matplotlib for AI & Machine Learning Page 32


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 6.3 – EDA dashboard: 6-panel feature distribution analysis

Figure 6.4 – Histogram comparison across model types

Chapter 6 Summary
Chapter 6 Key Takeaways
• [Link](data, bins=30) — basic histogram; bins='auto' is a safe default
• Add mean/median lines with [Link]() to spot skewness

Matplotlib for AI & Machine Learning Page 33


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

• Use density=True when comparing distributions of different sizes


• alpha=0.6 for overlapping histograms — keeps both visible
• EDA use case: identify skewness → decide if log transform is needed

Matplotlib for AI & Machine Learning Page 34


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 7: Scatter Plots


Scatter plots visualize the relationship between two continuous variables. In ML, scatter plots are used
for correlation analysis, cluster visualization, dimensionality reduction output (PCA, t-SNE, UMAP), and
anomaly detection.

7.1 Basic Scatter Plot


import [Link] as plt
import numpy as np

[Link](42)

# Simulate house price dataset


sq_footage = [Link](1800, 400, 200) # Square footage
price = sq_footage * 250 + [Link](0, 50000, 200) # Price

[Link](figsize=(10, 6))
[Link](sq_footage, price,
color='steelblue',
alpha=0.6, # Transparency to see overlap
s=50, # Marker size (area in points^2)
edgecolors='white', linewidths=0.5)

# Add trend line (linear regression line)


z = [Link](sq_footage, price, 1) # Degree 1 = linear
p = np.poly1d(z)
x_line = [Link](sq_footage.min(), sq_footage.max(), 100)
[Link](x_line, p(x_line), color='red', linewidth=2, label='Trend Line')

# Pearson correlation
corr = [Link](sq_footage, price)[0, 1]
[Link](0.05, 0.95, f'r = {corr:.3f}', transform=[Link]().transAxes,
fontsize=12, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))

[Link]('House Price vs Square Footage', fontsize=14, fontweight='bold')


[Link]('Square Footage (sq ft)', fontsize=12)
[Link]('House Price ($)', fontsize=12)
[Link](fontsize=11)
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

>> 200 scattered blue dots showing a clear positive correlation.


>> Red trend line confirms the linear relationship.
>> Correlation coefficient r ≈ 0.97 displayed in upper-left box.
>> alpha=0.6 makes overlapping points visible (density visible through
transparency).

7.2 Scatter Plots in ML — Visualizing Clusters


One of the most important ML uses of scatter plots is visualizing clusters after dimensionality reduction
(PCA or t-SNE).

import [Link] as plt

Matplotlib for AI & Machine Learning Page 35


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

import numpy as np

[Link](42)

# Simulate PCA output of Iris dataset (3 classes)


# In real ML: from [Link] import PCA; X_pca =
PCA(2).fit_transform(X)
c0 = [Link].multivariate_normal([2, 3], [[0.5,0.1],[0.1,0.5]], 50)
c1 = [Link].multivariate_normal([-1, -2], [[0.6,0.2],[0.2,0.4]], 50)
c2 = [Link].multivariate_normal([4, -1], [[0.3,0.0],[0.0,0.6]], 50)

classes = ['Setosa', 'Versicolor', 'Virginica']


data = [c0, c1, c2]
colors = ['#4472C4', '#ED7D31', '#A9D18E']
markers = ['o', 's', '^']

[Link](figsize=(10, 7))
for i, (cluster, name, col, mk) in enumerate(zip(data, classes, colors,
markers)):
[Link](cluster[:, 0], cluster[:, 1],
c=col, label=name, s=80, marker=mk,
edgecolors='white', linewidths=0.8, alpha=0.85)

[Link]('PCA of Iris Dataset — 2D Projection',


fontsize=14, fontweight='bold')
[Link]('Principal Component 1 (PC1)', fontsize=12)
[Link]('Principal Component 2 (PC2)', fontsize=12)
[Link](title='Species', fontsize=11, title_fontsize=11)
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

>> Three distinct clusters with different colors and markers.


>> Setosa (blue circles) clearly separated from the other two.
>> Versicolor (orange squares) and Virginica (green triangles) closer together.
>> This is the standard way to visualize dimensionality reduction results in ML
papers.

7.3 Color Mapping Scatter Plots


Color mapping (using a colormap) lets you encode a third variable as color, effectively creating a 3D
visualization in 2D.

import [Link] as plt


import numpy as np

[Link](42)
n = 300

# Regression prediction visualization


x_feature = [Link](0, 10, n)
y_feature = [Link](0, 10, n)
predicted = 2*x_feature + 1.5*y_feature + [Link](0, 2, n)

[Link](figsize=(9, 7))
scatter = [Link](x_feature, y_feature,
c=predicted, # Color = predicted value
cmap='RdYlGn', # Red-Yellow-Green colormap
s=60, alpha=0.8,
edgecolors='gray', linewidths=0.3)

Matplotlib for AI & Machine Learning Page 36


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

# Add colorbar to explain the color scale


cbar = [Link](scatter)
cbar.set_label('Predicted Value', fontsize=11)

[Link]('Scatter Plot with Color-Mapped Predictions',


fontsize=14, fontweight='bold')
[Link]('Feature 1', fontsize=12)
[Link]('Feature 2', fontsize=12)
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

>> Points colored from red (low prediction) to green (high prediction).
>> A colorbar on the right maps colors to predicted values.
>> Visual shows how predictions increase diagonally — matching the linear
formula.
>> This technique is used to visualize regression model outputs across 2D feature
space.

7.4 Bubble Charts


Bubble charts are extended scatter plots where the size of each point encodes a third variable. Use
them to show three dimensions simultaneously.

import [Link] as plt


import numpy as np

# ML model comparison: Accuracy vs Training Time vs Model Size


models = ['Linear SVM', 'RBF SVM', 'Decision Tree',
'Random Forest', 'XGBoost', 'Neural Net']
accuracy = [0.83, 0.91, 0.82, 0.92, 0.94, 0.93]
train_time = [2, 15, 1, 8, 12, 45] # Seconds
model_size = [0.1, 0.5, 0.3, 8.0, 6.0, 25.0] # MB

colors = ['#4472C4','#ED7D31','#A9D18E','#FFC000','#5B9BD5','#E05050']

[Link](figsize=(11, 7))

for i in range(len(models)):
[Link](train_time[i], accuracy[i],
s=model_size[i] * 100, # Bubble size proportional to MB
c=colors[i], alpha=0.7,
edgecolors='white', linewidths=1.5)
[Link](models[i],
xy=(train_time[i], accuracy[i]),
xytext=(5, 5), textcoords='offset points',
fontsize=9)

[Link]('Model Comparison: Accuracy vs Training Time vs Model Size',


fontsize=13, fontweight='bold')
[Link]('Training Time (seconds)', fontsize=12)
[Link]('Accuracy', fontsize=12)
[Link](0.02, 0.02, 'Bubble size = Model size in MB',
transform=[Link]().transAxes, fontsize=10, style='italic',
bbox=dict(boxstyle='round', alpha=0.5, facecolor='lightyellow'))
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

Matplotlib for AI & Machine Learning Page 37


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

>> Each bubble is a model: x=training time, y=accuracy, size=model file size.
>> Neural Net: slow (45s) but high accuracy (0.93), very large (25MB) bubble.
>> Decision Tree: fast (1s), moderate accuracy (0.82), tiny bubble.
>> XGBoost: balance of speed, accuracy, size — visible as medium bubble.
>> Ideal model for deployment: upper-left area with small bubble.

Figure 7.1 – Basic scatter plot: feature relationship visualization

Figure 7.2 – PCA scatter plot: 2D projection with class labels

Matplotlib for AI & Machine Learning Page 38


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 7.3 – Colormap scatter plot: third variable encoded in color

Figure 7.4 – Bubble chart: size encodes a fourth dimension

Matplotlib for AI & Machine Learning Page 39


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 7 Summary
Chapter 7 Key Takeaways
• [Link](x, y, c=, s=, alpha=) — 2D relationship visualization
• Add trend line: [Link] + np.poly1d + [Link]()
• Color mapping: c=values, cmap='RdYlGn' + [Link]() for 3rd dimension
• Bubble chart: s=size_array — encode 3rd variable as bubble size
• Key ML uses: PCA/t-SNE cluster visualization, correlation analysis, model comparison

Matplotlib for AI & Machine Learning Page 40


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 8: Pie Charts


Pie charts show proportions and percentages of a whole. In ML, they're used to visualize class
distribution, dataset composition, and categorical feature breakdowns. Use pie charts when you have 5
or fewer categories; more categories are better visualized with bar charts.

8.1 Basic Pie Chart


import [Link] as plt

# Class distribution in a sentiment analysis dataset


labels = ['Positive', 'Negative', 'Neutral']
sizes = [1450, 890, 660] # Sample counts
colors = ['#A9D18E', '#FF6B6B', '#FFC000']

[Link](figsize=(9, 7))
patches, texts, autotexts = [Link](
sizes,
labels=labels,
colors=colors,
autopct='%1.1f%%', # Show percentage with 1 decimal
startangle=90, # Start at top (12 o'clock position)
pctdistance=0.75, # Distance of % text from center
labeldistance=1.1) # Distance of label from center

# Style the percentage text


for autotext in autotexts:
autotext.set_fontsize(12)
autotext.set_fontweight('bold')

[Link]('Sentiment Class Distribution',


fontsize=14, fontweight='bold', pad=20)
plt.tight_layout()
[Link]()

>> Three slices showing Positive ~47.5%, Negative ~29.1%, Neutral ~21.6%.
>> Percentages in bold inside each slice at 75% radius.
>> Starting at 90° (top) makes the largest slice appear at the top-right.
>> Immediately shows class imbalance — Positive class dominates.

8.2 Exploded Pie Chart


The explode parameter pulls one or more slices outward for emphasis. Use it to highlight a specific
class (like the minority class in imbalanced datasets).

import [Link] as plt


import numpy as np

# Fraud detection dataset — highlight fraud class


labels = ['Legitimate', 'Fraudulent']
sizes = [9875, 125] # Highly imbalanced!
colors = ['#4472C4', '#FF4444']
explode = (0.0, 0.15) # Pull fraud slice out by 15%

[Link](figsize=(9, 7))
patches, texts, autotexts = [Link](

Matplotlib for AI & Machine Learning Page 41


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

sizes,
labels=labels,
colors=colors,
explode=explode,
autopct='%1.2f%%',
shadow=True, # Add drop shadow for 3D effect
startangle=90)

# Custom colors
autotexts[0].set_color('white')
autotexts[0].set_fontweight('bold')
autotexts[1].set_color('white')
autotexts[1].set_fontweight('bold')

[Link]('Credit Card Fraud Dataset Distribution\n(Highly Imbalanced)',


fontsize=13, fontweight='bold')
plt.tight_layout()
[Link]()

>> Large blue slice (99.98%): Legitimate transactions — dominates the chart.
>> Small red slice (1.25%) for Fraud pulled outward by 15% — emphasizes the
minority.
>> Shadow gives a subtle 3D depth effect.
>> The extreme imbalance is immediately visible — motivates SMOTE oversampling.

8.3 Donut Chart


A donut chart is a pie chart with a hole in the center. The hole can display a summary statistic, making
it more informative.

import [Link] as plt

# Model ensemble composition


labels = ['Random Forest', 'XGBoost', 'Neural Net', 'SVM', 'Logistic Reg']
sizes = [35, 30, 20, 10, 5]
colors = ['#4472C4','#ED7D31','#A9D18E','#FFC000','#5B9BD5']

fig, ax = [Link](figsize=(10, 7))

wedges, texts, autotexts = [Link](


sizes, labels=labels, colors=colors,
autopct='%1.0f%%',
startangle=90,
pctdistance=0.8,
wedgeprops=dict(width=0.5, edgecolor='white', linewidth=2) # width < 1 =
donut
)

# Text in the center hole


[Link](0, 0, 'Model\nEnsemble', ha='center', va='center',
fontsize=14, fontweight='bold', color='#1B3A6B')

ax.set_title('Ensemble Model Composition', fontsize=14, fontweight='bold',


pad=20)
plt.tight_layout()
[Link]()

>> Ring-shaped chart with 'Model Ensemble' text in the center hole.
>> wedgeprops width=0.5 creates the donut hole (0=solid pie, 1=no slices).
>> Each wedge shows the weight of that model in the ensemble voting.

Matplotlib for AI & Machine Learning Page 42


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 8.1 – Basic pie chart: ML model performance share

Figure 8.2 – Exploded pie chart: credit card fraud dataset (highly imbalanced)

Matplotlib for AI & Machine Learning Page 43


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 8.3 – Donut chart: ensemble model composition

Chapter 8 Summary
Chapter 8 Key Takeaways
• [Link](sizes, labels=, autopct='%1.1f%%', startangle=90)
• explode=(0, 0.1) — pull out slices to emphasize minority classes
• shadow=True — adds 3D drop shadow for visual depth
• Donut: wedgeprops=dict(width=0.5) — leaves a hole in the center
• Best for ≤5 categories; class imbalance, dataset splits, ensemble weights

Matplotlib for AI & Machine Learning Page 44


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 9: Subplots
Subplots allow you to display multiple charts in one figure. In ML workflows, you'll constantly need to
compare metrics side by side, show before/after preprocessing, or create model performance
dashboards.

9.1 [Link]() — The Basic Approach


import [Link] as plt
import numpy as np

[Link](42)
epochs = [Link](1, 31)
train_loss = 0.9 * [Link](-epochs/8) + 0.05 + [Link](0, 0.01, 30)
val_loss = 0.9 * [Link](-epochs/9) + 0.08 + [Link](0, 0.015, 30)
train_acc = 1 - train_loss + 0.05
val_acc = 1 - val_loss + 0.03

[Link](figsize=(14, 5))

# [Link](nrows, ncols, index)


[Link](1, 2, 1) # 1 row, 2 columns, position 1
[Link](epochs, train_loss, 'b-', lw=2, label='Train Loss')
[Link](epochs, val_loss, 'r--', lw=2, label='Val Loss')
[Link]('Loss Curves', fontsize=13, fontweight='bold')
[Link]('Epoch'); [Link]('Loss')
[Link](); [Link](True, alpha=0.3)

[Link](1, 2, 2) # 1 row, 2 columns, position 2


[Link](epochs, train_acc, 'b-', lw=2, label='Train Acc')
[Link](epochs, val_acc, 'r--', lw=2, label='Val Acc')
[Link]('Accuracy Curves', fontsize=13, fontweight='bold')
[Link]('Epoch'); [Link]('Accuracy')
[Link](); [Link](True, alpha=0.3)

[Link]('Training Dashboard — 30 Epochs', fontsize=15, fontweight='bold',


y=1.02)
plt.tight_layout()
[Link]()

>> Side-by-side Loss and Accuracy plots for training and validation.
>> Left: Loss decreasing — training faster than validation (slight overfitting).
>> Right: Accuracy increasing — both converging toward similar final values.
>> suptitle() adds an overall title across both subplots.
>> This is the standard training dashboard layout used in Keras/PyTorch projects.

9.2 [Link]() — The Modern Approach (Recommended)


[Link]() is the modern, cleaner way to create subplots. It returns a Figure object and an array of
Axes objects, which you can access with array indexing.

import [Link] as plt


import numpy as np

[Link](42)

Matplotlib for AI & Machine Learning Page 45


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

# Create a 2x3 grid of subplots


fig, axes = [Link](2, 3, figsize=(15, 9))

# ── Row 1: Different distribution types ──


# Histogram
axes[0,0].hist([Link](0,1,1000), bins=30, color='steelblue',
edgecolor='white')
axes[0,0].set_title('Normal Distribution', fontsize=11)

# Skewed distribution
axes[0,1].hist([Link](2, 1000), bins=30, color='tomato',
edgecolor='white')
axes[0,1].set_title('Exponential Distribution', fontsize=11)

# Bimodal
bimodal = [Link]([[Link](-2,0.5,500),
[Link](2,0.5,500)])
axes[0,2].hist(bimodal, bins=40, color='purple', edgecolor='white')
axes[0,2].set_title('Bimodal Distribution', fontsize=11)

# ── Row 2: Different plot types ──


x = [Link](0, 10, 100)
axes[1,0].plot(x, [Link](x), 'b-', lw=2)
axes[1,0].set_title('Line Chart', fontsize=11)

x2, y2 = [Link](50), [Link](50)


axes[1,1].scatter(x2, y2, c=[Link](50), cmap='viridis', s=60, alpha=0.7)
axes[1,1].set_title('Scatter Plot', fontsize=11)

cats = ['A','B','C','D','E']
axes[1,2].bar(cats, [Link](10,100,5),
color=['#4472C4','#ED7D31','#A9D18E','#FFC000','#FF6B6B'])
axes[1,2].set_title('Bar Chart', fontsize=11)

# Apply grid and labels to all subplots


for row in axes:
for ax in row:
[Link](True, alpha=0.3)

[Link]('Data Distribution & Chart Type Reference', fontsize=15,


fontweight='bold')
plt.tight_layout()
[Link]()

>> 2x3 grid: top row shows three distribution types, bottom row shows three chart
types.
>> Access each subplot by index: axes[0,0], axes[0,1], axes[1,2], etc.
>> The for loop applies grid to all 6 subplots at once — efficient!
>> tight_layout() prevents subplots from overlapping.

9.3 Shared Axes — Aligned Comparison


import [Link] as plt
import numpy as np

[Link](42)
time = [Link](0, 100)
price = 100 + [Link]([Link](100)) * 2
volume = [Link](1000, 100)

# sharex=True — both plots share the same X axis (synchronized)


fig, (ax1, ax2) = [Link](2, 1, figsize=(13, 8),

Matplotlib for AI & Machine Learning Page 46


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

sharex=True,
gridspec_kw={'height_ratios': [3, 1]})

# Top: Price chart


[Link](time, price, color='steelblue', lw=2)
ax1.fill_between(time, price, [Link](), alpha=0.1, color='steelblue')
ax1.set_ylabel('Stock Price ($)', fontsize=12)
ax1.set_title('Stock Price & Volume (Finance AI)', fontsize=14,
fontweight='bold')
[Link](True, alpha=0.3)

# Bottom: Volume bars


[Link](time, volume, color='orange', alpha=0.7, width=1.0)
ax2.set_ylabel('Volume', fontsize=12)
ax2.set_xlabel('Time (days)', fontsize=12)
[Link](True, alpha=0.3)

plt.tight_layout()
[Link]()

>> Two stacked plots sharing the same X axis — panning/zooming one pans both.
>> Top plot (3x height): price line with light blue fill area below.
>> Bottom plot (1x height): orange volume bars.
>> gridspec_kw={'height_ratios':[3,1]} makes top 3x taller than bottom.
>> This layout is standard in financial ML (algorithmic trading) dashboards.

9.4 GridSpec — Advanced Layout Control


GridSpec gives you pixel-perfect control over subplot layout — including different-sized subplots in
irregular arrangements.

import [Link] as plt


import [Link] as gridspec
import numpy as np

[Link](42)

fig = [Link](figsize=(14, 9))


gs = [Link](2, 3, figure=fig, hspace=0.4, wspace=0.35)

# Large plot spanning 2 columns


ax_main = fig.add_subplot(gs[0, :2]) # Row 0, columns 0-1
x = [Link](0, 4*[Link], 200)
ax_main.plot(x, [Link](x), 'b-', lw=2, label='sin(x)')
ax_main.plot(x, [Link](x), 'r--', lw=2, label='cos(x)')
ax_main.set_title('Main: Trig Functions (Spans 2 Columns)', fontsize=12,
fontweight='bold')
ax_main.legend(); ax_main.grid(True, alpha=0.3)

# Right column: narrow histogram spanning full height of row 0


ax_hist = fig.add_subplot(gs[0, 2])
ax_hist.hist([Link](0,1,500), bins=25, color='green',
orientation='horizontal')
ax_hist.set_title('Distribution', fontsize=11)
ax_hist.grid(True, alpha=0.3)

# Bottom row: 3 equal charts


for col in range(3):
ax = fig.add_subplot(gs[1, col])
data = [Link](100) * (col+1)

Matplotlib for AI & Machine Learning Page 47


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

[Link](data, bins=20, color=[Link].Set1(col/3), edgecolor='white')


ax.set_title(f'Feature {col+1}', fontsize=11)
[Link](True, alpha=0.3)

[Link]('Advanced GridSpec Layout — ML Dashboard', fontsize=14,


fontweight='bold')
[Link]()

>> Top-left: large main chart spanning 2 columns — the focal visualization.
>> Top-right: compact histogram using the remaining column.
>> Bottom row: three equal feature distribution histograms.
>> This asymmetric layout creates a professional ML report dashboard.

Figure 9.1 – Training dashboard: loss and accuracy curves side-by-side

Figure 9.2 – 2x3 subplot grid: distributions and chart types reference

Matplotlib for AI & Machine Learning Page 48


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 9.3 – Shared-axis stock price and volume chart (finance AI)

Figure 9.4 – GridSpec advanced layout: ML dashboard with spanning panels

Matplotlib for AI & Machine Learning Page 49


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 9 Summary
Chapter 9 Key Takeaways
• [Link](rows, cols, index) — simple subplot creation (1-indexed)
• fig, axes = [Link](r, c) — modern approach; axes[row,col] indexing
• sharex=True / sharey=True — sync axes between subplots
• gridspec_kw={'height_ratios':[3,1]} — unequal subplot sizes
• GridSpec — complex asymmetric layouts; spans columns with gs[0, :2]

Matplotlib for AI & Machine Learning Page 50


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Chapter 10: Customization Techniques


Customization is what separates a rough exploratory plot from a publication-quality visualization. This
chapter covers colors, themes, axis customization, annotations, and text placement — skills that make
your ML reports stand out.

10.1 Working with Colors


Matplotlib provides multiple color systems. For professional ML visualizations, hex codes and named
colormaps give you the most control.

import [Link] as plt


import numpy as np

# Professional color palette for ML visualizations


# These colors work well together and are colorblind-friendly
PALETTE = {
'primary': '#2E75B6', # Professional blue
'secondary': '#E87722', # Warm orange
'success': '#217346', # Forest green
'danger': '#C00000', # Deep red
'warning': '#FFB900', # Amber
'neutral': '#595959', # Dark gray
}

fig, axes = [Link](1, 3, figsize=(15, 5))

# Plot 1: Using hex palette


categories = ['Model A', 'Model B', 'Model C', 'Model D']
scores = [0.87, 0.91, 0.84, 0.93]
bar_colors = [PALETTE['primary'], PALETTE['secondary'],
PALETTE['success'], PALETTE['danger']]
axes[0].bar(categories, scores, color=bar_colors, edgecolor='white', lw=1.5)
axes[0].set_title('Hex Color Palette', fontsize=12, fontweight='bold')
axes[0].set_ylim(0.75, 1.0); axes[0].grid(True, axis='y', alpha=0.3)

# Plot 2: Matplotlib named colormaps


x = [Link](0, 10, 100)
cmaps = ['viridis','plasma','inferno','magma']
for i, cmap_name in enumerate(cmaps):
y = [Link](x + i*0.5)
color = [Link].get_cmap(cmap_name)(0.7) # Get a specific color from colormap
axes[1].plot(x, y + i*0.5, color=color, lw=2, label=cmap_name)
axes[1].set_title('Colors from Colormaps', fontsize=12, fontweight='bold')
axes[1].legend(fontsize=9); axes[1].grid(True, alpha=0.3)

# Plot 3: Color with transparency (alpha)


[Link](42)
for i, (alpha, color) in enumerate(zip([1.0, 0.7, 0.4, 0.2],
['blue','red','green','purple'])):
data = [Link](i, 0.8, 300)
axes[2].hist(data, bins=20, color=color, alpha=alpha, label=f'alpha={alpha}')
axes[2].set_title('Alpha (Transparency)', fontsize=12, fontweight='bold')
axes[2].legend(fontsize=9); axes[2].grid(True, alpha=0.3)

[Link]('Color Control in Matplotlib', fontsize=14, fontweight='bold')


plt.tight_layout()
[Link]()

Matplotlib for AI & Machine Learning Page 51


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Useful Matplotlib Colormaps for ML


Colormap Category Best For

viridis Sequential Heatmaps, continuous data — perceptually


uniform

plasma / inferno Sequential Alternative to viridis — warm tones

RdYlGn Diverging Good/bad metrics (green=good, red=bad)

coolwarm / bwr Diverging Correlation matrices — diverging from 0

Blues / Reds Sequential single-hue Confusion matrix intensity

tab10 / Set1 Qualitative Categorical class labels (up to 10 classes)

jet Rainbow (avoid!) Legacy; avoid — misleading in data viz

Greys Sequential Grayscale outputs, print-friendly charts


Table 10.1 – Recommended Matplotlib Colormaps for ML

10.2 Themes and Styles


Using a consistent style across all plots in your notebook or report instantly elevates professionalism.

import [Link] as plt


import numpy as np

# Create same plot in 4 different styles


x = [Link](0, 10, 100)
styles = ['default', 'seaborn-v0_8-darkgrid', 'ggplot', 'dark_background']
titles = ['Default', 'Seaborn Dark Grid', 'ggplot', 'Dark Background']

fig, axes = [Link](2, 2, figsize=(14, 9))


axes = [Link]()

for ax, style, title in zip(axes, styles, titles):


with [Link](style): # Apply style only inside this block
[Link](x, [Link](x), lw=2, label='sin(x)')
[Link](x, [Link](x), lw=2, label='cos(x)')
ax.set_title(f'Style: {title}', fontsize=12, fontweight='bold')
[Link](fontsize=10)
ax.set_xlabel('X')
ax.set_ylabel('Y')

[Link]('Matplotlib Style Comparison', fontsize=14, fontweight='bold')


plt.tight_layout()
[Link]()

>> Top-left: Default style — white background, blue/orange default colors.


>> Top-right: Seaborn darkgrid — gray background with white gridlines.
>> Bottom-left: ggplot — R-style gray background with prominent gridlines.
>> Bottom-right: Dark background — black background, bright vibrant lines.
>> Use context manager (with [Link](...)) to apply style locally.

Matplotlib for AI & Machine Learning Page 52


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

10.3 Axis Customization


import [Link] as plt
import numpy as np

fig, axes = [Link](1, 2, figsize=(14, 6))

x = [Link](0.01, 100, 500)


y = [Link](x) * 10

# Left: Default linear axes


axes[0].plot(x, y, 'steelblue', lw=2)
axes[0].set_title('Linear Scale', fontsize=12, fontweight='bold')
axes[0].set_xlabel('X (Linear)'); axes[0].set_ylabel('Y')
axes[0].grid(True, alpha=0.3)

# Right: Fully customized axes


axes[1].plot(x, y, 'steelblue', lw=2)
axes[1].set_title('Fully Customized Axes', fontsize=12, fontweight='bold')

# Custom tick marks


axes[1].set_xticks([0, 20, 40, 60, 80, 100])
axes[1].set_xticklabels(['0', '20', '40', '60', '80', '100ms'])

axes[1].set_yticks([Link](0, 50, 10))


axes[1].tick_params(axis='x', rotation=30, labelsize=10, color='blue')
axes[1].tick_params(axis='y', labelsize=10, colors='darkgreen')

# Axis limits
axes[1].set_xlim(0, 110)
axes[1].set_ylim(-5, 48)

# Add a secondary Y axis (twin axes)


ax2 = axes[1].twinx()
[Link](x, y/10, 'tomato', lw=1.5, linestyle='--', alpha=0.7, label='Scaled')
ax2.set_ylabel('Scaled Y (÷10)', color='tomato', fontsize=11)
ax2.tick_params(axis='y', labelcolor='tomato')

axes[1].set_xlabel('Time (ms)')
axes[1].set_ylabel('Signal Strength (dB)', color='steelblue')
axes[1].grid(True, alpha=0.3)

plt.tight_layout()
[Link]()

>> Left: plain default axes with auto-determined ticks.


>> Right: custom tick labels (with 'ms' unit on x), colored tick marks,
>> explicit axis limits, and a secondary Y axis in red on the right.
>> Twin Y axes are common in finance/signal processing ML applications.

10.4 Annotations
Annotations add context directly on plots — pointing to key events, maximum values, or decision
boundaries. Essential for making ML plots self-explanatory.

import [Link] as plt


import numpy as np

[Link](42)
epochs = [Link](1, 51)

Matplotlib for AI & Machine Learning Page 53


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

val_acc = 0.5 + 0.45*(1 - [Link](-epochs/10)) + [Link](0, 0.008, 50)


val_acc[30] += 0.04 # Simulate a jump due to LR decay
best_epoch = [Link](val_acc) + 1
best_acc = val_acc[best_epoch - 1]

[Link](figsize=(12, 6))
[Link](epochs, val_acc, 'steelblue', lw=2, label='Validation Accuracy')

# ── Annotation 1: Arrow pointing to best epoch ──


[Link](
f'Best Accuracy\n{best_acc:.4f} @ Epoch {best_epoch}',
xy=(best_epoch, best_acc), # Where the arrow points
xytext=(best_epoch+7, best_acc-0.06), # Where the text box sits
fontsize=11, fontweight='bold',
color='darkgreen',
arrowprops=dict(
arrowstyle='->', color='darkgreen', lw=2
),
bbox=dict(boxstyle='round,pad=0.4', facecolor='lightgreen', alpha=0.8)
)

# ── Annotation 2: Vertical line at LR decay ──


[Link](x=31, color='orange', ls='--', lw=1.5, alpha=0.8)
[Link](32, 0.56, 'LR Decay\nApplied', color='darkorange',
fontsize=10, fontweight='bold',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))

# ── Annotation 3: Horizontal line at target accuracy ──


[Link](y=0.90, color='red', ls=':', lw=1.5, alpha=0.7, label='Target: 90%')

# ── Annotation 4: Fill between (confidence region) ──


plt.fill_between(epochs, val_acc - 0.015, val_acc + 0.015,
alpha=0.15, color='steelblue', label='±1 Std Dev')

[Link]('Validation Accuracy with Annotations', fontsize=14, fontweight='bold')


[Link]('Epoch'); [Link]('Validation Accuracy')
[Link](fontsize=11, loc='lower right')
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

>> Accuracy curve with four types of annotations:


>> 1. Green arrow pointing to the peak accuracy with boxed label
>> 2. Orange dashed vertical line marking when LR decay was applied
>> 3. Red dotted horizontal line marking the 90% target threshold
>> 4. Light blue shaded band showing ±1 standard deviation confidence interval
>> This is a complete, self-documenting ML training visualization.

Annotation Parameters Quick Reference


Parameter Description Example

xy Arrow tip location (data coordinates) (epoch, accuracy)

xytext Text box position (epoch+5, accuracy-0.05)

arrowprops Arrow style dictionary dict(arrowstyle='->', color='red',


lw=2)

bbox Text box background dict(boxstyle='round',


facecolor='yellow')

fontsize Text size 10, 11, 12

Matplotlib for AI & Machine Learning Page 54


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

color Text color 'darkgreen', '#2E75B6'

ha / va Horizontal/vertical alignment 'center', 'left', 'top'


Table 10.2 – [Link]() Key Parameters

10.5 Text Placement and LaTeX


import [Link] as plt
import numpy as np

x = [Link](-5, 5, 200)
y = 1 / (1 + [Link](-x)) # Sigmoid function

[Link](figsize=(10, 6))
[Link](x, y, color='steelblue', lw=3, label='Sigmoid')
[Link](0.5, color='gray', ls='--', alpha=0.5)
[Link](0, color='gray', ls='--', alpha=0.5)

# LaTeX math formula in title


[Link](r'Sigmoid Activation: $\sigma(x) = \frac{1}{1+e^{-x}}$',
fontsize=15, fontweight='bold')

# LaTeX in annotation
[Link](r'$\sigma(0) = 0.5$', xy=(0, 0.5), xytext=(1.5, 0.35),
fontsize=12, color='red',
arrowprops=dict(arrowstyle='->', color='red', lw=1.5))

# [Link]() for simple text placement (no arrow)


[Link](-4.5, 0.9, r'Saturates at $y \to 1$',
fontsize=11, style='italic', color='darkgreen')
[Link](-4.5, 0.1, r'Saturates at $y \to 0$',
fontsize=11, style='italic', color='darkred')

[Link](0.55, 0.05, 'transform=axes means\nfractional coordinates',


transform=[Link]().transAxes, # 0-1 coordinates instead of data
fontsize=9, color='gray')

[Link]('x (input)', fontsize=12)


[Link](r'$\sigma(x)$ (output)', fontsize=12)
[Link](True, alpha=0.3)
[Link](fontsize=11)
plt.tight_layout()
[Link]()

>> The title shows the rendered LaTeX sigmoid formula with fraction.
>> Red arrow points to the midpoint (0, 0.5) with LaTeX annotation.
>> Italic notes explain saturation at the top and bottom.
>> transAxes coordinates (0.55, 0.05) place text relative to axes size,
>> not data — stays in same corner regardless of zoom.

10.6 Spines and Frame Customization


import [Link] as plt
import numpy as np

fig, (ax1, ax2) = [Link](1, 2, figsize=(13, 5))

x = [Link](0, 10, 100)

Matplotlib for AI & Machine Learning Page 55


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

y = [Link](x)

# Default spines
[Link](x, y, 'steelblue', lw=2)
ax1.set_title('Default Spines (4 borders)', fontsize=12)

# Custom spines — like Seaborn or matplotlib default style


[Link](x, y, 'steelblue', lw=2)
ax2.set_title('Custom Spines', fontsize=12)

# Hide top and right spines (clean academic style)


[Link]['top'].set_visible(False)
[Link]['right'].set_visible(False)

# Style remaining spines


[Link]['left'].set_color('#2E75B6')
[Link]['left'].set_linewidth(2)
[Link]['bottom'].set_color('#2E75B6')
[Link]['bottom'].set_linewidth(2)

# Move y-axis tick marks inward


ax2.tick_params(direction='in', length=5, width=1.5, colors='#2E75B6')

for ax in [ax1, ax2]:


[Link](True, alpha=0.3)
ax.set_xlabel('X'); ax.set_ylabel('Y')

plt.tight_layout()
[Link]()

>> Left: default 4-sided box frame.


>> Right: clean academic style — only left and bottom spines visible,
>> colored steel blue, tick marks pointing inward.
>> This style is common in Nature, Science, and academic ML publications.

10.7 Figure Aesthetics — Complete Professional Plot


Let's combine everything we've learned into one complete, publication-ready ML visualization:

import [Link] as plt


import numpy as np

# ─── Style Setup ───────────────────────────────────────────────


[Link]({
'[Link]': 'DejaVu Sans',
'[Link]': 11,
'[Link]': 14,
'[Link]': 12,
'[Link]': 10,
'[Link]': 10,
'[Link]': 10,
'[Link]': 'white',
'[Link]': '#FAFAFA',
'[Link]': True,
'[Link]': 0.35,
'[Link]': '--',
})

[Link](42)
epochs = [Link](1, 41)

Matplotlib for AI & Machine Learning Page 56


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

train_loss = 0.85 * [Link](-epochs/10) + 0.10 + [Link](0, 0.008, 40)


val_loss = 0.85 * [Link](-epochs/12) + 0.13 + [Link](0, 0.012, 40)
train_acc = 0.60 + 0.36*([Link](-epochs/8)) + [Link](0, 0.005, 40)
val_acc = 0.58 + 0.33*([Link](-epochs/9)) + [Link](0, 0.008, 40)

fig, (ax1, ax2) = [Link](1, 2, figsize=(15, 6))


[Link].set_facecolor('white')

# ─── Loss Plot ─────────────────────────────────────────────────


[Link](epochs, train_loss, color='#2E75B6', lw=2.5, label='Train Loss',
zorder=3)
[Link](epochs, val_loss, color='#E87722', lw=2.5, ls='--', label='Val Loss',
zorder=3)
ax1.fill_between(epochs, train_loss, val_loss, alpha=0.08, color='purple',
label='Generalization Gap')
ax1.set_title('Training & Validation Loss', fontweight='bold', pad=12)
ax1.set_xlabel('Epoch'); ax1.set_ylabel('Cross-Entropy Loss')
[Link](loc='upper right')
[Link][['top','right']].set_visible(False)

# ─── Accuracy Plot ─────────────────────────────────────────────


[Link](epochs, train_acc, color='#2E75B6', lw=2.5, label='Train Acc', zorder=3)
[Link](epochs, val_acc, color='#E87722', lw=2.5, ls='--', label='Val Acc',
zorder=3)

best_ep = [Link](val_acc) + 1
best_acc = val_acc[best_ep-1]
[Link]([best_ep], [best_acc], s=120, c='#217346', zorder=5)
[Link](f'Best: {best_acc:.3f}\n@ Epoch {best_ep}',
xy=(best_ep, best_acc), xytext=(best_ep+4, best_acc-0.04),
arrowprops=dict(arrowstyle='->', color='#217346', lw=1.5),
fontsize=10, color='#217346', fontweight='bold',
bbox=dict(boxstyle='round,pad=0.3', facecolor='#E8F5E9', alpha=0.9))

[Link](0.90, color='#C00000', ls=':', lw=1.5, alpha=0.7, label='Target:


90%')
ax2.set_title('Training & Validation Accuracy', fontweight='bold', pad=12)
ax2.set_xlabel('Epoch'); ax2.set_ylabel('Accuracy')
ax2.set_ylim(0.55, 1.0)
[Link](loc='lower right')
[Link][['top','right']].set_visible(False)

[Link]('Neural Network Training Dashboard — Binary Classification',


fontsize=16, fontweight='bold', y=1.01)
plt.tight_layout()
[Link]('training_dashboard.png', dpi=150, bbox_inches='tight')
[Link]()

>> Professional two-panel training dashboard.


>> Left panel: loss curves with purple shaded generalization gap.
>> Right panel: accuracy curves with green dot at best validation epoch,
>> red target line at 90%, arrow annotation with box.
>> Clean axes (no top/right spines), consistent styling, saved to PNG.
>> This is the standard ML training visualization used in all major papers.

Matplotlib for AI & Machine Learning Page 57


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 10.1 – Color control: hex palette, colormap sampling, and alpha transparency

Figure 10.2 – Style comparison: Default, Seaborn Dark Grid, ggplot, Dark Background

Matplotlib for AI & Machine Learning Page 58


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Figure 10.3 – Axis customization: tick labels, rotation, twin axis, color-coded axes

Chapter 10 Summary
Chapter 10 Key Takeaways
• Use hex colors (#2E75B6) and named colormaps (viridis, RdYlGn) for professional style
• [Link]() or context manager for consistent themed visualization
• Axis ticks: set_xticks(), set_xticklabels(), tick_params() for rotation/color
• Annotations: [Link](text, xy=tip, xytext=label, arrowprops=...)
• LaTeX support: use raw strings r'$\sigma(x)$' for math equations in labels
• Spines: [Link][['top','right']].set_visible(False) for clean academic style

Matplotlib for AI & Machine Learning Page 59


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Practice Exercises — Part 1


These exercises cover all 10 chapters. Complete them to solidify your understanding before moving to
Part 2.

Beginner Exercises (Chapters 1–5)


1. Install Matplotlib and print its version. Import it with the standard alias and verify by calling
[Link]().
1. Create a line chart showing y = x³ for x from -5 to 5. Add a title, axis labels, and grid.
1. Plot both y = x² and y = x³ on the same chart with different colors and a legend.

2. Create a bar chart showing the accuracy of 5 ML models of your choice. Add value labels on top
of each bar.
2. Create a horizontal bar chart ranking the top 8 features by importance (use random values).
Sort ascending before plotting.

Intermediate Exercises (Chapters 6–9)


3. Generate 1000 samples from a normal distribution (mean=70, std=15). Plot a histogram with
mean and median vertical lines. Label everything clearly.
3. Create overlapping histograms for two groups (e.g., male vs female height distributions) using
alpha=0.6. Use density=True.
2. Create a scatter plot with 200 points. Add a linear trend line and display the Pearson correlation
coefficient as text on the plot.

4. Create a 2x2 subplot grid showing: histogram, scatter plot, line chart, and bar chart — all using
the same dataset.
4. Create a pie chart showing your daily time allocation (sleep, study, food, exercise, etc.). Use the
explode parameter on your highest slice.

Advanced AI/ML Exercises


5. Simulate 50 epochs of training. Create a professional dual-panel dashboard showing loss
curves (left) and accuracy curves (right). Include legend, grid, and annotations for best
validation epoch.
5. Create a grouped bar chart comparing Precision, Recall, and F1 for 4 different classes.
Simulate a multi-class classification report.
3. Create a bubble chart comparing 6 ML models on: x = inference time (ms), y = test accuracy,
size = memory usage (MB).

6. Create a complete EDA dashboard for a synthetic 4-feature dataset. Use a 2x2 subplot grid with
one histogram per feature. Include mean/median lines and descriptive titles.
6. Recreate the learning rate comparison line chart from Chapter 4. Extend it by adding shaded
regions using fill_between() to show the 'too small' and 'too large' LR zones.

Matplotlib for AI & Machine Learning Page 60


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

💡 IMPORTANT
Challenge: Combine all customization techniques from Chapter 10 to create a single publication-
quality plot of your choice. It should include: custom rcParams, annotations with arrows, clean
spines, legend, colorbar, and a saved PNG output.

Matplotlib for AI & Machine Learning Page 61


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Interview Questions — Part 1


These are frequently asked Matplotlib questions in data science, AI/ML, and analytics interviews. Study
these before technical interviews.

Q&A Section
Q1. What is Matplotlib and why is it used in ML?
📘 NOTE
Matplotlib is Python's most popular 2D plotting library, used in ML for data exploration (EDA),
visualizing training metrics (loss/accuracy curves), model evaluation (confusion matrix, ROC curve),
and communicating results to stakeholders.

Q2. What is the difference between [Link]() and [Link]()?


Feature [Link]() [Link]()

Primary Use Connect data points with lines Show individual point positions

Best For Time series, curves, trends Correlation analysis, clusters

Marker Control All markers same size/color Each point can differ in size/color

Performance Faster for large datasets Slower for >10,000 points

3rd variable Not directly Via c= and s= parameters

Q3. How do you make a plot not display but save to a file?
📘 NOTE
Use [Link]('[Link]', dpi=150, bbox_inches='tight') BEFORE [Link](). To suppress display
entirely (e.g., in automated pipelines), use [Link]() instead of [Link](), or use a non-interactive
backend: import matplotlib; [Link]('Agg')

Q4. What is the purpose of plt.tight_layout()?


📘 NOTE
tight_layout() automatically adjusts subplot parameters to prevent labels, titles, and tick marks from
being cut off or overlapping between subplots. Always call it before [Link]() or [Link](). For
suptitle, use plt.tight_layout(rect=[0,0,1,0.95]) to leave space.

Q5. What is the difference between [Link]() and [Link]()?


Aspect [Link](nrows, ncols, idx) fig, axes = [Link](nrows,
ncols)

Return Value Single Axes object Figure + array of Axes objects

Call Pattern Call once per subplot Call once for all subplots

Matplotlib for AI & Machine Learning Page 62


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Axis Access Via [Link]() Via axes[row, col] indexing

Preferred Quick scripting Modern, recommended approach

SharedAxes Not supported Via sharex=, sharey= parameters

Q6. What is rcParams? How do you use it?


📘 NOTE
rcParams (runtime configuration parameters) is a dictionary-like object that controls default visual
settings for all plots in a session. Set with [Link]['[Link]'] = (10,6) or batch-update with
[Link]({...}). Reset with [Link]().

Q7. How do you visualize training vs validation loss in Matplotlib?


# Standard pattern for ML training curves
[Link](figsize=(10, 5))
[Link](epochs, train_loss, 'b-', lw=2, label='Training Loss')
[Link](epochs, val_loss, 'r--', lw=2, label='Validation Loss')
[Link]('Training & Validation Loss')
[Link]('Epoch'); [Link]('Loss')
[Link](loc='upper right')
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()

Q8. What is the difference between figure-level and axes-level functions?


Category Figure-Level (plt.*) Axes-Level (ax.*)

Example [Link](), [Link]() ax.set_title(), ax.set_xlabel()

Scope Acts on current active axes Acts on specific axes object

Recommended Simple single-plot scripts Multi-subplot scripts

Consistency Can be ambiguous in subplots Precise and unambiguous

Q9. How do you annotate a specific point on a line chart?


# Annotate best epoch in a training curve
[Link](
'Best Validation Accuracy',
xy=(best_epoch, best_accuracy), # Arrow tip location
xytext=(best_epoch+3, best_accuracy-0.05), # Text box location
arrowprops=dict(arrowstyle='->', color='green', lw=2),
fontsize=11, color='green', fontweight='bold',
bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8)
)

Q10. What colormaps are best for ML heatmaps and confusion matrices?
📘 NOTE
For confusion matrices: use 'Blues' (intensity shows count). For correlation matrices: use 'coolwarm'

Matplotlib for AI & Machine Learning Page 63


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

or 'RdYlGn' (diverging from 0). For feature intensity maps: use 'viridis' (perceptually uniform,
colorblind-friendly). Avoid 'jet' — it misleads perception of gradients.

Matplotlib for AI & Machine Learning Page 64


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Cheat Sheet — Most Used Commands (Part 1)


This quick-reference section covers the most frequently used Matplotlib commands from Chapters 1–
10. The full cheat sheet appears in Part 2.

Essential Setup
import [Link] as plt
import numpy as np
%matplotlib inline # Jupyter inline plots
[Link]['[Link]'] = (10, 6)
[Link]('seaborn-v0_8-darkgrid')

Core Plotting Commands


Command Purpose Key Parameters

[Link](x,y) Line chart color, lw, ls, marker, ms, label, alpha

[Link](x,y) Scatter plot c, s, cmap, alpha, edgecolors

[Link](x,y) Vertical bar color, width, edgecolor, bottom

[Link](y,x) Horizontal bar color, height, edgecolor

[Link](data) Histogram bins, color, edgecolor, density, alpha

[Link](sizes) Pie chart labels, autopct, explode, shadow, colors

[Link](r,c,i) Single subplot nrows, ncols, index (1-based)

[Link](r,c) Multi subplot figsize, sharex, sharey

[Link](txt) Annotation with xy, xytext, arrowprops, bbox


arrow

[Link](sc) Add colorbar label, shrink, pad


Table CS.1 – Core Matplotlib Command Reference

Labels, Titles, and Formatting


[Link]('Title', fontsize=14, fontweight='bold', pad=12)
[Link]('X Axis', fontsize=12, labelpad=8)
[Link]('Y Axis', fontsize=12)
[Link](loc='best', fontsize=11, framealpha=0.9)
[Link](True, ls='--', alpha=0.3)
[Link](0, 100) | [Link](0, 1)
[Link](rotation=45, fontsize=10)
plt.tight_layout() # Always call before show()/savefig()
[Link]('[Link]', dpi=150, bbox_inches='tight')
[Link]()

Matplotlib for AI & Machine Learning Page 65


📊 Matplotlib for AI & Machine Learning — Part 1 Chapters 1–10

Line Styles Quick Reference


Style Code Marker Code

Solid '-' Circle 'o'

Dashed '--' Square 's'

Dash-dot '-.' Triangle '^'

Dotted ':' Diamond 'D'

No line 'None' Star '*'


Table CS.2 – Line and Marker Quick Reference

📘 End of Part 1
Chapters 1–10 Complete
Part 2 Coverage:
Chapter 11: NumPy & Pandas Integration | Chapter 12: Advanced Visualization (Heatmaps, 3D)
Chapter 13: Matplotlib in Machine Learning | Chapter 14: Real AI/ML Projects
Chapter 15: Seaborn Integration | Chapter 16: Best Practices
Chapter 17: Common Errors & Debugging | Chapter 18: Full Cheat Sheet
Chapter 19: All Practice Exercises | Chapter 20: Full Interview Questions & Answers

Matplotlib for AI & Machine Learning Page 66

You might also like