Chapter-5- Matplotlib-Part-1
Chapter-5- Matplotlib-Part-1
Part-I
1
4 Matplotlib
• What is Matplotlib?
• Matplotlib is a low level graph plotting library in
python that serves as a visualization utility.
• Matplotlib was created by John D. Hunter.
• Matplotlib is open source and we can use it
freely.
• Matplotlib is mostly written in python, a few
segments are written in C, Objective-C and
Javascript for Platform compatibility.
2
4 Matplotlib
• Installation of Matplotlib
• If you have Pythin or PIP already installed on a
system, then installation of Matplotlib is very
easy.
• Install it using this command:
• > Pip Install matplotlib
3
4 Matplotlib
• Import Matplotlib
• Once Matplotlib is installed, import it in your
applications by adding the imprt matplotlib
statement:
• Checking Matplotlib Version
• The version string is stored under
• > Print( matplotlib.__version__ )
4
4 Matplotlib
• Matplotlib Pyplot
• Most of the Matplotlib utilities lies under the
pyplot submodule, and are usually imported
under the plt alias:
• import matplotlib.pyplot as plt
• Now the Pyplot package can be referred to as
plt
5
4 Matplotlib
• Example
• import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
6
4 Matplotlib
• Plotting x and y points
• The plot() function is used to draw points
(markers) in a diagram.
• By default, the plot() function draws a line
from point to point.
• The function takes parameters for specifying
points in the diagram.
7
4 Matplotlib
• Plotting x and y points
• Parameter 1 is an array containing the points
on the x-axis.
• Parameter 2 is an array containing the points
on the y-axis.
• If we need to plot a line from (1, 3) to (8, 10),
we have to pass two arrays [1, 8] and [3, 10] to
the plot function.
8
4 Matplotlib
• Example
• Draw a line in a diagram from position (1, 3) to
position (8, 10):
• import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
9
4 Matplotlib
• Example
10
4 Matplotlib
• Plotting Without Line
• To plot only the markers, you can use shortcut
string notation parameter 'o', which means
'rings'.
• Example
• Draw two points in the diagram, one at
position (1, 3) and one in position (8, 10):
11
4 Matplotlib
• import matplotlib.pyplot as plt
import numpy as np
12
4 Matplotlib
13
4 Matplotlib
• Multiple Points
• You can plot as many points as you like, just
make sure you have the same number of
points in both axis.
14
4 Matplotlib
• Example
• Draw a line in a diagram from position (1, 3) to (2,
8) then to (6, 1) and finally to position (8, 10):
• import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
15
5 Matplotlib
16
5 Matplotlib
17
5 Matplotlib
• Marker Reference
18
5 Matplotlib
• Line Reference
• > plt.plot(ypoints, linestyle = 'dotted')
19
5 Matplotlib
• Line Reference
• > plt.plot(ypoints, linestyle = 'dotted')
• import matplotlib.pyplot as plt
import numpy as np
22
5 Matplotlib
• Color Reference
• > plt.plot(ypoints, 'o:r')
23
5 Matplotlib
• Marker Size
• > plt.plot(ypoints, marker = 'o', ms = 20)
24
5 Matplotlib
• Marker Color
• > import matplotlib.pyplot as plt
import numpy as np
25
5 Matplotlib
• Marker Color
26
5 Matplotlib
• Matplotlib Labels and Title
• Pyplot, use the xlabel (), ylabel() functions to
set a label for the x- and y-axis.
• you can use the title()
27
5 Matplotlib
• Matplotlib Labels and Title
• import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()
28
5 Matplotlib
• Set Font Properties for Title and Labels
• import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
font1 = {'family':'serif','color':'blue','size':20}
font2 = {'family':'serif','color':'darkred','size':15}
plt.plot(x, y)
plt.show()
29
5 Matplotlib
• Matplotlib Subplot
• Subplot() function you can draw multiple plots
in one figure:
• The layout is organized in rows and columns,
which are represented by
the first and second argument.
• The third argument represents the index of
the current plot.
30
5 Matplotlib
• Matplotlib Subplot
• import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
31
5 Matplotlib
• Matplotlib Subplot
32
5 Matplotlib
• Matplotlib Subplot
• plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot
is the first plot.
• plt.subplot(1, 2, 2)
#the figure has 1 row, 2 columns, and this plot
is the second plot.
33
5 Matplotlib
• Matplotlib Subplot
• import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
34
5 Matplotlib
• Matplotlib Subplot
35
5 Matplotlib
• Scatter Plot
• scatter(x, y) function is used to draw a scatter
plot.
• scatter(x, y) function plots one dot for each
observation.
• It needs two arrays of the same length,
• one for the values of the x-axis, and one for
values on the y-axis:
36
5 Matplotlib
• Scatter Plot
• import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y=
np.array([99,86,87,88,111,86,103,87,94,78,77,
85,86])
plt.scatter(x, y)
plt.show()
37
5 Matplotlib
• Scatter Plot
38
5 Matplotlib
• Scatter Plot
• The observation in the example above is the
result of 13 cars passing by.
• The X-axis shows how old the car is.
• The Y-axis shows the speed of the car when it
passes.
• Are there any relationships between the
observations?
• It seems that the newer the car, the faster it
drives, but that could be a coincidence, after all
we only registered 13 cars.
39
5 Matplotlib
• Compare Plots
• In the example above, there seems to be a
relationship between speed and age, but what
if we plot the observations from another day
as well? Will the scatter plot tell us something
else?
40
5 Matplotlib
• Compare Plots
• import matplotlib.pyplot as plt
import numpy as np
#day one, the age and speed of 13 cars:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
#day two, the age and speed of 15 cars:
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y)
plt.show()
41
5 Matplotlib
• Compare Plots
42
5 Matplotlib
• Compare Plots
43
5 Matplotlib
• Color
• plt.scatter(x, y, color = 'hotpink‘)
• plt.scatter(x, y, color = '#88c999‘)
• You can adjust the transparency of the dots
with the alpha
• You can specify the colormap with the
keyword argument cmap with the value of the
colormap, in this case viridis which is one of
the built-in colormaps available in Matplotlib.
44
5 Matplotlib
• Combine Color Size and Alpha
45
5 Matplotlib
• Matplotlib Histograms
• A histogram is a graph
showing frequency distributions.
• It is a graph showing the number of
observations within each given interval.
• Example: Say you ask for the height of 250
people, you might end up with a histogram
like this:
46
5 Matplotlib
• Matplotlib Histograms
47
5 Matplotlib
• Matplotlib Histograms
• You can read from the histogram that there are
approximately:
• 2 people from 140 to 145cm
5 people from 145 to 150cm
15 people from 151 to 156cm
31 people from 157 to 162cm
46 people from 163 to 168cm
53 people from 168 to 173cm
45 people from 173 to 178cm
28 people from 179 to 184cm
21 people from 185 to 190cm
4 people from 190 to 195cm
48
5 Matplotlib
• Matplotlib Histograms
• The hist() function will use an array of
numbers to create a histogram, the array is
sent into the function as an argument.
• For simplicity we use NumPy to randomly
generate an array with 250 values, where the
values will concentrate around 170, and the
standard deviation is 10
49
5 Matplotlib
• Matplotlib Histograms
• A Normal Data Distribution by NumPy:
• import numpy as np
print(x)
print(x)
52
5 Matplotlib
• Matplotlib Histograms
• The hist() function will read the array and produce a
histogram:
• Example
• A simple histogram:
• import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(170, 10, 250)
plt.hist(x)
plt.show()
• Reuslt: Displya A Histogram
53
5 Matplotlib
• A 3D plotting is a way to represent three
dimensional data in a graphical format.
• It allows you to visualize the information in
three spatial dimensions, represented as X, Y,
and Z coordinates.
• In 3D plots, data points are not only located
on a flat plane but also have depth, creating a
more detailed representation of the dataset.
54
5 Matplotlib
55
5 Matplotlib
• In Matplotlib, we can create a three-
dimensional plot using the
mpl_toolkits.mplot3d module.
• This module provides tools to create three-
dimensional visualizations, including scatter
plots, line plots, surface plots, and more.
• These plots provide a way to represent and
explore data points or mathematical functions
in three-dimensional space.
56
5 Matplotlib
• The mpl_toolkits.mplot3d Module
• The "mpl_toolkits.mplot3d" module in
Matplotlib enhances the library's capabilities
for three-dimensional plotting. It introduces
the "Axes3D" class, which enables the
creation of 3D subplots.
57
5 Matplotlib
• Example
• In the following example, we are generating
random 3D data points using NumPy and
creating a 3D scatter plot with blue markers
58
5 Matplotlib
• Example
• import matplotlib.pyplot as plt
• from mpl_toolkits.mplot3d import Axes3D
• import numpy as np
• # Generating random 3D data
• np.random.seed(42)
• n_points = 100
• x = np.random.rand(n_points)
• y = np.random.rand(n_points)
• z = np.random.rand(n_points)
• # Creating a 3D scatter plot
• fig = plt.figure()
• ax = fig.add_subplot(111, projection='3d')
• ax.scatter(x, y, z, c='blue', marker='o')
• ax.set_xlabel('X Axis')
• ax.set_ylabel('Y Axis')
• ax.set_zlabel('Z Axis')
• ax.set_title('3D Scatter Plot')
• plt.show()
59
5 Matplotlib
• Output
60
5 Matplotlib
• 3D Surface Plot
• A 3D surface plot in Matplotlib is a visual
representation of a mathematical function or a
dataset in three-dimensional space.
• Instead of using flat lines or markers, this plot
uses a continuous surface to show how a variable
changes across two input dimensions (X and Y)
and is dependent on a third dimension (Z).
• We can create this type of plot using the
plot_surface() function.
61
5 Matplotlib
• Example
62
5 Matplotlib
• Output
63