Chapter

---
Introduction to Matplotlib & pylab

Aman W
Department of Applied Physics
University of Gondar
Contents

• Introduction to Graph &visualization of data
• Matplotlib
• Pylab
– Plot
– Show()
• Graphs/Plots
• Line plot
• Scatter plot, histogram, …, etc
• Pylab & Numpy & Scipy
• 3D graphics
Introduction to Graph &visualization of data
• So far we have created programs that print out words and
numbers,
• The purpose of scientific computation is not getting numbers,
but to analyze what this number shows
• To understand the meaning of the (many) numbers we
compute, we often need post processing, statistical analysis
and graphical visualization of our data.
• We will also want our programs to produce graphics, meaning
pictures of some sort.
• Visualization is a method of computing. It transforms the
symbolic into the geometric and enabling researchers to
observe their simulations and computations.
Matplotlib & Pylab

• A picture says more than a thousand words.
• The following sections describe Matplotlib/Pylab which
allows us to generate high quality graphs of the type y = f(x)
(and a bit more)
• The Python library Matplotlib is a 2D/3D plotting library
which produces quality figures in a variety of hardcopy
formats and interactive environments.
• Pylab is slightly more convenient to use for easy plots, and
• Matplotlib gives far more detailed control over how plots are
created.
• You can generate different plots,
– line graphs, histograms, power spectra,
– bar charts, errorcharts, scatterplots, etc, with just a few lines of
code.
• Matplotlib home page
http://matplotlib.sourceforge.net
• Matplotlib tutorial
http://matplotlib.sourceforge.net/users/index.html
• Visual Python which is a very handy tool to quickly generate
animations of time dependent processes taking place in 3d
space.
Graphs/Plots

• A number of Python packages include features for making
graphs.
• In this section we will use the powerful, easy-to-use, and
popular package pylab.
• The package contains features for generating graphs of many
different types.
• We will concentrate of three types that are especially useful in
physics: ordinary line graphs, scatter plots, and density (or
heat) plots.
• We start by looking at line graphs.
Import Pylab

 Before using Pylab, we should import it the package
 Three formats of the command:
import Pylab
from Pylab import *
from Pylab import Name
• The difference?
• What gets imported from the file and what name refers to it after importing
• import Pylab
• Everything in Pylab gets imported.
• To refer to something in the file, append the text Numpy to the front
of its name:
 Pylab.Name
 from Pylab import *
• Everything in Pylab gets imported
• To refer to anything in the module, just use its name.
Everything in the module is now in the current namespace.
• Take care! Using this import command can easily overwrite
the definition of an existing function or variable!
• from pylab import * this method is not generally
recommended but it is okay for interactive testing
• While using from pylab import * is acceptable at the command
prompt to interactively create
• The pylab top level provides over 800 different objects which
are all imported into the global name space when running from
pylab import *.
• This is not good practice, and could conflict with other objects
that exist already or are created later.
• As a rule of thumb: never use from somewhere import * in
programs we save.
 from Pylab import Name
• Only the item Name in Pylab gets imported.
• After importing Name, you can just use it without a module
prefix. It’s brought into the current namespace.
• The pylab module has a number of function
– Plot(),
– show(),
– xlabel(), ylabel(),
– legend(),
– Title(), …, etc
• To create an ordinary graph in Python, we use the function
plot and show() from the pylab package
Line plots

• Here is a simple example
• import pylab # We import pylab
y = [ 1.0, 2.4, 1.7, 0.3, 0.6,1.8 ]
pylab.plot(y)
• In the simplest case, this function plot takes one argument, which is a
list or array of the values we want to plot, y.
• The function creates a graph of the given values in the memory of the
computer, but it doesn’t actually display it on the screen of the
computer
pylab,show()
• To display the graph we use a second function from pylab, the show
function, which takes the graph in memory and draws it on the screen
Pylab: plot, show

• When all of them written simply as
follows
import pylab # import pylab
y = [ 1.0, 2.4, 1.7, 0.3, 0.6,1.8 ]
pylab.plot(y)
pylab,show()
• When we run the program above, it
produces a new window on the
screen with a graph in it like this:
• The computer has plotted the values
in the list y at unit intervals along the
x-axis (starting from zero in the
standard Python style) and joined
them up with straight lines.
Pylab: plot, show

• Normally we want to specify both
the x- and y-coordinates for the
points in the graph.
• We can do this using a plot
statement with two list arguments,
thus:

>>> import pylab
>>>x = [ 0.5, 1.0, 2.0, 4.0, 7.0, 10.0 ]
>>>y = [ 1.0, 2.4, 1.7, 0.3, 0.6, 1.8 ]
>>>pylab.plot(x, y)
>>>pylab.show()
• Once you have displayed a graph on the screen you can do
other things with it.
• You will notice a number of buttons along the bottom of the
window in which the graph appears (not shown in the figures
here, but you will see them if you run the programs on your
own computer).
• Among other things, these buttons allow you to zoom in on
portions of the graph, move your view around the graph, or
save the graph as an image file on your computer.
• You can also save the graph in “PostScript” format, which you
can then print out on a printer or insert as a figure in a word
processor document.
• The other important thing about this graph is
• What variable x and y axis indicates?
• What is the title/ description of this plot?
• y = sin(x)--- this plot
• import pylab
x = [ 0.5, 1.0, 2.0, 4.0, 7.0, 10.0 ]
y = [ 1.0, 2.4, 1.7, 0.3, 0.6, 1.8 ]
pylab.plot(x, y)
pylab.xlabel('x-axis')
pylab.ylabel('y-axis')
pylab.title('x-y plot')
pylab.show()
• xlabel('...') and ylabel('...') allow labelling the axes.
• Title or plot(x,y, label=‘—’) The label keyword defines the
name of this line.
• The line label will be shown in the legend if the legend()
command is used .
• legend() This command will display a legend with the labels
as defined in the plot command.
• grid() This command will display a grid on the backdrop.
• The full list of options can be found when typing
help(‘pylab.plot’) at the Python prompt
import pylab
x = [ 0.5, 1.0, 2.0, 4.0, 7.0, 10.0 ]
y = [ 1.0, 2.4, 1.7, 0.3, 0.6, 1.8 ]
pylab. plot(x,y,'--k')
pylab.xlabel('x-axis')
pylab.ylabel('y-axis')
pylab.title('x-y plot')
pylab.show()
• Note further than you can chose different line styles, line
thicknesses, symbols and colours for the data to be plotted.
(The syntax is very similar to MATLAB.)
• For example:
– plot(x,y,'og') will plot circles (o) in green (g)
– plot(x,y,'-r') will plot a line (-) in red (r)
– plot(x,y,'-b‘, line width=2) will plot a blue line (b) with two
pixel thickness line width=2 which is twice as wide as the
default.
Pylab: Plot Style

• Line style
• Color – "-": solid line
– r: red – "--": dashed line
– g: green – ".": mark points with a
– b: blue point
– c: cyan – "o": mark points with a
circle
– m: magenta
– "s": mark points with a
– y: yellow
square
– k: black For instance
– w: white 'r-^‘ red, dot-dash, triangles
Pylab: xlim, ylim, xlabel, ylabel

• xlim
– Get or set the *x* limit of the current axes.
• ylim
– Get of set the *y* limit of the current axes.
• xlabel
– Set the *x* axis label of the current axes.
• ylabel
– Set the *y* axis label of the current axes.
• Once you have created the figure (using the plot command)
and added any labels, legends etc, you
• have two options to save the plot.
– You can display the figure (using show) and interactively
save it by clicking on the disk icon.
– You can (without displaying the figure) save it directly
from your Python code.
• The command to use is savefig.
• The format is determined by the extension of the le name you
provide.
• Here is an example which saves the plot
import pylab
x = [ 0.5, 1.0, 2.0, 4.0, 7.0, 10.0 ]
y = [ 1.0, 2.4, 1.7, 0.3, 0.6, 1.8 ]
pylab . plot (x, y, label =‘x-y plot')
pylab.xlabel('x-axis')
pylab.ylabel('y-axis')
pylab . savefig ('myplot .png ') #
saves png file
pylab . savefig ('myplot .eps ') #
saves eps file
pylab . savefig ('myplot .pdf ') #
saves pdf file