Level: Beginner
Table of Contents
- Course Overview
- Understanding Matplotlib Architecture
- Building Line Charts
- Working with Scatter Plots
- Creating Bar Charts
- Reference Tables
- Reference Diagrams
1. Course Overview
Matplotlib is a data visualization library for Python. This course covers the basics for creating and customizing fundamental charts: line charts, bar charts, and scatter plots.
Prerequisites:
- Familiarity with the Jupyter Notebook interface
- Data manipulation with Pandas
What you will learn:
- Matplotlib architecture (Figure, Axes, Artist)
- Both APIs: scripting layer (
plt.*) and artist layer (OOP) - Creating and customizing line charts, scatter plots, and bar charts
- Exporting figures to PNG/PDF
2. Understanding Matplotlib Architecture
2.1 Installation
# Via pip
pip install matplotlib
# Via conda (Anaconda distribution)
conda install matplotlib
Verify installed version:
import matplotlib
print(matplotlib.__version__) # e.g.: 3.6.2
2.2 Figure Anatomy
Matplotlib has its own vocabulary. Understanding these terms from the start makes reading documentation and debugging code easier.
| Term | Definition |
|---|---|
| Figure | The global container — the entire window or page. Can contain one or more Axes. |
| Axes | The plotting area inside the Figure where a chart is rendered. Contains x-axis and y-axis objects. |
| Axis | An individual axis (x, y, or z for 3D charts). Includes tick marks, tick labels, and labels. |
| Artist | Any visual element on the Figure (lines, text, markers, patches, etc.). |
| Title | Descriptive text placed above an Axes. |
| Legend | Key for interpreting encoded data. |
| Annotation | Text or arrow to highlight a data point. |
| Grid | Horizontal/vertical reference lines for easier value reading. |
Object hierarchy:
Figure
└── Axes (1 or more)
├── XAxis
│ ├── tick marks (major/minor)
│ └── tick labels
├── YAxis
│ ├── tick marks (major/minor)
│ └── tick labels
├── Title
├── Line2D
├── Text (annotations, labels)
└── Patch (rectangles for bar charts, etc.)
2.3 Three-Layer Architecture
Matplotlib’s architecture is conceptualized as a stack of three layers:
┌─────────────────────────────────────────┐
│ Scripting Layer (pyplot — plt.*) │ ← Simple user interface
│ High-level API, implicit │
├─────────────────────────────────────────┤
│ Artist Layer (OOP / explicit API) │ ← Fine control over each element
│ Figure, Axes, Line2D, Text, Patch… │
├─────────────────────────────────────────┤
│ Backend Layer │ ← Actual rendering in environment
│ (inline, notebook, Qt5Agg, Agg…) │
└─────────────────────────────────────────┘
| Layer | Role | Usage |
|---|---|---|
| Backend | Rendering in environment (Jupyter, GUI, file) | Automatic |
| Artist | Object-oriented API, fine control (fig, ax) | Programmers |
| Scripting (pyplot) | plt.* interface, simple and fast | Everyone |
2.4 Backends
The backend determines how and where the figure is displayed. Matplotlib automatically chooses the appropriate backend.
# Check active backend
import matplotlib.pyplot as plt
plt.get_backend() # 'module://matplotlib_inline.backend_inline' in Jupyter
# Enable interactive backend in Jupyter Notebook
import ipympl
%matplotlib notebook
Note: In Jupyter Notebook, the
inlinebackend automatically callsplt.show()at the end of each cell. In other environments, you must callplt.show()explicitly.
2.5 Demo: Creating Figures
Scripting Layer (Implicit API)
import matplotlib.pyplot as plt
import numpy as np
# Plot a single point
plt.plot(2, 2, '.')
# Plot a simple curve
x = np.array([1, 2, 3, 4, 5])
y = x * 10
plt.plot(x, y)
plt.show()
Artist Layer (Explicit API / OOP)
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = x * 10
# Create Figure and Axes separately
fig = plt.figure()
ax = plt.subplot()
ax.plot(x, y)
plt.show()
Difference Between the Two APIs
| Aspect | Scripting Layer (plt.*) | Artist Layer (OOP) |
|---|---|---|
| Syntax | plt.plot(x, y) | fig, ax = plt.subplots(); ax.plot(x, y) |
| Control | Implicit (manages Figure/Axes automatically) | Explicit (direct reference to objects) |
| Usage | Quick scripts, exploration | Complex applications, multiple subplots |
| Title | plt.title('...') | ax.set_title('...') |
| Labels | plt.xlabel('...') | ax.set_xlabel('...') |
2.6 Text and Colors
Adding Text
| Element | Scripting Layer | Artist Layer |
|---|---|---|
| Axes title | plt.title('...') | ax.set_title('...') |
| X axis label | plt.xlabel('...') | ax.set_xlabel('...') |
| Y axis label | plt.ylabel('...') | ax.set_ylabel('...') |
| Figure title | fig.suptitle('...') | fig.suptitle('...') |
| Arbitrary text | plt.text(x, y, '...') | ax.text(x, y, '...') |
| Annotation | plt.annotate(...) | ax.annotate(...) |
Text Customization Parameters
plt.title(
'Basic plot',
family='serif', # font family: serif, monospace, sans, cursive, fantasy
color='#00A3FF', # color (hex, name, letter)
weight='bold', # weight: bold, normal, black, ultralight (or 0–1000)
size=20, # size in points or: small, medium, large
ha='left', # horizontal alignment: left, center, right
x=0 # relative x position (0=left, 1=right)
)
Color Specification
# Short letter
plt.plot(x, y, color='r') # red
# Full name
plt.plot(x, y, color='green')
# Hexadecimal code
plt.plot(x, y, color='#00A3FF')
# RGB tuple (0–1)
plt.plot(x, y, color=(0.1, 0.5, 0.9))
2.7 Demo: Subplots
A Figure can contain multiple Axes. They are positioned using a grid system (rows × columns).
import matplotlib.pyplot as plt
import numpy as np
a = np.random.randint(0, high=50, size=5)
b = np.random.randint(0, high=50, size=5)
x = np.random.randint(0, high=50, size=5)
y = np.random.randint(0, high=50, size=5)
# 2×2 grid: 4 subplots
fig = plt.figure()
ax1 = plt.subplot(2, 2, 1) # row 1, column 1
ax2 = plt.subplot(2, 2, 2) # row 1, column 2
ax3 = plt.subplot(2, 2, 3) # row 2, column 1
ax4 = plt.subplot(2, 2, 4) # row 2, column 2
ax1.plot(a, b, '.')
ax2.plot(a, x, '.')
ax3.plot(x, y, '.')
ax4.plot(b, y, '.')
plt.show()
Alternative syntax with plt.subplots() (recommended):
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))
axes[0, 0].plot(a, b, '.')
axes[0, 1].plot(a, x, '.')
axes[1, 0].plot(x, y, '.')
axes[1, 1].plot(b, y, '.')
plt.tight_layout() # automatic spacing adjustment
plt.show()
3. Building Line Charts
3.1 When to Use a Line Chart
Line charts are ideal for:
- Showing trends over time
- Identifying outliers in a time series
- Making predictions about future evolution
- Comparing multiple series on the same time scale
3.2 Dataset: Yellow Taxi Trips NYC
The dataset used throughout this course is a public dataset of Yellow Taxi trips in New York City (January 2022, source: NYC Government).
Main columns:
| Column | Type | Description |
|---|---|---|
ID | int | Trip identifier |
Pickup_Date | date | Pickup date |
Payment_Type | str | Payment method |
Total_Amount | float | Total amount paid |
Tip_Amount | float | Tip |
Passenger_Count | int | Number of passengers |
Rate_Code | str | Rate code (e.g., JFK) |
Week_No | int | Week number |
3.3 Demo: Creating Line Charts
Data Preparation
import matplotlib.pyplot as plt
import pandas as pd
# Import 5 CSV files (one per week)
df1 = pd.read_csv('Yellow Taxi Trips - Week 1.csv')
df2 = pd.read_csv('Yellow Taxi Trips - Week 2.csv')
df3 = pd.read_csv('Yellow Taxi Trips - Week 3.csv')
df4 = pd.read_csv('Yellow Taxi Trips - Week 4.csv')
df5 = pd.read_csv('Yellow Taxi Trips - Week 5.csv')
full_dataset = pd.concat([df1, df2, df3, df4, df5])
# Convert date column to proper type
full_dataset['Pickup_Date'] = pd.to_datetime(
full_dataset['Pickup_Date'],
format='%d/%m/%Y'
)
# Aggregation: total trips per day
trips = full_dataset.groupby(
by='Pickup_Date',
as_index=False
)['ID'].count()
trips.rename(columns={'ID': 'Trips'}, inplace=True)
Creating the Line Chart
# --- Scripting Layer (implicit) ---
plt.plot(trips['Pickup_Date'], trips['Trips'])
plt.show()
# --- Artist Layer (explicit / OOP) ---
fig, ax = plt.subplots()
ax.plot(trips['Pickup_Date'], trips['Trips'])
plt.show()
3.4 Demo: Customizing Line Charts
fig, ax = plt.subplots(figsize=(9, 4))
ax.plot(
trips['Pickup_Date'],
trips['Trips'],
'#5A5A5A', # line color
linewidth=2, # line thickness
linestyle='--', # style: '-', '--', '-.', ':'
marker='o', # marker type
markersize=5, # marker size
markerfacecolor='blue'
)
ax.set_title('Yellow Taxi Trips in New York City')
ax.set_xlabel('Pickup Date')
ax.set_ylabel('Trips')
ax.set_ylim(0, 120000)
fig.autofmt_xdate() # auto-rotate date labels
plt.show()
plt.plot() / ax.plot() Key Parameters
| Parameter | Description | Examples |
|---|---|---|
color / c | Line color | 'r', '#00A3FF', 'green' |
linewidth / lw | Line thickness | 1, 2.5 |
linestyle / ls | Line style | '-', '--', '-.', ':' |
marker | Marker type on points | 'o', 's', '^', '*', '.' |
markersize / ms | Marker size | 5, 10 |
markerfacecolor / mfc | Marker fill color | 'blue', 'none' |
alpha | Transparency (0–1) | 0.5 |
label | Text for legend | 'Series A' |
4. Working with Scatter Plots
4.1 When to Use a Scatter Plot
Scatter plots are used to:
- Visualize the relationship between two variables
- Identify the direction (positive/negative) and strength of a correlation
- Detect clusters and outliers
- Correlation analysis (without implying causality)
⚠️ Warning: Correlation ≠ Causation.
Overplotting solution: When many points overlap, use:
marker='.'— smaller marker types=5— reduce marker sizealpha=0.15— adjust transparency
4.2 Demo: Creating Scatter Plots
import matplotlib.pyplot as plt
import pandas as pd
taxi_trips = pd.read_csv('Yellow Taxi Trips - Week 1.csv')
JFK_trips = taxi_trips[
(taxi_trips['Payment_Type'] == 'Credit card') &
(taxi_trips['Rate_Code'] == 'JFK') &
(taxi_trips['Passenger_Count'] > 0) &
(taxi_trips['Total_Amount'] < 90)
]
# Method 1: plt.scatter()
plt.scatter(JFK_trips['Total_Amount'], JFK_trips['Tip_Amount'])
plt.show()
# Method 2: plt.plot() with linestyle='None'
plt.plot(
JFK_trips['Total_Amount'],
JFK_trips['Tip_Amount'],
linestyle='None',
marker='o'
)
plt.show()
4.3 Demo: Customizing Scatter Plots
Scatter plot with colorbar (3rd variable encoded)
plt.figure(figsize=(9, 4))
scatter = plt.scatter(
JFK_trips['Total_Amount'],
JFK_trips['Tip_Amount'],
marker='o',
s=10,
c=JFK_trips['Passenger_Count'], # color encoded by 3rd variable
cmap='plasma', # colormap
alpha=0.6
)
plt.title('Is there a relationship between the total amount paid and the tip amount?')
plt.xlabel('Total Amount')
plt.ylabel('Tip Amount')
cbar = plt.colorbar(orientation='horizontal')
cbar.set_label('Passengers')
plt.show()
5. Creating Bar Charts
5.1 When to Use a Bar Chart
Bar charts are ideal for:
- Comparing categories and ranking them easily
- Analyzing rankings (historical highs and lows at a glance)
- Showing part-to-whole relationships (stacked bar charts)
- Identifying trends and outliers by category
5.2 Demo: Creating Bar Charts
import matplotlib.pyplot as plt
import pandas as pd
full_dataset = pd.concat([pd.read_csv(f'Yellow Taxi Trips - Week {i}.csv') for i in range(1,6)])
trips = full_dataset.groupby(by='Payment_Type', as_index=False)['ID'].count()
trips.rename(columns={'ID': 'Trips'}, inplace=True)
# Vertical bar chart
plt.bar(trips['Payment_Type'], trips['Trips'])
plt.title('Yellow Taxi Trips by Payment Method')
plt.xlabel('Payment Method')
plt.ylabel('Trips')
plt.show()
# Horizontal bar chart
plt.barh(trips['Payment_Type'], trips['Trips'])
plt.show()
Stacked bar chart
weekly_trips = full_dataset.pivot_table(
values='ID',
index='Week_No',
columns='Payment_Type',
aggfunc='count'
).reset_index()
plt.bar(weekly_trips['Week_No'], weekly_trips['Cash'], label='Cash')
plt.bar(
weekly_trips['Week_No'],
weekly_trips['Credit card'],
bottom=weekly_trips['Cash'],
label='Credit card'
)
plt.legend()
plt.show()
5.3 Demo: Customizing Bar Charts
colors = ['#00A3FF', '#1B1834']
barchart = plt.bar(
trips['Payment_Type'],
trips['Trips'],
width=0.6,
color=colors,
alpha=0.8,
edgecolor='black',
linewidth=2,
linestyle='-'
)
plt.title('Yellow Taxi Trips by Payment Method')
plt.xlabel('Payment Method')
plt.ylabel('Trips')
plt.bar_label(barchart, labels=trips['Trips'])
plt.show()
5.4 Demo: Exporting Figures
# Export to PNG (high resolution)
plt.savefig(
'barchart.png',
dpi=300, # dots per inch (300 = print quality)
bbox_inches='tight' # avoid clipping
)
# Export to PDF
plt.savefig('barchart.pdf', bbox_inches='tight')
6. Reference Tables
Chart Types
| Chart | Function | When to Use |
|---|---|---|
| Line Chart | plt.plot() | Trends over time, continuous data |
| Scatter Plot | plt.scatter() | Correlation between 2 variables |
| Bar Chart | plt.bar() | Categorical comparison, vertical |
| Horizontal Bar | plt.barh() | Categorical comparison, horizontal |
| Stacked Bar | plt.bar() + bottom= | Part-to-whole relationships |
| Histogram | plt.hist() | Frequency distribution |
| Pie Chart | plt.pie() | Proportions of a whole |
| Box Plot | plt.boxplot() | Statistical distribution |
Common Parameters
| Parameter | Line Chart | Scatter Plot | Bar Chart |
|---|---|---|---|
| Color | color= | c= or color= | color= |
| Transparency | alpha= | alpha= | alpha= |
| Size | linewidth= | s= | width= |
| Border | — | edgecolors= | edgecolor= |
| Labels | label= | label= | label= |
Line Styles and Markers
| Linestyle | Code | Markers | Code |
|---|---|---|---|
| Solid | '-' | Circle | 'o' |
| Dashed | '--' | Square | 's' |
| Dash-dot | '-.' | Triangle up | '^' |
| Dotted | ':' | Star | '*' |
| None | 'None' | Point | '.' |
Color Specification
| Method | Example | When to Use |
|---|---|---|
| Short letter | 'r' | Quick prototyping |
| Full name | 'steelblue' | Readability |
| Hex code | '#00A3FF' | Exact color control |
| RGB tuple | (0.1, 0.5, 0.9) | Programmatic colors |
7. Reference Diagrams
Visualization Workflow
flowchart LR
A[Import\ndata] --> B[Prepare\nPandas DataFrame]
B --> C[Choose\nchart type]
C --> D[Create\nFigure and Axes]
D --> E[Plot\ndata]
E --> F[Customize\ntext, colors, styles]
F --> G[Display\nplt.show]
G --> H[Export\nsavefig]
Chart Type Decision
flowchart TD
Q1{What is\nthe goal?}
Q1 -->|Trend over time| LC["Line Chart\nplt.plot()"]
Q1 -->|Relationship between 2 variables| SC["Scatter Plot\nplt.scatter()"]
Q1 -->|Compare categories| Q2{Orientation?}
Q1 -->|Distribution| H["Histogram\nplt.hist()"]
Q1 -->|Proportions| P["Pie Chart\nplt.pie()"]
Q2 -->|Vertical| BC["Bar Chart\nplt.bar()"]
Q2 -->|Horizontal| BH["Horizontal Bar\nplt.barh()"]
Q2 -->|Composition| SB["Stacked Bar\nplt.bar + bottom="]
Search Terms
matplotlib · python · foundations · data · analysis · engineering · analytics · chart · charts · line · bar · scatter · customizing · parameters · plots · text · api · architecture · color · figures · layer · plot · reference · specification