This tutorial covers the essential Matplotlib concepts for data visualization, using a step‑by‑step approach with mental models and practical examples.
1. Introduction
What is Matplotlib?
Matplotlib is a Python library used to create visualizations.
Matplotlib is one of the most widely used Python libraries for creating static, interactive, and publication-quality visualizations.
It also works very well with libraries such as NumPy and Pandas.
Why learn Matplotlib?
Visualization is essential for understanding data before applying Machine Learning.
Flexibility – you can customize almost every element of a plot.
Integration – it’s the backbone of plotting in Pandas and many other libraries.
Importing Matplotlib
Let’s start by importing the necessary libraries:
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
If you're using Jupyter Notebook or Colab, add this magic command to display plots inline:
%matplotlib inline
2. Two Ways to Plot: Pyplot vs Object-Oriented
Matplotlib offers two main approaches:
Pyplot (functional) – Quick and simple, but less flexible for complex plots.
Object‑Oriented (OO) – More explicit and powerful; recommended for advanced work.
Both approaches can produce the same types of charts. The main difference is how we control the chart.
Pyplot Method
The Pyplot approach is the simpler approach.
plt.plot([1, 2, 3, 4])plt.show()
This uses the global plt interface. It's useful when you want to create a quick visualization without needing much customization.
Object‑Oriented Method
The Object-Oriented approach is a little more explicit.
# Create a figure and an axes objectfig, ax = plt.subplots()# Plot data on the axesax.plot([1, 2, 3, 4])# Display the plotplt.show()
The OO method gives you explicit control over the Figure (the whole canvas) and Axes (the actual plot area). It’s the recommended approach for anything beyond simple plots.
You can also create a figure and add axes manually:
x = np.linspace(0, 10, 100)y = x ** 2fig = plt.figure() # create an empty figureax = fig.add_subplot() # add a single subplotax.plot(x, y) # plot data on the axesplt.show() # display the figure
But plt.subplots() is more convenient and is the standard.
3. Plotting Basics
Let's explore the most common plot types:
Line plot → shows trends or changes
Scatter plot → shows relationships between variables
Bar plot → compares categories
Histogram → shows the distribution of numerical data
Line Plot
A line plot connects data points with a line. It's commonly used when we want to see how something changes.
x = np.linspace(0, 10, 100) # 100 points from 0 to 10y = x ** 2fig, ax = plt.subplots()ax.plot(x, y)plt.show()
Scatter Plot
A scatter plot displays individual points instead of connecting them with lines. Scatter plots are useful for showing relationships between two variables.
fig, ax = plt.subplots()ax.scatter(x, np.exp(x)) # scatter plot of exponentialplt.show()
A simple mental model:
Scatter plot = put a dot wherever an (x, y) value exists.
It's often useful when asking questions like:
"Does one variable have a relationship with another variable?"
Bar Plot
Bar charts compare categories. We can plot from a dictionary:
Note:.keys() and .values() return view objects. Wrapping them in list() is not always required by recent Matplotlib versions, but it's the safest, most portable form.
Histogram
Histograms show the distribution of a dataset.
data = np.random.randn(1000) # 1000 random numbers from normal distributionfig, ax = plt.subplots()ax.hist(data)plt.show()
A histogram groups values into ranges called bins and shows how many values fall into each range. Think of it as:
"Where are most of my values concentrated?"
This makes histograms particularly useful when exploring a dataset before Machine Learning.
4. Subplots
You can create multiple plots in the same figure using plt.subplots().
The Make column has inconsistent capitalization ("toyota", "TOYOTA", "Toyota"). Normalize it so they aren't treated as separate categories when grouping or plotting:
car_sales["Make"] = car_sales["Make"].str.title()
The Price column is currently a string. We need to convert it to a numeric type:
Important:car_sales.plot(x='Make', y='Odometer (KM)', kind='bar') draws one bar per row, not one bar per make. If you want a per-make comparison, use groupby(...).mean() (or another aggregation) before plotting.
This lets us see the distribution of the cars' odometer values.
6. Customizing Your Plots
Creating a chart is only the first step. We often need to customize it so that the information is easier to understand.
Common customizations include:
Styles
Colors
Axis limits
Legends
Titles
Labels
Reference lines
Note: The examples in Sections 6.2 and 6.3 use over_50, which is created in Section 8 from the heart disease dataset. If you're following along out of order, you can create a small stand-in:
Create Figure + Axes ↓Add data ↓Set colors ↓Add title and labels ↓Add legend ↓Add mean reference line ↓Display
Subplot with Two Scatter Plots
Now let's compare two different relationships in one figure:
Cholesterol vs age
Maximum heart rate vs age
fig, (ax0, ax1) = plt.subplots( nrows=2, ncols=1, figsize=(10, 10), sharex=True)# First subplot: cholesterol vs agescatter = ax0.scatter(over_50['age'], over_50['chol'], c=over_50['target'], cmap='winter')ax0.set(title="Heart Disease and Cholesterol Levels", ylabel="Cholesterol")ax0.legend(*scatter.legend_elements(), title="Target")ax0.axhline(over_50['chol'].mean(), linestyle='--')# Second subplot: max heart rate vs agescatter = ax1.scatter(over_50['age'], over_50['thalach'], c=over_50['target'], cmap='winter')ax1.set(title="Heart Disease and Max Heart Rate", xlabel="Age", ylabel="Max Heart Rate")ax1.legend(*scatter.legend_elements(), title="Target")ax1.axhline(over_50['thalach'].mean(), linestyle='--')fig.suptitle("Heart Disease Analysis", fontsize=16, fontweight='bold')plt.show()
Notice:
sharex=True
Both plots use age on the x-axis, so sharing the x-axis makes comparison easier.
The final result is one Figure containing two related visualizations.
9. Key Takeaways
Two main approaches: pyplot (quick) and object-oriented (explicit, recommended).
Common plots: line, scatter, bar, histogram.
Subplots let you arrange multiple plots in one figure.
Pandas integration makes it easy to plot directly from DataFrames—but aggregate with groupby() when you want one bar per category, not one bar per row.
Customization includes styles, colors, colormaps, axis limits, legends, and mean lines.
Always save your figures with fig.savefig() when you want to keep them.
Clean your data first (e.g., normalize string categories, strip currency symbols) so plots don't split categories unexpectedly.
Mental model:
Think of a figure as a canvas, and axes as the individual plots you draw on it. For most visualizations, think:
Create Figure + Axes ↓Add Data ↓Customize ↓Show / Save
The most important distinction to remember is:
Figure = the whole canvasAxes = the actual plotting area
Once this mental model is clear, the different Matplotlib functions become much easier to understand.
With these skills, you can create informative and visually appealing charts for data analysis and Machine Learning projects.