0% found this document useful (0 votes)
5 views29 pages

14 Matplotlib Full

The document provides an introduction to Matplotlib, a library for creating visualizations in Python, highlighting its key features such as static, animated, and interactive visualizations. It covers essential components of a Matplotlib figure, the use of the Pyplot module, and various plotting techniques including line plots, scatter plots, and bar charts. Additionally, it discusses statistical distributions and methods for visualizing data distributions, such as histograms and box plots.

Uploaded by

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

14 Matplotlib Full

The document provides an introduction to Matplotlib, a library for creating visualizations in Python, highlighting its key features such as static, animated, and interactive visualizations. It covers essential components of a Matplotlib figure, the use of the Pyplot module, and various plotting techniques including line plots, scatter plots, and bar charts. Additionally, it discusses statistical distributions and methods for visualizing data distributions, such as histograms and box plots.

Uploaded by

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

COMP 1023 Introduction to Python Programming

Matplotlib
Dr. Cecia Chan, Prof. SC Cheung, Dr. Alex Lam, Dr. Desmond Tsoi
Department of Computer Science & Engineering
The Hong Kong University of Science and Technology, Hong Kong SAR, China
Introduction
Matplotlib is a comprehensive library for creating static, animated, and interactive
visualizations in Python. It is widely used for data visualization across various fields,
including data science, engineering, and research.
Key Features:
Static Visualizations: Generate high-quality static plots, such as line graphs, bar charts, and
scatter plots.
Animated Visualizations: Create dynamic visualizations that illustrate changes over time or
other variables.
Interactive Visualizations: Build interactive plots that allow users to explore data through
zooming, panning, and real-time updates.

In this course, we will use version 3.10.3, and we will focus on static visualizations.

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 2 / 29


Why Matplotlib?

Wide Adoption: Matplotlib is one of the


most widely used libraries for data
visualization in the Python ecosystem.
Customization: It offers extensive options
for customizing visual elements, including
colors, labels, and styles.
Integration: Matplotlib easily integrates
with other libraries such as NumPy,
Pandas, and Seaborn (a statistical data
visualization library) for enhanced data
analysis and visualization.

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 3 / 29


Key Components of a Matplotlib Figure
A Matplotlib figure is composed of several key
elements:
Figure: This serves as the primary container for all
visual elements, functioning as the canvas for the
entire plot.
Axes: These are the specific regions within the figure
where data visualization occurs; a single figure can
incorporate multiple axes.
Axis: The axes define the horizontal (x-axis) and
vertical (y-axis) dimensions, including their limits, tick
marks, and labels essential for data interpretation.
Lines and Markers: Lines are utilized to connect data
points, illustrating trends, while markers highlight
individual data points, particularly in scatter plots.
Title and Labels: The title of the plot provides
overarching context, while axis labels clarify the data
being represented on each respective axis.

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 4 / 29


Introduction to Matplotlib Pyplot
Pyplot is a module of Matplotlib designed for creating static, interactive, and animated
visualizations in Python.
To effectively utilize Pyplot, follow these steps:
1. Import the Module: Begin by importing the module using import [Link] as
plt.
2. Prepare Data: Organize your data into lists or arrays for plotting.
3. Create the Plot: Generate the plot by calling [Link]() with your data.
4. Enhance the Visualization: Customize the plot by adding titles, axis labels, and other
features using [Link](), [Link](), and [Link]().
5. Display the Plot: Finally, render the plot on the screen with [Link]().

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 5 / 29


Figures and Axes
The Figure object contains all the plots.
You can have multiple plots inside the Figure object.
You can also save the figure as an image (e.g., JPEG, PNG, etc.)
You can have one or more Axes inside the figure object, and each Axes object corresponds
to a plot.
Each Axes has an x axis and an y axis that represent the data that you want to plot.

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 6 / 29


Creating a New Figure with a Plot

To create a Figure, use the subplots() function from the Matplotlib library.
The subplots() function returns a new Figure and its Axes object.

# Filename: single_plot_create.py
import [Link] as plt

# The width and height are 5 and 3 inches


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

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 7 / 29


Creating a New Figure with Multiple Plots
To create multiple plots, specify the number of rows and columns in the parameters.
The first two parameters of [Link]() define the number of plots as rows and
columns. It returns the Figure object and the Axes as a NumPy array, allowing you to
access each chart using NumPy indexing methods.

# Filename: multiple_plots_create.py
import [Link] as plt

# Multiple plots with 2 rows and 3 columns


fig, ax = [Link](2, 3, figsize=(5, 3))
[Link]()

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 8 / 29


Part I

Pairwise Data Visualization

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 9 / 29


Pairwise Data Visualization
Visualization techniques for pairwise data include plots of (x,y) coordinates, tabular data
(var0 , . . ., varn ), and functional relationships of the form f (x) = y .
plot(x, y): Creates a line plot connecting the data points.
scatter(x, y): Generates a scatter plot to display individual data points.
bar(x, height): Produces a bar chart representing categorical data.
stem(x, y)†: Generates a stem plot for discrete data representation.
fill between(x, y1, y2)†: Fills the area between two curves.
stackplot(x, y)†: Creates a stacked area plot to visualize cumulative data.
stairs(values)†: Generates a step plot for visualizing changes in data.
†: Self-explore

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 10 / 29


Drawing a Line Curve
To draw a line curve, use the plot() method of the Axes object ([Link]). This method takes two lists
or NumPy arrays as input: the first list contains the x-coordinates, and the second contains the
y-coordinates of the points in the line.
You can customize the appearance of the plot by specifying the marker type using the marker attribute,
and by adding a legend for the data points with the label attribute.
You can specify the labels (i.e., names) of the x and y axes using set xlabel() and set ylabel(),
respectively, and add a title to the plot, use the set title() method.

import [Link] as plt # Filename: line_curve_draw.py

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


# Line through (x,y) -> (0,0), (2,4), (4,16), (6,36), (8, 64)
[Link]([0, 2, 4, 6, 8], [0, 4, 16, 36, 64],
marker='o', label="Data Points 1")
# Another line through (x,y) -> (0,3), (4,7), (8,50)
[Link]([0, 4, 8], [3, 7, 50],
marker='x', label="Data Points 2")

ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")
ax.set_title("Sample Plot of X vs Y")
[Link]()
{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 11 / 29
Drawing a Line Plot in Multiple Rows and Multiple Columns
Each subplot can represent different datasets.
x and y axis labels can be added using set xlabel() and set ylabel().
Titles for each subplot are set using the set title() method.
import [Link] as plt # Filename: line_plot_draw_multiples.py

fig, ax = [Link](2, 2, figsize=(10, 6))

ax[0, 0].plot([0, 1, 2], [2, 4, 6]) # First subplot


ax[0, 0].set_xlabel("X Values")
ax[0, 0].set_ylabel("Y Values")
ax[0, 0].set_title("Plot 1: Line through (0,2), (1,4), (2,6)")

ax[0, 1].plot([0, 1, 2], [3, 6, 9]) # Second subplot


ax[0, 1].set_xlabel("X Values")
ax[0, 1].set_ylabel("Y Values")
ax[0, 1].set_title("Plot 2: Line through (0,3), (1,6), (2,9)")

ax[1, 0].plot([0, 1, 2], [1, 2, 3]) # Third subplot


ax[1, 0].set_xlabel("X Values")
ax[1, 0].set_ylabel("Y Values")
ax[1, 0].set_title("Plot 3: Line through (0,1), (1,2), (2,3)")

ax[1, 1].plot([0, 1, 2], [4, 8, 12]) # Fourth subplot


ax[1, 1].set_xlabel("X Values")
ax[1, 1].set_ylabel("Y Values")
ax[1, 1].set_title("Plot 4: Line through (0,4), (1,8), (2,12)")

plt.tight_layout()
[Link]()
{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 12 / 29
Drawing a Sequence of Points/Segments
The [Link]() function also allows you to display a sequence of points or segments
that share the same properties (e.g., size, color, width).
# Filename: sequence_points_segments_draw.py
import [Link] as plt
import numpy as np

x = [Link](0, 5, 20)
y = [Link](x)

fig, ax = [Link](figsize=(3, 2))

[Link](x, y, c="blue", linestyle="",


marker='*', label="Curve 1")
[Link](x, 2*y, c="green",
linestyle="--", label="Curve 2")

# Specify the legend position with relative position


[Link](loc=(1.1, 0.5))
[Link]()

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 13 / 29


Scatter Plot: Displaying a Set of Points With Colormap
To show a set of points and assign them custom properties (e.g., color, size), use the [Link]()
method.
You need to specify the lists of x and y coordinates of all your points as parameters (as NumPy arrays).
You can also specify a colormap using the cmap parameter, and the size of the points using the s
parameter. The size is expressed as the area in square points (dpi).

import numpy as np # Filename: [Link]


import [Link] as plt

x = [Link](20)
y = [Link](20)

# Color as a function of the positions of the points


colors = x + y
# Size as a function of the positions of the points
area = 100 * (x + y)
fig, ax = [Link](figsize=(3, 2))

# Specify the colormap as "spring"


[Link](x, y, c=colors, cmap="spring", s=area)
[Link]()
{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 14 / 29
Bar Chart: Displaying a Sequence of Numbers as Bars
To plot vertical or horizontal bars, use the [Link]() method. You can specify the
position of each bar on the x-axis as a list, and the height of each bar as a corresponding
list (both lists should have the same size).
You can assign text labels to the ticks on the horizontal axis using the tick label
parameter.
# Filename: barchart_single.py
import numpy as np
import [Link] as plt

# Position of the bars on the x-axis


x = [1, 2, 3]
# The height of each bar
height = [10, 2, 8]

labels = ["Sensor 1", "Sensor 2", "Sensor 3"]


fig, ax = [Link](figsize=(3, 2))
[Link](x, height, tick_label=labels)
[Link]()

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 15 / 29


Bar Chart: Displaying Multiples Bars
You can group multiple bars side-by-side.
Position the two bar plots at x + width
2 and x − width
2 .
# Filename: barchart_multiples.py
import numpy as np
import [Link] as plt
heightMin = [10, 2, 8]
heightMax = [8, 6, 5]
x = [Link](3)
width = 0.4
labels = ["Sensor 1", "Sensor 2", "Sensor 3"]

fig, ax = [Link](figsize=(3, 2))


# Blue bars
[Link](x + width / 2, heightMin, width=width, label="Min")
# Orange bars
[Link](x - width / 2, heightMax, width=width, label="Max")

ax.set_xticks(x)
ax.set_xticklabels(labels)
[Link](loc=(1.1, 0.5))
[Link]()
{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 16 / 29
Part II

Statistical Distributions

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 17 / 29


Statistical Distributions

Visualization techniques for depicting the distribution of one or more variables within a
dataset.
Many of these methods also provide calculations of the distributions.
hist(x): Creates a histogram to visualize the frequency distribution of a single variable.
boxplot(X): Generates a box plot to summarize the distribution of data through their
quartiles.
errorbar(x, y, yerr, xerr)†: Displays data points with error bars indicating variability.
violinplot(D) †: Combines a box plot and a density plot to show the distribution of data.
eventplot(D)†: Visualizes events along an axis, useful for time series data.
hist2d(x, y)†: Creates a 2D histogram to display the joint distribution of two variables.
hexbin(x, y, C)†: Generates a hexagonal bin plot for bivariate data visualization.
pie(x)†: Creates a pie chart to represent proportions of categorical data.
ecdf(x)†: Computes and plots the empirical cumulative distribution function.
†: Self-explore

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 18 / 29


Creating a Histogram
The hist(x) function is used to create a histogram, which visualizes the distribution of a
dataset. x is a one-dimensional array or list containing numerical data.
You can customize the number of bins to adjust the granularity of the histogram using
the bins parameter.
Additional options such as color, alpha, and edgecolor can enhance the visual appeal
of the histogram.

# Filename: [Link]
import [Link] as plt
import numpy as np

data = [Link](1000) # Generate random data

[Link](data, bins=30, color='blue',


alpha=0.7, edgecolor='black')
[Link]("Histogram of Random Data")
[Link]("Value")
[Link]("Frequency")
[Link]()

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 19 / 29


Creating a Box Plot
The boxplot(X) function creates a box plot, which visualizes the distribution of a
dataset through its quartiles. X is a one-dimensional array or a two-dimensional array (for
multiple box plots).
Box plots provide a summary of the central tendency, variability, and potential outliers in
the data.
You can customize the appearance of the box plot using parameters such as color,
notch, and vert (to control orientation).
import [Link] as plt # Filename: [Link]
import numpy as np

data = [[Link](0, std, 100) for std in range(1, 4)]

[Link](data, notch=True, patch_artist=True,


boxprops=dict(facecolor='lightblue',
color='blue'), medianprops=dict(color='red'))
[Link]("Box Plot of Random Data")
[Link]("Dataset"); [Link]("Value")
[Link]([1, 2, 3], ['Data 1', 'Data 2', 'Data 3'])
[Link]()
{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 20 / 29
Save a Plot to File
Generated figures can be saved to files in various formats (e.g., JPEG, PNG, PDF, EPS,
etc.).
Use the [Link]() method to save the figure.
# Filename: save_plot.py
import [Link] as plt

fig, ax = [Link](figsize=(3, 2))

[Link]([0, 1, 2], [2, 4, 6])


[Link]([0, 1, 2], [3, 6, 9])

[Link]("[Link]") # or .jpg, .eps, .pdf

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 21 / 29


A Lot More to Explore

Gridded Data 3D and Volumetric Data


imshow(Z)† bar3d(x, y, z, dx, dy, dz)†
pcolormesh(X, Y, Z)† fill between(x1, y1, z1, x2, y2, z2)
contour(X, Y, Z) plot(xs, ys, zs)†
contourf(X, Y, Z)† quiver(X, Y, Z, U, V, W)†
barbs(X, Y, U, V)† scatter(xs, ys, zs)†
quiver(X, Y, U, V)† streamplot(x, y, u, v)†
streamplot(X, Y, U, V)† plot surface(X, Y, Z)†
Irregularly Gridded Data plot trisurf(x, y, z)†
tricontour(x, y, z) voxels([x, y, z], filled)†
tricontourf(x, y, z)† plot wireframe(X, Y, Z)†
tripcolor(x, y, z)†
triplot(x, y)†
†: Self-explore

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 22 / 29


Creating Contour Plots with contour()
The contour() function is used to create contour plots, which represent 3D data in two
dimensions using contour lines. A grid of data points represented by 2D arrays for the x
and y coordinates and a corresponding z value.
You can customize the contour levels using the levels parameter to specify the number
of contour lines or specific z-values. Additional parameters such as cmap allow you to
choose color maps for better visualization.
# Filename: [Link]
import numpy as np
import [Link] as plt

x = [Link](-5, 5, 100); y = [Link](-5, 5, 100)


X, Y = [Link](x, y)
Z = [Link]([Link](X**2 + Y**2))

[Link](X, Y, Z, levels=20, cmap='viridis')


[Link](label='Z Value')
[Link]("Contour Plot of $Z = \sin(\sqrt{X^2 + Y^2})$")
[Link]("X-axis"); [Link]("Y-axis")
[Link]()
{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 23 / 29
Creating Triangular Contour Plots with tricontour()
The tricontour() function is used to create contour plots for irregularly spaced data
defined by triangles. Three 1D arrays representing the x and y coordinates of the points,
and a corresponding z value for each point.
You can specify the contour levels using the levels parameter to control the number of
contour lines or specific z-values. The triangulate parameter allows you to define the
triangulation of the data for better visualization.
# Filename: [Link]
import numpy as np
import [Link] as plt
from [Link] import Triangulation

x = [Link](30); y = [Link](30)
z = [Link](x) + [Link](y)
triang = Triangulation(x, y) # Create triangulation

[Link](triang, z, levels=14, cmap='plasma')


[Link](label='Z Value')
[Link]("Triangular Contour Plot")
[Link]("X-axis"); [Link]("Y-axis")
[Link]()
{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 24 / 29
Using fill between() for Area Filling
The fill between() function is used to fill the area between two horizontal curves,
useful for highlighting regions in a plot. x-coordinates and two sets of y-coordinates are
defined the boundaries of the filled area.
You can customize the appearance of the filled area using parameters like color, alpha
(transparency), and label for legends.
# Filename: area_filling.py
import numpy as np
import [Link] as plt

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


y1 = [Link](x); y2 = [Link](x) + 0.5

plt.fill_between(x, y1, y2, color='skyblue',


alpha=0.5, label='Area between curves')
[Link](x, y1, label='y1 = sin(x)', color='blue')
[Link](x, y2, label='y2 = sin(x) + 0.5', color='orange')
[Link]("Area Filling with fill_between()")
[Link]("X-axis"); [Link]("Y-axis")
[Link]()
[Link]()
{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 25 / 29
Key Terms

Animated Visualizations fill between


Area Filling Gridded Data
Axes Histogram
Axis Interactive Visualizations
Bar Chart Irregularly Gridded Data
Box Plot Matplotlib
Color Map Plot
Contour Plot Pyplot
Data Visualization Scatter Plot
Error Bars Static Visualizations
Figure Triangular Contour Plot

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 26 / 29


Review Questions
Fill in the blanks in each of the following sentences about the Python environment.
1. Matplotlib is a comprehensive library for creating , animated, and
interactive visualizations in Python.
2. The module is designed for creating static, interactive, and animated
visualizations.
3. A serves as the primary container for all visual elements in a plot.
4. The defines the horizontal (x-axis) and vertical (y-axis) dimensions of
a plot.
5. The function is used to create a histogram, which visualizes the
distribution of a dataset.
6. To create a plot, you can use the boxplot() function.

Answer: 1. static plots, 2. Pyplot, 3. figure, 4. axis, 5. hist(), 6. box.

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 27 / 29


Review Questions
Fill in the blanks in each of the following sentences about the Python environment.
7. The scatter() method is used to show a set of on a plot.
8. You can fill the area between two curves using the function.
9. The contour() function is used to create plots that represent 3D
data in two dimensions.
10. To create multiple plots in one figure, use the subplots() function with specified
and .
11. The parameter in the plot() method allows you to customize the
appearance of the plot.
12. You can save a figure to a file using the [Link]() method, which allows saving in
various .

Answer: 7. points, 8. fill between, 9. contour, 10. rows; columns, 11. marker, 12. formats.

{kccecia, sccheung, lamngok, desmond}@[Link] COMP 1023 (Fall 2025) 28 / 29


That’s all!
Any question?

You might also like