Beginner

Getting Started with Matplotlib

Matplotlib architecture and building line, scatter and bar charts.

Level: Beginner


Table of Contents

  1. Course Overview
  2. Understanding Matplotlib Architecture
  3. Building Line Charts
  4. Working with Scatter Plots
  5. Creating Bar Charts
  6. Reference Tables
  7. 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.

TermDefinition
FigureThe global container — the entire window or page. Can contain one or more Axes.
AxesThe plotting area inside the Figure where a chart is rendered. Contains x-axis and y-axis objects.
AxisAn individual axis (x, y, or z for 3D charts). Includes tick marks, tick labels, and labels.
ArtistAny visual element on the Figure (lines, text, markers, patches, etc.).
TitleDescriptive text placed above an Axes.
LegendKey for interpreting encoded data.
AnnotationText or arrow to highlight a data point.
GridHorizontal/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…)       │
└─────────────────────────────────────────┘
LayerRoleUsage
BackendRendering in environment (Jupyter, GUI, file)Automatic
ArtistObject-oriented API, fine control (fig, ax)Programmers
Scripting (pyplot)plt.* interface, simple and fastEveryone

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 inline backend automatically calls plt.show() at the end of each cell. In other environments, you must call plt.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

AspectScripting Layer (plt.*)Artist Layer (OOP)
Syntaxplt.plot(x, y)fig, ax = plt.subplots(); ax.plot(x, y)
ControlImplicit (manages Figure/Axes automatically)Explicit (direct reference to objects)
UsageQuick scripts, explorationComplex applications, multiple subplots
Titleplt.title('...')ax.set_title('...')
Labelsplt.xlabel('...')ax.set_xlabel('...')

2.6 Text and Colors

Adding Text

ElementScripting LayerArtist Layer
Axes titleplt.title('...')ax.set_title('...')
X axis labelplt.xlabel('...')ax.set_xlabel('...')
Y axis labelplt.ylabel('...')ax.set_ylabel('...')
Figure titlefig.suptitle('...')fig.suptitle('...')
Arbitrary textplt.text(x, y, '...')ax.text(x, y, '...')
Annotationplt.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:

ColumnTypeDescription
IDintTrip identifier
Pickup_DatedatePickup date
Payment_TypestrPayment method
Total_AmountfloatTotal amount paid
Tip_AmountfloatTip
Passenger_CountintNumber of passengers
Rate_CodestrRate code (e.g., JFK)
Week_NointWeek 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

ParameterDescriptionExamples
color / cLine color'r', '#00A3FF', 'green'
linewidth / lwLine thickness1, 2.5
linestyle / lsLine style'-', '--', '-.', ':'
markerMarker type on points'o', 's', '^', '*', '.'
markersize / msMarker size5, 10
markerfacecolor / mfcMarker fill color'blue', 'none'
alphaTransparency (0–1)0.5
labelText 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 type
  • s=5 — reduce marker size
  • alpha=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

ChartFunctionWhen to Use
Line Chartplt.plot()Trends over time, continuous data
Scatter Plotplt.scatter()Correlation between 2 variables
Bar Chartplt.bar()Categorical comparison, vertical
Horizontal Barplt.barh()Categorical comparison, horizontal
Stacked Barplt.bar() + bottom=Part-to-whole relationships
Histogramplt.hist()Frequency distribution
Pie Chartplt.pie()Proportions of a whole
Box Plotplt.boxplot()Statistical distribution

Common Parameters

ParameterLine ChartScatter PlotBar Chart
Colorcolor=c= or color=color=
Transparencyalpha=alpha=alpha=
Sizelinewidth=s=width=
Borderedgecolors=edgecolor=
Labelslabel=label=label=

Line Styles and Markers

LinestyleCodeMarkersCode
Solid'-'Circle'o'
Dashed'--'Square's'
Dash-dot'-.'Triangle up'^'
Dotted':'Star'*'
None'None'Point'.'

Color Specification

MethodExampleWhen 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

Interested in this course?

Contact us to book it or get a custom training plan for your team.