CSE488_Lab4_Matplotlib
CSE488_Lab4_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>]
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.
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>]
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 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>
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
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
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
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
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: