0% found this document useful (0 votes)
5 views

CSE488_Lab4_Matplotlib

The document provides an introduction to the Matplotlib library in Python, focusing on its architecture, usage, and functionalities for creating two-dimensional charts. It covers key components such as the scripting layer (pyplot), graph properties, and how to enhance charts with titles, labels, grids, and legends. Additionally, it discusses saving charts and introduces various types of charts that can be created using Matplotlib.

Uploaded by

Fady Kamil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CSE488_Lab4_Matplotlib

The document provides an introduction to the Matplotlib library in Python, focusing on its architecture, usage, and functionalities for creating two-dimensional charts. It covers key components such as the scripting layer (pyplot), graph properties, and how to enhance charts with titles, labels, grids, and legends. Additionally, it discusses saving charts and introduces various types of charts that can be created using Matplotlib.

Uploaded by

Fady Kamil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Mechatronics Engineering and Automation Program

CSE488: Computational Intelligence


Lab #04: Introduction to Matplotlib

Matplotlib
matplotlib is a Python library specializing in the development of two-dimensional charts
(including 3D charts). In recent years, it has been widespread in scientific and engineering
circles (http://matplolib.org).
MATLAB in terms of both graphical view and syntactic form. This approach has proved
successful, as it has been able to exploit the experience of software (MATLAB) that has been
on the market for several years and is now widespread in all professional technical scientific
circles. Not only is matplotlib based on a scheme known and quite familiar to most experts
in the field, but also it also exploits those optimizations that over the years have led to a
deducibility and simplicity in its use, which makes this library also an excellent choice for
those approaching data visualization for the first time, especially those without any
experience with applications such as MATLAB or similar.

Architecture
One of the key tasks that matplotlib must take on is provide a set of functions and tools that
allow representation and manipulation of a Figure (the main object), along with all internal
objects of which it is composed.
The architecture of matplotlib is logically structured into three layers, which are placed at
three different levels. The communication is unidirectional, that is, each layer can
communicate with the underlying layer, while the lower layers cannot communicate with
the top ones.

Scripting Layer
Artist classes and their related functions (the matplotlib API) are particularly suitable to all
developers, especially for those who work on web application servers or develop the GUI.
But for purposes of calculation, and in particular for the analysis and visualization of data,
the scripting layer is best. This layer consists of an interface called pyplot.
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

pyplot

The pyplot module is a collection of command-style functions that allow you to use
matplotlib much like MATLAB. Each pyplot function will operate or make some changes to
the Figure object, for example, the creation of the Figure itself, the creation of a plotting
area, representation of a line, decoration of the plot with a label, etc.
import matplotlib.pyplot as plt
import numpy as np

simple graph
To get familiar with the matplotlib library and in a particular way with Pyplot, you will start
creating a simple chart.
plt.plot([1,2,3,4])
[<matplotlib.lines.Line2D at 0x1348f440e88>]

As you can see, a Line2D object has been generated. The object is a line that represents the
linear trend of the points included in the chart. Now it is all set. You just have to give the
command to show the plot using the show() function.
plt.plot([1,2,3,4])
plt.show()
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

As we are using the IPython Notebook, you may have noticed that after calling the plot()
function the chart is displayed directly without explicitly invoking the show() function.
If you pass only a list of numbers or an array to the plt.plot() function, matplotlib assumes it
is the sequence of y values of the chart, and it associates them to the natural sequence of
values x: 0,1,2,3, ... . Generally a plot represents value pairs (x, y), so if you want to define a
chart correctly, you must define two arrays, the first containing the values on the x-axis and
the second containing the values on the y-axis. Moreover, the plot() function can accept a
third argument, which describes the specifics of how you want the point to be represented
on the chart.
plt.plot([1,2,3,4],[1,4,9,16])
[<matplotlib.lines.Line2D at 0x1348f5764c8>]

Setting graph properties


if you do not specify otherwise, the plot is represented taking into account a default
configuration of the plt.plot() function: - The size of the axes matches perfectly with the
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

range of the input data - There is neither a title nor axis labels - There is no legend - A blue
line connecting the points is drawn
Therefore, you need to change this representation to have a real plot in which each pair of
values (x, y) is represented by a red dot
plt.plot([1,2,3,4],[1,4,9,16],'ro')
[<matplotlib.lines.Line2D at 0x1348f5e3948>]

You can define the range both on the x-axis and on the y-axis by defining the details of a list
[xmin, xmax, ymin, ymax] and then passing it as an argument to the axis()
function. You can set several properties, one of which is the title that can be entere d using
the title() function.
plt.axis([0,5,0,20])
plt.title('My first plot')
plt.plot([1,2,3,4],[1,4,9,16],'ro')
[<matplotlib.lines.Line2D at 0x1348f649588>]
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

You can see how the new settings made the plot more readable. In fact, the end points of
the dataset are now represented within the plot rather than at the edges. Also the title of
the plot is now visible at the top.

matplotlib and NumPy


Even the matplot library, despite being a fully graphical library, has its foundation as the
NumPy library. In fact, you have seen so far how to pass lists as arguments, both to
represent the data and to set the extremes of the axes. Actually, these lists have been
converted internally in NumPy arrays. Therefore, you can directly enter NumPy arrays as
input data.
As an example let's so how to generate points following a sinusoidal trend, you will use the
NumPy library. Generate a series of points on the x-axis using the arange() function, while
for the values on the y-axis you will use the map() function to apply the sin() function on
all the items of the array without a loop.
import numpy as np
t = np.arange(0,2.5,0.1)
y1 = np.sin(np.pi*t)
y2 = np.sin(np.pi*t+np.pi/2)
y3 = np.sin(np.pi*t-np.pi/2)
plt.plot(t,y1,'r*',t,y2,'g^',t,y3,'ys')
[<matplotlib.lines.Line2D at 0x1348f6bea08>,
<matplotlib.lines.Line2D at 0x1348f6d2108>,
<matplotlib.lines.Line2D at 0x1348f005408>]
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

It is better to use the lines to differentiate the three trends with something other than color,
you can use the pattern composed of different combinations of dots and dashes ( - and . ).
plt.plot(t,y1,'b--',t,y2,'g',t,y3,'r-.')
[<matplotlib.lines.Line2D at 0x1348f743408>,
<matplotlib.lines.Line2D at 0x1348f743648>,
<matplotlib.lines.Line2D at 0x1348f743888>]

Using kwargs
The objects that make up a chart have many attributes that characterize them. These
attributes are all default values, but can be set through the use of keyword args , often
referred as kwargs. These keywords are passed as arguments to functions. In reference
documentation of the various functions of the matplotlib library, you will always find them
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

referred to as kwargs in the last position. For example the plot() function that you are
using in these examples is referred to in the following way.
matplotlib.pyplot.plot(*args, **kwargs)
For a practical example, the thickness of a line can be changed if you set the linewidth
keyword
plt.plot([1,2,4,2,1,0,1,2,1,4],linewidth=5.0)
[<matplotlib.lines.Line2D at 0x1348f7af108>]

Working with multiple figures and axes


So far you have seen how all pyplot commands are routed to the display of a single figure.
Actually, matplotlib allows you to manage multiple figures simultaneously, and within each
figure, it offers the ability to view different plots defined as subplots.
Now you will see an example where two subplots are represented in a single figure. The
subplot() function, in addition to subdividing the figure in different drawing areas, is used to
focus the commands on a specific subplot. The argument passed to the subplot()
function sets the mode of subdivision and determines which is the current subplot. The
current subplot will be the only figure that will be affected by the commands. The argument
of the subplot() function is composed of three integers. The first number defines how
many parts the figure is split into vertically. The second number defines how many parts the
figure is divided into horizontally. The third issue selects which is the current subplot on
which you can direct commands.
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

t = np.arange(0,5,0.1)
y1 = np.sin(2*np.pi*t)
y2 = np.sin(2*np.pi*t)
plt.subplot(211)
plt.plot(t,y1,'b-.')
plt.subplot(212)
plt.plot(t,y2,'r--')
[<matplotlib.lines.Line2D at 0x1348f8608c8>]

Now you do the same thing by dividing the figure in two vertical subplots. The numbers to
be passed as arguments to the subplot() function are 121 and 122
t = np.arange(0,5,0.1)
y1 = np.sin(2*np.pi*t)
y2 = np.sin(2*np.pi*t)
plt.subplot(121)
plt.plot(t,y1,'b-.')
plt.subplot(122)
plt.plot(t,y2,'r--')
[<matplotlib.lines.Line2D at 0x1348f525b48>]
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

Adding Elements to the Chart


In order to make a chart more informative, many times it is not enough to represent the
data using lines or markers and assign the range of values using two axes. In fact, there are
many other elements that can be added to a chart in order to enrich it with additional
information.

Adding Text
You’ve already seen how you can add the title to a chart with the title() function. Two
other textual indications you can add the axis labels. This is possible through the use of two
other specific functions, called xlabel() and ylabel(). These functions take as an
argument a string, which will be the shown text.
plt.axis([0,5,0,20])
plt.title('My first plot')
plt.xlabel('Counting')
plt.ylabel('Square values')
plt.plot([1,2,3,4],[1,4,9,16],'ro')
[<matplotlib.lines.Line2D at 0x1348f8ebf08>]
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

But matplotlib is not limited to this: pyplot allows you to add text to any position within a
chart. This feature is performed by a specific function called text(). text(x,y,s,
fontdict=None, **kwargs)
The first two arguments are the coordinates of the location where you want to place the
text. s is the string of text to be added, and fontdict (optional) is the font that you want to
use. Finally, you can add the keywords
plt.axis([0,5,0,20])
plt.title('My first plot')
plt.xlabel('Counting')
plt.ylabel('Square values')
plt.text(1,1.5,'First')
plt.text(2,4.5,'Second')
plt.text(3,9.5,'Third')
plt.text(4,16.5,'Fourth')
plt.plot([1,2,3,4],[1,4,9,16],'ro')
[<matplotlib.lines.Line2D at 0x1348c020788>]
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

Adding Grids
Another element you can add to a plot is a grid. Often its addition is necessary in order to
better understand the position occupied by each point on the chart. Adding a grid to a chart
is a very simple operation: just add the grid() function, passing True as an argument
plt.axis([0,5,0,20])
plt.title('My first plot')
plt.xlabel('Counting')
plt.ylabel('Square values')
plt.text(1,1.5,'First')
plt.text(2,4.5,'Second')
plt.text(3,9.5,'Third')
plt.text(4,16.5,'Fourth')
plt.plot([1,2,3,4],[1,4,9,16],'ro')
plt.grid()
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

Adding Legends
Another very important component that should be present in any chart is the legend. pyplot
also provides a specific function for this type of object: legend(). Add a legend to your
chart with the legend() function and a string indicating the words with which you want the
series to be shown. In this example, you assign the First series name to the input data array
plt.axis([0,5,0,20])
plt.title('My first plot')
plt.xlabel('Counting')
plt.ylabel('Square values')
plt.grid(True)
plt.plot([1,2,3,4],[1,4,9,16],'ro')
plt.plot([1,2,3,4],[0.8,3.5,8,15],'g^')
plt.plot([1,2,3,4],[0.5,2.5,4,12],'b*')
plt.legend(['First series','Second series','Third series'])
<matplotlib.legend.Legend at 0x1348c106848>
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

the legend is added in the upper-right corner by default. Again if you want to change this
behavior you will need to add a few kwargs. For example, the position occupied by the
legend is set by assigning numbers from 0 to 10 to the loc kwarg. Each of these numbers
characterizes one of the corners of the chart. A value of 1 is the default, that is, the upper-
right corner.

plt.axis([0,5,0,20])
plt.title('My first plot')
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

plt.xlabel('Counting')
plt.ylabel('Square values')
plt.grid(True)
plt.plot([1,2,3,4],[1,4,9,16],'ro')
plt.plot([1,2,3,4],[0.8,3.5,8,15],'g^')
plt.plot([1,2,3,4],[0.5,2.5,4,12],'b*')
plt.legend(['First series','Second series','Third series'],loc=1)
<matplotlib.legend.Legend at 0x1348fc4ffc8>

Saving Your Chart


If you are interested in saving only the figure of a chart as an image file, ignoring all the code
you’ve written during the session, this is also possible. In fact, thanks to the savefig()
function, you can directly save the chart in a PNG format, although you should take care to
add this function to the end of the same series of commands (otherwise you’ll get a blank
PNG file).
plt.axis([0,5,0,20])
plt.title('My first plot')
plt.xlabel('Counting')
plt.ylabel('Square values')
plt.grid(True)
plt.plot([1,2,3,4],[1,4,9,16],'ro')
plt.plot([1,2,3,4],[0.8,3.5,8,15],'g^')
plt.plot([1,2,3,4],[0.5,2.5,4,12],'b*')
plt.legend(['First series','Second series','Third series'],loc=2)
plt.savefig('my_chart.png')
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

Other types of Charts


There are different types of charts, starting from the most common ones such as linear
charts, bar charts, and pie charts, up to a discussion about some that are more sophisticated
but commonly used nonetheless.

Histogram
A histogram consists of adjacent rectangles erected on the x-axis, split into discrete intervals
called bins, and with an area proportional to the frequency of the occurrences for that bin.
This kind of visualization is commonly used in statistical studies about distribution of
samples. In order to represent a histogram, pyplot provides a special function called
hist(). There are two inputs. The first is a series of samples of values as an argument and
the number of bins in which to be divided
pop = np.random.randint(0,100,100)
n,bins,patches = plt.hist(pop,bins=20)
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

Bar Chart
Another very common type of chart is the bar chart. It is very similar to a histogram but in
this case the x-axis is not used to reference numerical values but categories. The realization
of the bar chart is very simple with matplotlib, using the bar() function.
index = [0,1,2,3,4]
values = [5,7,3,4,6]
plt.bar(index,values)
<BarContainer object of 5 artists>

index = [0,1,2,3,4]
values = [5,7,3,4,6]
plt.barh(index,values)
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

<BarContainer object of 5 artists>

Pie Chart
An alternative way to display data to the bar charts is the pie chart, easily obtainable using
the pie() function. Even for this type of function, you pass as the main argument a list
containing the values to be displayed. I chose the percentages (their sum is 100), but you
can use any kind of value. It will be up to the pie() function to inherently calculate the
percentage occupied by each value.
labels = ['Nokia','Samsung','Apple','Lumia']
values = [10,30,45,15]
colors = ['yellow','green','red','blue']
plt.pie(values,labels=labels,colors=colors)
plt.axis('equal')
(-1.11637372803214,
1.1007797090739162,
-1.1163737124158366,
1.1007797083302826)
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

Contour Plots
A quite common type of chart in the scientific world is the contour plot or contour map. This
visualization is in fact suitable for displaying three-dimensional surfaces through a contour
map composed of curves closed showing the points on the surface that are located at the
same level, or that have the same z value.
Although visually the contour plot is a very complex structure, its implementation is not so
difficult, thanks to the matplotlib library. First, you need the function z = f (x, y) for
generating a three-dimensional surface. Then, once you have defined a range of values x, y
that will define the area of the map to be displayed, you can calculate the z values for each
pair (x, y), applying the function f (x, y) just defined in order to obtain a matrix of z values.
Finally, thanks to the contour() function, you can generate the contour map of the surface. It
is often desirable to add also a color map along with a contour map. That is, the areas
delimited by the curves of level are filled by a color gradient, defined by a color map.
dx = 0.01; dy = 0.01
x = np.arange(-2.0,2.0,dx)
y = np.arange(-2.0,2.0,dy)
X,Y = np.meshgrid(x,y)
def f(x,y):
return (1 - y**5 + x**5)*np.exp(-x**2-y**2)
C = plt.contour(X,Y,f(X,Y),8,colors='black')
plt.contourf(X,Y,f(X,Y),8)
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

plt.clabel(C, inline=1, fontsize=10)


plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x13490cdf7c8>

The mplot3d toolkit


The mplot3d toolkit is included with all standard installations of matplotlib and allows you
to extend the capabilities of visualization to 3D data. If the figure is displayed in a separate
window, you can rotate the axes of the three-dimensional representation with the mouse.
With this package you are still using the Figure object, only that instead of the Axes object
you will define a new kind of object, called Axes3D, and introduced by this toolkit. Thus,
you need to add a new import to the code, if you want to use the Axes3D object.
from mpl_toolkits.mplot3d import Axes3D

3D Surface
In a previous section, you used the contour plot to represent the three -dimensional surfaces
through the level lines. Using the mplot3D package, surfaces can be drawn directly in 3D. In
this example, you will use the same function z = f (x, y) you have use d in the contour map.
Once you have calculated the meshgrid, you can view the surface with the
plot_surface() function. A three-dimensional blue surface will appear
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-2,2,0.1)
Y = np.arange(-2,2,0.1)
X,Y = np.meshgrid(X,Y)
def f(x,y):
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

return (1 - y**5 + x**5)*np.exp(-x**2-y**2)


ax.plot_surface(X,Y,f(X,Y), rstride=1, cstride=1)
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x1348c0b76c8>

Scatter Plot in 3D
The mode most used among all 3D views remains the 3D scatter plot. With this type of
visualization, you can identify if the points follow particular trends, but above all if they tend
to cluster. In this case, you will use the scatter() function as the 2D case but applied on
the Axes3D object. By doing this, you can visualize different series, expressed by the calls to
the scatter() function, all together in the same 3D representation
xs = np.random.randint(30,40,100)
ys = np.random.randint(20,30,100)
zs = np.random.randint(10,20,100)

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(xs,ys,zs)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #04: Introduction to Matplotlib

Text(0.5, 0, 'Z Label')

Exercise 3
Generate the following graph:

please note that the samples appear in red and blue are randomly generated samples with
different ranges.

Exercise 4
Plot the surface of the following function:

You might also like