A Deep Dive into
Matplotlib
Module-5
Syllabus:
• A Deep Dive into Matplotlib Introduction, Overview of
Plots in Matplotlib, Pyplot Basics: Creating Figures,
Closing Figures, Format Strings, Plotting, Plotting Using
pandas DataFrames, Displaying Figures, Saving Figures;
Basic Text and Legend Functions: Labels, Titles, Text,
Annotations, Legends; Basic Plots:Bar Chart, Pie Chart,
Stacked Bar Chart, Stacked Area Chart, Histogram, Box
Plot, Scatter Plot, Bubble Plot; Layouts: Subplots, Tight
Layout, Radar Charts, GridSpec; Images: Basic Image
Operations, Writing Mathematical Expressions Textbook
2: Chapter 3
28/04/2025 A Deep Dive into Matplotlib 2
Course Outcome:
CO 5. Develop different charts and
include mathematical expressions.
28/04/2025 A Deep Dive into Matplotlib 3
Introduction
• In the last chapter, we explored different types of
visualizations to find out which ones are best for
displaying specific information from a dataset.
• We looked at various plots like comparison plots, relation
plots, composition plots, distribution plots, and geoplots,
and discussed their features, uses, and best practices.
28/04/2025 A Deep Dive into Matplotlib 4
Matplotlib
• Matplotlib is one of the most popular Python libraries
for creating the visualizations.
• It was created by John Hunter, an American
neurobiologist, in 2003.
• He designed Matplotlib to be similar to MATLAB, a
software widely used in scientific research at the time,
making it easier for MATLAB users to switch to Matplotlib.
28/04/2025 A Deep Dive into Matplotlib 5
• Before diving into creating visualizations with Matplotlib,
it's important to understand its hierarchical structure.
• We'll learn the basics like how to create, display, and
save Figures (plots).
• We'll also cover common visualizations, text and legend
functions, and how to combine multiple plots into one
layout.
• Finally, we'll discuss how to plot images and use
mathematical expressions in our plots.
28/04/2025 A Deep Dive into Matplotlib 6
Overview of Plots in Matplotlib
• Matplotlib plots have a tree-like structure with
different components nested inside each other.
• The top-level container is called a Figure. This
can hold multiple Axes, which are individual
plots.
28/04/2025 A Deep Dive into Matplotlib 7
Overview of Plots in Matplotlib
28/04/2025 A Deep Dive into Matplotlib 8
Two Main Components of a plot:
• Figure: The outermost container that
can contain multiple plots. It can also have
a title.
• Axes: The actual plot, which can be a
single plot or multiple subplots. Each Axes
includes the x-axis, y-axis, spines, and
legends.
28/04/2025 A Deep Dive into Matplotlib 9
28/04/2025 A Deep Dive into Matplotlib 10
28/04/2025 A Deep Dive into Matplotlib 11
•Figure: The outermost
container with the title "Figure:
The Outermost Container".
•Axes: The actual plot with the
title "Axes: The Actual Plot".
•Spines: Green lines connecting
the axis tick marks.
•Title: The main label for the
entire Figure.
28/04/2025 A Deep Dive into Matplotlib 12
•Legend: Describes the
content of the plot, shown as
"Line Plot".
•Grid: Vertical and horizontal
lines extending from tick marks.
•X/Y Axis Labels: Labels for
the X and Y axes.
•Ticks: Indicators for values on
the axes, with red major ticks
and blue minor ticks.
•Lines and Markers: Lines
connecting data points with
markers highlighting individual
points.
28/04/2025 A Deep Dive into Matplotlib 13
Note:
The term "Axes" in Matplotlib refers to the actual area
where the data is plotted. Each "Axes" object can
contain:
• The data itself (lines, markers, bars, etc.)
• Labels for the x and y axes
• Tick marks along the x and y axes
• Grid lines
• A title for the Axes
• A legend
28/04/2025 A Deep Dive into Matplotlib 14
As per Textbook
28/04/2025 A Deep Dive into Matplotlib 15
• Spines: Lines connecting the axis tick marks.
• Title: Text label of the whole Figure object
• Legend: Describes the content of the plot
• Grid: Vertical and horizontal lines used as an extension of the
tick marks
• X/Y axis label: Text labels for the X and Y axes below the spines
• Minor tick: Small value indicators between the major tick marks
• Minor tick label: Text label that will be displayed at the minor
ticks
• Major tick: Major value indicators on the spines
• Major tick label: Text label that will be displayed at the major
ticks
• Line: Plotting type that connects data points with a line
• Markers: Plotting type that plots every data point with a defined
marker
28/04/2025 A Deep Dive into Matplotlib 16
Pyplot Basics
• Pyplot provides a simple way to
create visualizations in Python.
28/04/2025 A Deep Dive into Matplotlib 17
Here's how pyplot works:
1. Importing Pyplot:
Use import matplotlib.pyplot as
plt to bring in Pyplot, often using the
alias plt for convenience.
28/04/2025 A Deep Dive into Matplotlib 18
How pyplot works
2. Creating Figures:
• Figure: The main container for plots.
• Use plt.figure() to create a new Figure.
• By default, Figures are 6.4 inches wide, 4.8 inches
tall, with a resolution of 100 dots per inch (dpi).
plt.figure(figsize=(10, 5)) # Change width and height
plt.figure(dpi=300) # Change dpi
28/04/2025 A Deep Dive into Matplotlib 19
How pyplot works
3. Closing Figures:
• Close Figures with plt.close() to free up memory.
• By default, plt.close() closes the current Figure.
plt.figure(num=10) # Create Figure with number 10
plt.close(10) # Close Figure with number 10
plt.close('all’) #closes all open Figures.
28/04/2025 A Deep Dive into Matplotlib 20
Format Strings
• The format strings are a neat way to
specify colors, marker types, and line
styles.
• A format string is specified as [color]
[marker][line], where each item is
optional.
28/04/2025 A Deep Dive into Matplotlib 21
Format Strings
• If the color argument is the only argument of the format
string, you can use matplotlib.colors.
• Matplotlib recognizes the following formats, among others:
• RGB or RGBA float tuples (for example, (0.2, 0.4, 0.3) or
(0.2, 0.4, 0.3, 0.5))
• RGB or RGBA hex strings (for example, '#0F0F0F' or
'#0F0F0F0F')
28/04/2025 A Deep Dive into Matplotlib 22
RGB or RGBA Float Tuples:
• RGB: A tuple of three float values representing the Red, Green,
and Blue components of the color, each ranging from 0 to 1. For
example, (0.2, 0.4, 0.3) represents a specific shade of green.
• RGBA: Similar to RGB but includes an Alpha component for
transparency. For example, (0.2, 0.4, 0.3, 0.5) where the last value
(0.5) represents 50% transparency.
28/04/2025 A Deep Dive into Matplotlib 23
RGB or RGBA Hex Strings:
• RGB: A string starting with a # followed by six
hexadecimal digits. For example, '#0F0F0F' represents
a very dark gray color.
• RGBA: Similar to RGB but includes an extra two
hexadecimal digits for the Alpha component. For
example, '#0F0F0F0F' where the last two digits
represent the transparency.
28/04/2025 A Deep Dive into Matplotlib 24
The following table is an example of how a
color can be represented in one particular
format:
28/04/2025 A Deep Dive into Matplotlib 25
Markers
• All the available marker options are
illustrated in the following figure:
28/04/2025 A Deep Dive into Matplotlib 26
28/04/2025 A Deep Dive into Matplotlib 27
line styles
28/04/2025 A Deep Dive into Matplotlib 28
Plotting:
• With plt.plot([x], y, [fmt]), you can plot data points as
lines and/or markers.
• The function returns a list of Line2D objects
representing the plotted data.
• By default, if you do not provide a format string (fmt),
the data points will be connected with straight, solid
lines.
• plt.plot([0, 1, 2, 3], [2, 4, 6, 8])
28/04/2025 A Deep Dive into Matplotlib 29
plt.plot([0, 1, 2, 3], [2, 4, 6, 8], 'o')
• If you want to plot markers instead of
lines, you can just specify a format
string with any marker type.
28/04/2025 A Deep Dive into Matplotlib 30
plt.plot([x], y, [fmt], [x], y2, [fmt2], …)
• To plot multiple data pairs, the above
syntax can be used as below.
• plt.plot([2, 4, 6, 8], 'o', [1, 5, 9, 13], 's')
28/04/2025 A Deep Dive into Matplotlib 31
Plotting Using pandas DataFrames
• It is pretty straightforward to use
pandas.DataFrame as a data source.
• Instead of providing x and y values, you can
provide the pandas.DataFrame in the data
parameter and give keys for x and y, as follows:
plt.plot('x_key', 'y_key', data=df)
28/04/2025 A Deep Dive into Matplotlib 32
Advantage:
• Using pandas.DataFrame directly with
Matplotlib simplifies plotting code and
enhances readability by eliminating the
need to manage separate data arrays.
28/04/2025 A Deep Dive into Matplotlib 33
Displaying Figures
• plt.show() is used to display a Figure or
multiple Figures.
• To display Figures within a Jupyter Notebook,
simply set the %matplotlib inline command at
the beginning of the code.
• If you forget to use plt.show(), the plot won't
show up.
28/04/2025 A Deep Dive into Matplotlib 34
Saving Figures
• The plt.savefig(fname) saves the current Figure.
• There are some useful optional parameters you can
specify, such as dpi, format, or transparent.
• The following code snippet gives an example of how
you can save a Figure:
28/04/2025 A Deep Dive into Matplotlib 35
Note:
• All exercises and activities will be developed in Jupyter
Notebook. Please download the GitHub repository with
all the prepared templates from
https://packt.live/2HkTW1m
• The datasets used in this chapter can be downloaded
from https://packt.live/3bzApYN
28/04/2025 A Deep Dive into Matplotlib 36
Exercise 3.01: Creating a Simple Visualization (Correct
program)
import numpy as np
import matplotlib.pyplot as plt
# Set up matplotlib to work interactively in a Jupyter notebook
%matplotlib inline
# Create a new figure with specified DPI
plt.figure(dpi=200)
# Plotting data
plt.plot([1, 2, 4, 5], [1, 3, 4, 3], '-o')
# Save the current plot as Exercise3.02.png with tight bounding box
plt.savefig('Exercise3.02.png', bbox_inches='tight')
# Display the plot interactively (if needed)
plt.show()
28/04/2025 A Deep Dive into Matplotlib 37
OUTPUT ON SCREEN AS WELL AS 'Exercise3.02.png’ FILE
28/04/2025 A Deep Dive into Matplotlib 38
Exercise 3.01: Creating a Simple Visualization
(Avoid writing the below program)
import numpy as np
import matplotlib.pyplot as plt
# Set up matplotlib to work interactively in a Jupyter notebook
%matplotlib inline
# Create a new figure with specified DPI
plt.figure(dpi=200)
# Plotting data
plt.plot([1, 2, 4, 5], [1, 3, 4, 3], '-o')
# Display the plot interactively
plt.show()
# Save the current plot as Exercise3.02.png with tight bounding box
plt.savefig('Exercise3.02.png', bbox_inches='tight')
28/04/2025 A Deep Dive into Matplotlib 39
Basic Text and Legend Functions
• Most of the text-related functions in
matplotlib return an object of the class Text.
• This Text object contains all the properties
and methods for manipulating the text, such
as changing its position, font, size, color, etc.
28/04/2025 A Deep Dive into Matplotlib 40
Labels
• Matplotlib provides a few label functions that we can use
for setting labels to the x- and y-axes.
• The plt.xlabel() and plt.ylabel() functions are used to set
the label for the current axes.
• The set_xlabel() and set_ylabel() functions are used to set
the label for specified axes.
Example:
ax.set_xlabel('X Label’)
ax.set_ylabel('Y
28/04/2025 Label') A Deep Dive into Matplotlib 41
Labels
Single Plot: plt.xlabel() and Multiple Subplots: ax.set_xlabel()
plt.ylabel() and ax.set_ylabel()
• Using plt.xlabel() and • Using ax.set_xlabel() and
ax.set_ylabel() allows setting
plt.ylabel() sets the labels
labels for specific axes (ax1
for the current active axes, and ax2).
which is straightforward when • This is essential when
working with multiple
dealing with a single plot.
subplots to ensure each
subplot has the correct labels.
28/04/2025 A Deep Dive into Matplotlib 42
Important Note:
• You should (always) add labels to make
a visualization more self-explanatory.
28/04/2025 A Deep Dive into Matplotlib 43
Titles
• A title describes a particular chart/graph.
• The titles are placed above the axes in the center, left edge,
or right edge.
• There are two options for titles – you can either set the
Figure title or the title of an Axes.
• The suptitle() function sets the title for the current and
specified Figure.
• The title() function helps in setting the title for the current
and specified axes.
28/04/2025 A Deep Dive into Matplotlib 44
Example:
fig = plt.figure()
fig.suptitle('Suptitle', fontsize=10, fontweight='bold’)
• This creates a bold Figure title with a text
subtitle and a font size of 10
plt.title('Title', fontsize=16)
• The plt.title function will add a title to the Figure
with text as Title and font size of 16 in this case.
28/04/2025 A Deep Dive into Matplotlib 45
Text
• There are two options for text – you can either add text to a
Figure or text to an Axes.
• The figtext(x, y, text) and text(x, y, text) functions add text
at locations x or y for a Figure.
Example:
• ax.text(4, 6, 'Text in Data Coords', bbox={'facecolor': 'yellow',
'alpha':0.5, 'pad':10})
• This creates a yellow text box with the text Text in Data
Coords.
28/04/2025 A Deep Dive into Matplotlib 46
Annotations
• Annotations are used to annotate some features
of the plot.
• In annotations, there are two locations to
consider:
• The annotated location, xy, and the location of the
annotation, text xytext.
• It is useful to specify the parameter arrowprops, which
results in an arrow pointing to the annotated
28/04/2025
location. A Deep Dive into Matplotlib 47
Example:
ax.annotate('Example of Annotate', xy=(4,2),
xytext=(8,4), arrowprops=dict(facecolor='green',
shrink=0.05))
• This creates a green arrow pointing to the data coordinates (4,
2) with the text Example of Annotate at data coordinates (8, 4):
28/04/2025 A Deep Dive into Matplotlib 48
28/04/2025 A Deep Dive into Matplotlib 49
Legends
• Legend describes the content of the plot.
• To add a legend to your Axes, we have to specify the label
parameter at the time of plot creation.
• Calling plt.legend() for the current Axes or Axes.legend()
for a specific Axes will add the legend.
• The loc parameter specifies the location of the legend.
Example:
plt.plot([1, 2, 3], label='Label 1’)
plt.plot([2, 4, 3], label='Label 2’)
plt.legend(loc='best')
28/04/2025 A Deep Dive into Matplotlib 50
Basic Plots:
• Bar Chart
• Pie Chart
• Stacked Bar Chart
• Stacked Area Chart
• Histogram
• Box Plot
• Scatter Plot
• Bubble Plot
28/04/2025 A Deep Dive into Matplotlib 51
Bar Chart
• The plt.bar(x, height, [width]) creates a vertical bar
plot.
• For horizontal bars, use the plt.barh() function.
Important parameters:
• x: Specifies the x coordinates of the bars
• height: Specifies the height of the bars
• width (optional): Specifies the width of all bars; the
default is 0.8
28/04/2025 A Deep Dive into Matplotlib 52
Output:
28/04/2025 A Deep Dive into Matplotlib 53
Syntax:
plt.bar(['A', 'B', 'C', 'D'], [20, 25, 40, 10])
Full code:
import matplotlib.pyplot as plt # Data for the bar chart
categories = ['A', 'B', 'C', 'D’]
values = [20, 25, 40, 10] # Create the bar chart
plt.bar(categories, values) # Add labels and title
plt.xlabel('Categories’)
plt.ylabel('Values’)
plt.title('Bar Chart Example’) # Display the
plotplt.show()
28/04/2025 A Deep Dive into Matplotlib 54
Bar charts with subcategories
How this is possible?
28/04/2025 A Deep Dive into Matplotlib 55
Bar charts with subcategories
• Multiple Bars: To display subcategories within each
main category, you need to use the plt.bar() function
multiple times.
• Each call to plt.bar() will add a new set of bars to the chart.
• Shifted x-coordinates: You have to slightly shift the x-
coordinates for each set of bars so that they don't
overlap. This creates a side-by-side bar chart for the
subcategories.
28/04/2025 A Deep Dive into Matplotlib 56
Bar charts with subcategories
• NumPy's arange(): This function generates evenly
spaced values, which helps in positioning the bars
correctly.
• Current Axes: The plt.gca() function retrieves the
current axes of the plot, which allows you to make
modifications, such as setting labels.
• Custom Labels: The set_xticklabels() function allows
you to customize the labels on the x-axis to match the
categories and subcategories.
28/04/2025 A Deep Dive into Matplotlib 57
Activity 3.02: Creating a Bar Plot for
Movie Comparison
Assignment – page 139
28/04/2025 A Deep Dive into Matplotlib 58
Pie Chart
• The plt.pie(x, [explode], [labels], [autopct])
function creates a pie chart.
Important parameters:
• x: Specifies the slice sizes.
• explode (optional): Specifies the fraction of the
radius offset for each slice. The explode-array must
have the same length as the x-array.
• labels (optional): Specifies the labels for each slice.
• autopct (optional): Shows percentages inside the
slices according to the specified format string.
Example: '%1.1f%%'.
28/04/2025 A Deep Dive into Matplotlib 59
Example:
plt.pie([0.4, 0.3, 0.2, 0.1], explode=(0.1, 0, 0, 0),
labels=['A', 'B', 'C', 'D'])
28/04/2025 A Deep Dive into Matplotlib 60
Code:
import matplotlib.pyplot as plt # Data for the pie chart
sizes = [0.4, 0.3, 0.2, 0.1] # Sizes of each pie slice
explode = (0.1, 0, 0, 0) # Explode the 1st slice (A)
# Labels for each pie
slicelabels = ['A', 'B', 'C', 'D']# Create the pie Chart
plt.pie(sizes, explode=explode, labels=labels,autopct='%1.1f%%', shadow=True,
startangle=140)
# autopct='%1.1f%%'-This formats the percentage displayed in each slice.
# explode: A tuple specifying how much each slice is separated from the center. Here,
(0.1, 0, 0, 0) means only the first slice ('A') is exploded.
# shadow=True - Adds a shadow to the pie chart.
# startangle=140: Rotates the start of the pie chart by 140 degrees counterclockwise.
# Add a title
plt.title('Pie Chart Example’)
# Display the plot
plt.show()
28/04/2025 A Deep Dive into Matplotlib 61
Output:
28/04/2025 A Deep Dive into Matplotlib 62
Exercise 3.02:
• Creating a Pie Chart for Water Usage –
Page 141
28/04/2025 A Deep Dive into Matplotlib 63
Stacked Bar Chart
• A stacked bar chart uses the same plt.bar function as bar charts.
• For each stacked bar, the plt.bar function must be called, and
the bottom parameter must be specified, starting with the second
stacked bar.
Example:
plt.bar(x, bars1)
plt.bar(x, bars2, bottom=bars1)
plt.bar(x, bars3, bottom=np.add(bars1, bars2))
28/04/2025 A Deep Dive into Matplotlib 64
The result of the preceding code is visualized in
the following diagram:
28/04/2025 A Deep Dive into Matplotlib 65
Activity 3.03: Creating a Stacked Bar Plot to
Visualize Restaurant Performance – Page 144
28/04/2025 A Deep Dive into Matplotlib 66
Stacked Area Chart
• plt.stackplot(x, y) creates a stacked area plot.
Important parameters:
• x: Specifies the x-values of the data series.
• y: Specifies the y-values of the data series. For multiple
series, either as a 2D array or any number of 1D arrays, call
the following function: plt.stackplot(x, y1, y2, y3, …).
• labels (optional): Specifies the labels as a list or tuple for
each data series.
28/04/2025 A Deep Dive into Matplotlib 67
Example:
plt.stackplot([1, 2, 3, 4], [2, 4, 5, 8], [1, 5, 4,
2])
The result of the
preceding code is
shown in the
following diagram:
28/04/2025 A Deep Dive into Matplotlib 68
plt.stackplot([1, 2, 3, 4], [2, 4, 5, 8], [1, 5, 4, 2])
Here's a step-by-step explanation of how this works:
Data Points:
• x represents the x-axis values: [1, 2, 3, 4].
• y1 and y2 represent the y-axis values for
two different data series:
• y1 = [2, 4, 5, 8]
• y2 = [1, 5, 4, 2]
28/04/2025 A Deep Dive into Matplotlib 69
Here's a detailed explanation with visual stacking:
Only for Your Understanding
• For x = 1:
• y1 = 2
• y2 = 1 (stacked on top of y1, so the total height at x = 1 is 2 + 1 = 3)
• For x = 2:
• y1 = 4
• y2 = 5 (stacked on top of y1, so the total height at x = 2 is 4 + 5 = 9)
• For x = 3:
• y1 = 5
• y2 = 4 (stacked on top of y1, so the total height at x = 3 is 5 + 4 = 9)
• For x = 4:
• y1 = 8
• y2 = 2 (stacked on top of y1, so the total height at x = 4 is 8 + 2 =
10)
28/04/2025 A Deep Dive into Matplotlib 70
Activity 3.04: Comparing Smartphone Sales
Units Using a Stacked Area Chart – page 147
28/04/2025 A Deep Dive into Matplotlib 71
Histogram
• A histogram visualizes the distribution of a single
numerical variable. Each bar represents the
frequency for a certain interval.
• The plt.hist(x) function creates a histogram.
Important parameters:
• x: Specifies the input values.
• bins: (optional): Specifies the number of bins as an
integer or specifies the bin edges as a list.
• range: (optional): Specifies the lower and upper range
of the bins as a tuple.
• density: (optional): If true, the histogram represents a
probability density.
28/04/2025 A Deep Dive into Matplotlib 72
Example: plt.hist(x, bins=30, density=True)
28/04/2025 A Deep Dive into Matplotlib 73
plt.hist2d(x, y)
• plt.hist2d(x, y) creates a 2D histogram.
• 2D histograms can be used to visualize the frequency of
two-dimensional data.
• The data is plotted on the xy-plane and the frequency is
indicated by the color.
28/04/2025 A Deep Dive into Matplotlib 74
An example of a 2D histogram is shown in
the following diagram.
28/04/2025 A Deep Dive into Matplotlib 75
Box Plot
• The box plot shows multiple statistical measurements.
• The box extends from the lower to the upper quartile
values of the data, thereby allowing us to visualize the
interquartile range.
• The plt.boxplot(x) function creates a box plot.
28/04/2025 A Deep Dive into Matplotlib 76
Important parameters:
• x: Specifies the input data. It specifies either a 1D array
for a single box, or a sequence of arrays for multiple boxes.
• notch: (optional) If true, notches will be added to the plot
to indicate the confidence interval around the median.
• labels: (optional) Specifies the labels as a sequence.
• showfliers: (optional) By default, it is true, and outliers
are plotted beyond the caps.
• showmeans: (optional) If true, arithmetic means are
shown.
28/04/2025 A Deep Dive into Matplotlib 77
Example:
plt.boxplot([x1, x2], labels=['A', 'B'])
28/04/2025 A Deep Dive into Matplotlib 78
Activity 3.05: Using a Histogram and a Box
Plot to Visualize Intelligence Quotient – Page
151
28/04/2025 A Deep Dive into Matplotlib 79
Scatter Plot
• Scatter plots show data points for two numerical
variables, displaying a variable on both axes.
• plt.scatter(x, y) creates a scatter plot of y versus x,
with optionally varying marker size and/or color.
28/04/2025 A Deep Dive into Matplotlib 80
Important parameters:
• x, y: Specifies the data positions.
• s: (optional) Specifies the marker size in points
squared.
• c: (optional) Specifies the marker color. If a
sequence of numbers is specified, the numbers
will be mapped to the colors of the color map.
28/04/2025 A Deep Dive into Matplotlib 81
Example:
plt.scatter(x, y)
28/04/2025 A Deep Dive into Matplotlib 82
Exercise 3.03: Using a Scatter Plot to
Visualize Correlation between Various
Animals – Page 156
28/04/2025 A Deep Dive into Matplotlib 83
Bubble Plot
• The plt.scatter function is used to create a bubble plot.
• To visualize a third or fourth variable, the parameters s
(scale) and c (color) can be used.
plt.scatter(x, y, s=z*500, c=c, alpha=0.5)
plt.colorbar()
• The colorbar function adds a colorbar to the plot, which
indicates the value of the color.
28/04/2025 A Deep Dive into Matplotlib 84
28/04/2025 A Deep Dive into Matplotlib 85
Layouts
• “Layouts" refer to the arrangement and organization
of multiple Axes (plots) within a Figure.
Different methods can be employed to achieve specific
layouts:
• Subplots
• Tight Layout
• GridSpec
28/04/2025 A Deep Dive into Matplotlib 86
Subplots:
• This method involves dividing a single
Figure into a grid of smaller Axes.
• Each subplot can display different datasets
or variations of the same data, arranged in
rows and columns.
28/04/2025 A Deep Dive into Matplotlib 87
Explore the following options to create
subplots:
• The plt.subplots(, ncols) function creates a Figure and a
set of subplots.
• nrows, ncols define the number of rows and columns of
the subplots, respectively.
• The plt.subplot(nrows, ncols, index) function or,
equivalently, plt. subplot(pos) adds a subplot to the
current Figure. The index starts at 1. The plt.subplot(2,
2, 1) function is equivalent to plt.subplot(221).
28/04/2025 A Deep Dive into Matplotlib 88
Explore the following options to
create subplots:
• The Figure.subplots(nrows, ncols) function adds a
set of subplots to the specified Figure.
• The Figure.add_subplot(nrows, ncols, index)
function or, equivalently, Figure.add_subplot(pos),
adds a subplot to the specified Figure.
28/04/2025 A Deep Dive into Matplotlib 89
Radar Charts
• Radar charts, also known as spider or web charts,
visualize multiple variables, with each variable plotted
on its own axis, resulting in a polygon.
• All axes are arranged radially, starting at the center
with equal distance between each other, and have the
same scale.
28/04/2025 A Deep Dive into Matplotlib 90
Exercise 3.04: Working on Radar
Charts
1. Import the necessary modules and enable
plotting within a Jupyter Notebook:
# Import settings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
28/04/2025 A Deep Dive into Matplotlib 91
2. The following dataset contains ratings of
five different attributes for four employees:
# Sample data
# Attributes: Efficiency, Quality, Commitment, Responsible
Conduct, Cooperation
data = pd.DataFrame({
'Employee': ['Alex', 'Alice', 'Chris', 'Jennifer’],
'Efficiency': [5, 4, 4, 3,],
'Quality': [5, 5, 3, 3],
'Commitment': [5, 4, 4, 4],
'Responsible Conduct': [4, 4, 4, 3],
'Cooperation': [4, 3, 4, 5] })
28/04/2025 A Deep Dive into Matplotlib 92
3. Create angle values and close the
plot:
attributes = list(data.columns[1:])
values = list(data.values[:, 1:])
employees = list(data.values[:, 0])
angles = [n / float(len(attributes)) * 2 * np.pi for n in
range(len(attributes))] # Close the plot
angles += angles[:1]
values = np.asarray(values)
values = np.concatenate([values, values[:, 0:1]], axis=1)
28/04/2025 A Deep Dive into Matplotlib 93
4. Create subplots with the polar projection. Set
a tight layout so that nothing overlaps:
# Create figure
plt.figure(figsize=(8, 8), dpi=150) # Create subplots
for i in range(4):
ax = plt.subplot(2, 2, i + 1, polar=True)
ax.plot(angles, values[i])
ax.set_yticks([1, 2, 3, 4, 5])
ax.set_xticks(angles)
ax.set_xticklabels(attributes)
ax.set_title(employees[i], fontsize=14, color='r’)
# Set tight layout
plt.tight_layout()
# Show plot
28/04/2025 A Deep Dive into Matplotlib 94
plt.show()
28/04/2025 A Deep Dive into Matplotlib 95
GridSpec
The matplotlib.gridspec.GridSpec(nrows, ncols) function specifies
the geometry of the grid in which a subplot will be placed.
• Define a GridSpec Layout: You can create a grid with
specified rows and columns using GridSpec.
• Access GridSpec Elements: Access elements of the grid like
you would with a NumPy array.
• Create Subplots: Use single or multiple grid elements for each
subplot.
28/04/2025 A Deep Dive into Matplotlib 96
Images
• If you want to include images in your
visualizations or work with image data,
Matplotlib offers several functions for you.
• In this section, we will show you how to load,
save, and plot images with Matplotlib.
28/04/2025 A Deep Dive into Matplotlib 97
Basic Image Operations
The following are the basic operations for designing an
image.
• Loading Images
• Saving Images
• Plotting a Single Image
• Plotting Multiple Images in a Grid
28/04/2025 A Deep Dive into Matplotlib 98
Loading Images
• If you encounter image formats that are not supported
by Matplotlib, we recommend using the Pillow
library to load the image.
• In Matplotlib, loading images is part of the image
submodule.
• We use the alias mpimg for the submodule, as follows:
import matplotlib.image as mpimg
28/04/2025 A Deep Dive into Matplotlib 99
Loading Images
• The mpimg.imread(fname) reads an image and
returns it as a numpy.array object.
• For grayscale images, the returned array has a shape
(height, width), for RGB images (height, width, 3),
and for RGBA images (height, width, 4).
• The array values range from 0 to 255.
28/04/2025 A Deep Dive into Matplotlib 100
Loading Images
• We can also load the image in the following manner:
img_filenames = os.listdir('../../Datasets/images’)
imgs = [mpimg.imread(os.path.join('../../Datasets/images',
img_filename))
for img_filename in img_filenames]
28/04/2025 A Deep Dive into Matplotlib 101
Loading Images
• The os.listdir() method in Python is used to get
the list of all files and directories in the
specified directory.
• The os.path.join() function is used to join one
or more path components intelligently
28/04/2025 A Deep Dive into Matplotlib 102
Saving Images - mpimg.imsave
Purpose: mpimg.imsave(fname, array) saves a NumPy
array as an image file.
File Format: The format is inferred from the filename
extension if not specified.
Color Limits: Optional vmin and vmax parameters set the
color limits manually.
Colormap: For grayscale images, the default colormap is
'viridis'. Use cmap='gray' to display the image in grayscale.
28/04/2025 A Deep Dive into Matplotlib 103
Plotting a Single Image with plt.imshow
Displaying an Image:
• Use plt.imshow(img) to display an image.
• This function returns an AxesImage object.
Grayscale Images:
• For images with shape (height, width), the default colormap is
'viridis'.
• To visualize a grayscale image correctly, set the colormap to
'gray' using plt.imshow(img, cmap='gray').
28/04/2025 A Deep Dive into Matplotlib 104
• The "viridis" colormap is a color scheme
used in data visualization, particularly in
matplotlib for creating perceptually uniform
color maps.
28/04/2025 A Deep Dive into Matplotlib 105
Plotting Multiple Images in a
Grid
• To plot multiple images in a grid, we can simply
use plt.subplots and plot an image per Axes:
fig, axes = plt.subplots(1, 2)
for i in range(2):
axes[i].imshow(imgs[i])
28/04/2025 A Deep Dive into Matplotlib 106
Activity 3.07: Plotting Multiple
Images in a Grid – page 175
The following are the steps to perform:
1.Import the necessary modules and enable plotting
within a Jupyter Notebook.
2.Load all four images from the Datasets subfolder.
3.Visualize the images in a 2x2 grid. Remove the axes
and give each image a label.
28/04/2025 A Deep Dive into Matplotlib 107
Summary
• In this chapter, we provided a detailed
introduction to Matplotlib, one of the most
popular visualization libraries for Python.
28/04/2025 A Deep Dive into Matplotlib 108