Data visualization with
matplotlib library –
Module 1
Introduction
• Data visualization is a very important factor because incorrect or
inefficient data representation can ruin an otherwise excellent analysis.
Visualization Objectives
• Record information
• Analyze data to support reasoning
• Confirm hypotheses
• Communicate ideas to others
The matplotlib Library
• 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.
• Some features that have made it the most used tool in the graphical
representation of data:
❑ Extreme simplicity and deducibility in its use
❑ Gradual development and interactive data visualization
❑ Expressions and text in LaTeX
❑ Greater control over graphic elements
❑ Export to many formats, such as PNG, PDF, SVG, and EPS
• Used for basic plotting
• Highly customizable
• Works with NumPy and pandas
• Suitable for both experts in the field and also beginners
• Matplotlib looks like a graphics library that allows us to
programmatically manage the graphic elements that make up a
chart so that the graphical display can be controlled in its entirety.
• The ability to program the graphical representation allows
management of the reproducibility of the data representation across
multiple environments and especially when it is needed to make
changes or when the data is updated.
Installation
• There are many options for installing the matplotlib library.
• If you choose to use a distribution of packages like Anaconda or Enthought
Canopy, installing the matplotlib package is very simple.
• For example, with the conda package manager, enter the following:
conda install matplotlib
• If the package is to be directly installed, the commands to insert vary
depending on the operating system.
• On Debian-Ubuntu Linux systems, use this:
sudo apt-get install python-matplotlib
• On Fedora-Redhat Linux systems, use this:
sudo yum install python-matplotlib
• On Windows or MacOS, use pip for installing matplotlib.
Matplotlib Architecture
• One of the key tasks is that matplotlib provides 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.
• However, matplotlib not only deals with graphics but also provides all the
tools for event handling and the ability to animate graphics.
• With these additional features, matplotlib proves to be capable of
producing interactive charts based on the events triggered by pressing a
key on the keyboard or on mouse movement.
Three layers
• 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.
The three layers of the matplotlib architecture
• The three layers are:
❑ Scripting
❑ Artist
❑ Backend
Backend Layer
• In the diagram of the matplotlib architecture, the layer that works at the
lowest level is the Backend layer.
• This layer contains the matplotlib APIs - a set of classes that play the role
of implementing the graphic elements at a low level.
❑ FigureCanvas is the object that includes the concept of drawing area.
❑ Renderer is the object that draws on FigureCanvas.
❑ Event is the object that handles user inputs (keyboard and mouse events).
Artist Layer
• The intermediate layer is a layer called Artist.
• All the elements that make up a chart, such as title, axis labels, markers,
etc., are instances of the Artist object.
• Each of these instances plays its role within a hierarchical structure
Each element of a chart corresponds to an instance of Artist structured in a hierarchy
Two Artist classes
• Primitive
Primitive artists are individual objects that constitute the basic elements to
form a graphical representation in a plot, for example, a Line2D, or as a
geometric figure such as a Rectangle or Circle, or even pieces of text.
• Composite
The composite artists are those graphic elements present in a chart that is
composed of several base elements, namely, the primitive artists. Composite
artists are for example the Axis, Ticks, Axes, and Figures.
Three main artist objects in the hierarchy of the Artist layer
• Figure is the object with the highest level in the hierarchy. It corresponds
to the entire graphical representation and generally can contain many
Axes.
• Axes are generally plots or charts. Each Axis object belongs to only one
Figure, and is characterized by two Artist Axis (three in the
three-dimensional case). Other objects, such as the title, the x label, and the
y label, belong to this composite artist.
• Axis objects are the numerical values to be represented on Axes, define
the limits, and manage the ticks (the mark on the axes) and tick labels (the
label text represented on each tick).
• The position of the tick is adjusted by an object called a Locator while the
Scripting Layer (pyplot)
• 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.
pylab and pyplot
• Pylab is a module that is installed along with matplotlib, while Pyplot is
an internal module of matplotlib.
from pylab import *
and
import [Link] as plt
import numpy as np
• Pylab combines the functionality of pyplot with the capabilities of NumPy in
a single namespace, and therefore it is not needed to import NumPy separately.
• By importing pylab, Pyplot, and NumPy functions can be called directly
without any reference to a module (namespace).
plot(x,y)
array([1,2,3,4])
Instead of
[Link]()
[Link]([1,2,3,4]
• The pyplot package provides the classic Python interface for programming the
matplotlib library, has its own namespace, and requires the import of the
NumPy package separately.
pyplot
• The pyplot module is a collection of command-style functions that allows
using 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.
• Pyplot also is stateful, in that it tracks the status of the current figure and
its plotting area. The functions called act on the current figure.
A Simple Interactive Chart
• Using Matplotlib, creating a simple interactive chart is very simple.
• It is achieved using only three lines of code.
1. Import the pyplot package and rename it as plt.
In [1]: import [Link] as plt
• In Python, the constructors generally are not necessary; everything is already
implicitly defined.
• When the package is imported, the plt object with all its graphics capabilities has
already been instantiated and is ready to use.
2. The plot() function is simply used to pass the values to be plotted.
In [2]: [Link]([1,2,3,4])
Out[2]: [<[Link].Line2D at 0xa3eb438>]
A Line2D object has been generated.
The object is a line that represents the linear trend of the points included in the chart.
3. Give the command to show the plot using the show() function.
In [3]: [Link]()
• The result is the plotting window, with a toolbar and the plot represented
within it, just as with MATLAB.
Plotting Window
• The plotting window is characterized by a toolbar at the top in which there
are a series of buttons.
• The code entered into the IPython console corresponds to the Python console to
the following series of commands:
>>> import [Link] as plt
>>> [Link]([1,2,3,4])
[<[Link].Line2D at 0x0000000007DABFD0>]
>>> [Link]()
• Using the IPython QtConsole, it is observed that after calling the plot() function
the chart is displayed directly without explicitly invoking the show() function.
The QtConsole shows the chart directly as output
• If only a list of numbers or an array is passed to the [Link]() 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 for defining a chart correctly must
define two arrays, the first containing the values on the x-axis and the second
containing the values on the y-axis.
• The plot() function can accept a third argument, which describes the specifics of
representing point on the chart.
Set the Properties of the Plot
• The size of the axes matches perfectly with the 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
The pairs of (x,y) values are represented in
the plot by red circles
In [4]: [Link]([1,2,3,4],[1,4,9,16],'ro')
Out[4]: [<[Link].Line2D at 0x93e6898>]
In [5]: [Link]()
• Working on IPython, close the window to get back to the active prompt for
entering new commands. Then, the show() function is called back to observe the
changes made to the plot.
• Working on Jupyter QtConsole, a different plot is seen for each new command
that is entered.
• The range can be defined 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.
• Title can be entered using the title() function.
In [4]: [Link]([0,5,0,20])
...: [Link]('My first plot')
...: [Link]([1,2,3,4],[1,4,9,16],'ro')
Out[4]: [<[Link].Line2D at 0x97f1c18>]
matplotlib and NumPy
• Even the matplot library, despite being a fully graphical library, has its foundation as
the NumPy library.
• In fact, lists can be passed as arguments, both to represent the data and to set the
extremes of the axes.
• These lists have been converted internally in NumPy arrays.
• NumPy arrays can be directly entered as input data.
• This array of data, which has been processed by pandas, can be directly used with
matplotlib without further processing.
• Example: sin() function belonging to the math module. So it needs to be imported.
• To generate points following a sinusoidal trend, the NumPy library is used.
• Generate a series of points on the x-axis using the arange() function, while for the
values on the y-axis the map() function is used to apply the sin() function on all the
items of the array.
Example: Three sinusoidal trends phase-shifted by
π / 4 represented by markers
In [5]: import math
In [6]: import numpy as np
In [7]: t = [Link](0,2.5,0.1)
...: y1 = [Link]([Link]*t)
...: y2 = [Link]([Link]*t+[Link]/2)
...: y3 = [Link]([Link]*[Link]/2)
In [8]: [Link](t,y1,'b*',t,y2,'g^',t,y3,'ys')
Out[8]:
[<[Link].Line2D at 0xcbd2e48>,
<[Link].Line2D at 0xcbe10b8>,
<[Link].Line2D at 0xcbe15c0>]
• To differentiate the three trends with something other than color, the pattern composed of
different combinations of dots and dashes ( - and . ) can be used.
In [9]: [Link](t,y1,'b--',t,y2,'g',t,y3,'r-.')
Out[9]:
[<[Link].Line2D at 0xd1eb550>,
<[Link].Line2D at 0xd1eb780>,
<[Link].Line2D at 0xd1ebd68>]
• This chart represents the three sinusoidal patterns
with colored lines