You are on page 1of 22

Python 3: Plotting simple graphs

Bruce Beckles mbb10@cam.ac.uk


Bob Dowling rjd4@cam.ac.uk
4 February 2013
Whats in this course
This course runs through a series of types of graph. You will learn ost by !oing all of the" ob#iously.
$owe#er" if you want to fast%forwar! to &ust the sort of graph you want to !o then you nee! to !o the first
three sections an! then you can &up to the type of graph you want.
1. Drawing a basic line graph
2. Drawing multiple curves
3. Parametric graphs
4. 'catter graphs
(. )rror bar graphs
*. +olar graphs
,. $istogras
-. Bar charts
By the en! of each section you will be creating graphs like these" the en!%of%section e.ercises/
Prerequisites
This self%pace! course assues that you ha#e a knowle!ge of +ython 3 e0ui#alent to ha#ing coplete! one
or other of
+ython 3/ 1ntro!uction for 2bsolute Beginners" or
+ython 3/ 1ntro!uction for Those with +rograing ).perience
'oe e.perience beyon! these courses is always useful but no other course is assue!.
The course also assues that you know how to use a 3ni. te.t e!itor 4gedit" emacs" vi" 56.
!
The +ython o!ule use! in this course is built on top of the nuerical python
o!ule" numpy. You !o not nee! to know this o!ule for ost of the course as
the o!ule aps +ython lists into numpy7s one%!iensional arrays autoatically.
There is one place" in the bar charts chapter" where using numpy akes life
uch easier" an! we will !o it both ways. You can safely skip the numpy way if
you !o not know about it.
Facilities for this session
The coputers in this roo ha#e been prepare! for these self%pace! courses. They are alrea!y
logge! in with course 1Ds an! ha#e hoe !irectories specially prepare!. +lease !o not log in un!er
any other 1D.
These courses are hel! in a roo with two !eonstrators. 1f you get stuck or confuse!" or if you &ust
ha#e a 0uestion raise! by soething you rea!" please ask8
The hoe !irectories contain a nuber of sub!irectories one for each topic. For this topic please
enter !irectory graphs. 2ll work will be coplete! there/
$ cd graphs
$ pwd
/home/x250/graphs
$
2t the en! of this session the hoe !irectories will be cleare!. 2ny files you lea#e in the will be
!elete!. +lease copy any files you want to keep.
These han!outs an! the prepare! fol!ers to go with the can be !ownloa!e! fro
.ucs.cam.ac.uk/docs/course!notes/unix!courses/pythontopics
You are welcoe to annotate an! keep this han!out.
The foral !ocuentation for the topics co#ere! here can be foun! online at
matp"ot"ib.org/1.2.0/index.htm"
2922
Notation
Warnings
!
:arnings are arke! like this. These sections are use! to highlight coon
istakes or isconceptions.
!ercises
!ercise "
).ercises are arke! like this.
#nput an$ output
;aterial appearing in a terinal is presente! like this/
$ more lorem.txt
#orem ipsum do"or sit amet$ consectetur adipisicing e"it$ sed do eiusmod
tempor incididunt ut "abore et do"ore magna a"i%ua. &t enim ad minim veniam$
!!'ore!!(44)*
The aterial you type is presente! like this/ ls. 4Bol! face" typewriter font.6
The aterial the coputer respon!s with is presente! like this/ <#orem ipsum=. 4Typewriter font again but in
a noral face.6
%eys on the &eyboar$
>eys on the keyboar! will be shown as the sybol on the keyboar! surroun!e! by s0uare brackets" so the
<2 key= will be written <?2@=. Aote that the return key 4presse! at the en! of e#ery line of coan!s6 is written
<? @=" the shift key as <? @=" an! the tab key as <? @=. +ressing ore than one key at the sae tie 4such as
pressing the shift key !own while pressing the 2 key6 will be written as <? @B?2@=. Aote that pressing ?2@
generates the lower case letter <a=. To get the upper case letter <2= you nee! to press ? @B?2@.
'ontent of files
The content
1
of files 4with a coent6 will be shown like this/
#orem ipsum do"or sit amet$ consectetur adipisicing e"it$ sed do eiusmod tempor
incididunt ut "abore et do"ore magna a"i%ua. &t enim ad minim veniam$ %uis
nostrud exercitation u""amco "aboris nisi ut a"i%uip ex ea commodo conse%uat.
+uis nu""a pariatur. This is a comment about the line.
1 The e.aple te.t here is the faous <lore ipsu= !uy te.t use! in the printing an! typesetting
in!ustry. 1t !ates back to the 1(00s. 'ee http,//."ipsum.com/ for ore inforation.
3922
!
This course uses #ersion 3 of the +ython language. Cun your scripts as
$ python3 example1.py
etc.
Drawing a basic line graph
:e start by iporting the graphics o!ule we are going to use. The o!ule is calle!
<matp"ot"ib.pyp"ot= which is a bit long so we iport it un!er an alias" <pyp"ot=/
import matp"ot"ib.pyp"ot as pyp"ot
:e also nee! soe !ata to plot. Cather than spen! tie preparing !ata in our scripts the course has a local
o!ule which consists of nothing but !uy !ata for plotting :e iport this" but reeber it7s &ust a local
hack/
import p"otdata
x - p"otdata.data01x
y - p"otdata.data01y
The naes <x= an! <y= are attache! to two lists of floating point #alues" the .%#alues an! the y%#alues. 41f you
know the numpy o!ule then these can also be boun! to two nupy 1%! arrays of #alues too.6
The list p"otdata.data01x is &ust a list of nubers fro %1 to B1 an! p"otdata.p"ot01y is a list of
those nubers cube!.
Aow we ha#e to actually plot the !ata/
pyp"ot.p"ot(x$y*
2n! that7s it for a graph with all the !efault settings. Aow we &ust nee! to sa#e the graph to a file or !isplay it
on the screen/
pyp"ot.save.ig(/examp"e01.png/*
The pyp"ot.save.ig(* function sa#es the current graph to a file i!entifie! by nae. 1t can take a +ython
file ob&ect" but if you !o that reeber to open it in binary o!e. 4'o open it with
open(/examp"e01.png/$ /b/*.6
!
There is an alternati#e to pyp"ot.save.ig(* calle! pyp"ot.sho(*. This
launches an interacti#e #iewer. There is a proble with using it in an interacti#e
session" though/
pyp"ot.sho(* resets the state of the graphics subsyste an! you ha#e to
repeat ost of the coan!s you ha! pre#iously type! in to get a secon! graph
in the sae interacti#e session. 1tDs often sipler to 0uite +ython 3 an! restart it.
This is why this course uses pyp"ot.save.ig(* an! scripts.
:e can now run the script/
$ python3 example01.py
1f you want to #iew a graphics file7s contents" either !ouble%click on it in the graphical file browser or open it
fro the coan! line with the <eog= progra
2
/
2 <eog= stan!s for ye of (noe an! is the !efault graphics #iewer for the Enoe !esktop en#ironent
that we use on the ;anage! Fluster 'er#ice.
4922
$ eog example01.png &
011 5523
$
4This e.aple runs eog in the backgroun!. Gose the apersan! at the en!
to run it in the foregroun!.6
:e can obser#e a few aspects of the !efault beha#iour that we ight want
to o!ify/
the a.es e.actly atch the !ata ranges
the tick arks are e#ery 0.( units
there is no title
there are no labels on the a.es
there is no legen!
the line is blue
:e will a!!ress these points one%by%one. 2 series of e.aple scripts calle! <examp"e01a.py="
<examp"e01b.py=" etc. are pro#i!e! to illustrate each o!ification in isolation. )ach script is accopanie!
by its associate! graph <examp"e01a.png=" <examp"e01b.png=" etc.
)etting the a!es limits
4'cript/ examp"e01a.py" graph/ examp"e01a.png6
The a.es on the graph are autoatically !eri#e! fro the !ata ranges in
.%#alues an! y%#alues. This is often what you want an! is not a ba! !efault.
There is a function pyp"ot.axis(* which e.plicitly sets the liits of the
a.es to be !rawn. 1t takes a single arguent which is a list of four #alues/
pyp"ot.axis(04
min
$4
max
$5
min
$5
max
1*.
For e.aple" to set the line floating with 0.( units of space on either si!e of
our cur#e we woul! a!! the following line before the call to
pyp"ot.p"ot(x$y*/
pyp"ot.axis(0!1.5$ 1.5$ !1.5$ 1.51*
Typically all the settings calls are run before pyp"ot.p"ot(*. The only call that coes afterwar!s is
pyp"ot.save.ig(* or pyp"ot.sho(*.
!
There is another function with a #ery siilar nae" pyp"ot.axes(*" with #ery
siilar arguents that !oes soething relate! but !ifferent.
You want pyp"ot.axis.(* 4n.b./ singular axis6
)etting the tic& mar&s
There is a !efault set of tick arks that are create!" base! on the a.is liits. These are often sufficient but
you can change the if you want to.
There is a function pyp"ot.xticks(* which sets the ticks along the .%a.is an! a correspon!ing function"
pyp"ot.yticks(*" for the y%a.is. These can set the labels on the ticks as well as the position of the ticks.
1n its siplest use" pyp"ot.xticks(* is passe! a list of .%#alues at which it shoul! !raw ticks.
4'cript/ examp"e01b.py" graph/ examp"e01b.png6
For e.aple" to set .%ticks e#ery 0.2( rather than e#ery 0.( we coul! say
(922
pyp"ot.xticks(00.256k .or k in range(!4$5*1*
where we use +ython7s <list coprehension= synta./
777 [0.25*k for k in range(!"5#$
0!1.0$ !0.35$ !0.5$ !0.25$ 0.0$ 0.25$ 0.5$ 0.35$ 1.01
1f we really wante! to we coul! ha#e arbitrary ticks/
pyp"ot.yticks(0!0.8$ !0.4$ 0.0$ 0.2$ 0.9$ 0.:51*
4'cript/ examp"e01c.py" graph/ examp"e01c.png6
This is not copletely pointless. The specific #alues ight correspon! to
critical points in soe theory" in which case you ight want to label the as
such. The pyp"ot.xticks(* an! pyp"ot.yticks(* functions take an
optional secon! arguent which is a list of labels to attach to the tick arks
instea! of their nuerical #alues.
:e can nae the ticks like this/
pyp"ot.yticks(0!0.8$ !0.4$ 0.0$ 0.2$ 0.9$ 0.:51$
0/;"pha/$/<eta/$/=amma/$/+e"ta/$/>psi"on/$/?eta/1*
4'cript/ examp"e01d.py" graph/ examp"e01d.png6
)etting the title
By !efault the graph coes with no title.
There is a function pyp"ot.tit"e(* which sets a title. The title is &ust a siple te.t string which can
contain ultiple lines but !oes not nee! to en! with a new line character.
pyp"ot.tit"e(/y - x cubed@n.rom x-!1 to x-1/*
4'cript/ examp"e01e.py" graph/ examp"e01d.png6
Aote that the title goes abo#e the bo. an! is centre%aligne!.
There is an optional arguent on pyp"ot.tit"e(*"
horiAonta"a"ignment-5 which can takes the string #alues /"e.t/"
/center/" or /right/. This sets the title te.t7s alignent relati#e to the
centre of the figure.
4Files/ examp"e01..py" examp"e01g.py" examp"e01h.py for <left=" <center= an! <right= respecti#ely.6
1n a!!ition to horiHontal alignent we can also control the #ertical alignent with the
vertica"a"ignment-5 paraeter. 1t can take one of four string #alues/ /top/" /center/" /bottom/"
an! /base"ine/ 4the !efault6.
4Files/ examp"e01i.py" examp"e01j.py" examp"e01k.py for <top=" <center= an! <botto= respecti#ely"
with the correspon!ing graphs in examp"e01i.png" examp"e01j.png" examp"e01k.png.6
*922
If course" the title woul! benefit fro proper atheatical notationJ <yK.
3
= woul! look uch better than
<y K . cube!=. To support this" matp"ot"ib supports a subset of T
e
L7s synta.
3
if the te.t is enclose! in
!ollar signs 4also fro T
e
L6/
pyp"ot.tit"e(/$y - xBC2D$@n$!1ExE1$/*
4'cript/ examp"e01".py" graph/ examp"e01".png6
This atheatical notation can be use! in any of pyp"ot7s te.t functions.
*abelling the a!es
By !efault the a.es are unlabelle!. 4Don7t confuse this with the in!i#i!ual
tick arks being unlabelle!.6
There are functions" pyp"ot.x"abe"(* an! pyp"ot.y"abe"(*" which set the labels on the two a.es.
pyp"ot.x"abe"(/$!1ExE1$/*
pyp"ot.y"abe"(/$y-xBC2D$/*
4'cript/ examp"e01m.py" graph/ examp"e01m.png6
Aote that the te.t of the y%a.is label is rotate! to atch the a.is. 3se
pyp"ot.y"abe"(/$y-xBC2D$/$ rotation-/horiAonta"/*
to write horiHontally. The alternati#e" <rotation-/vertica"/= is the
!efault. 4'ee the script examp"e01n.py an! its correspon!ing graph examp"e01n.png for an e.aple.6
+$$ing a legen$
The last piece of labelling that ight be re0uire! is a legen!. This i!entifies the cur#e an! is typically ore
use when there are ultiple cur#es on the graph. For copleteness" though" we will show it here.
The best approach to creating a legen! is to attach te.t to the lines as they are plotte! with pyp"ot.p"ot(*
using an optional "abe"-5 paraeter. This !oes not" in itself" a!! any te.t to the plotte! graph but rather
akes the te.t a#ailable for other routines to use. Ine of those routines is pyp"ot."egend(* which plots a
legen! bo. using the label inforation store! with the lines. This function ust be calle! after any lines are
plotte!.
pyp"ot."ine - pyp"ot.p"ot(x$y$ "abe"-/x cubed/*
pyp"ot."egend(*
4'cript/ examp"e01o.py" graph/ examp"e01o.png6
Aote that the figure appears in the top right corner by !efault" obscuring part
of our line. :e can change its position by a!!ing a nae! paraeter"
"oc-5" to our call to pyp"ot."egend(* specifying where the legen!
shoul! go.
3 T
e
L is a atheatical typesetting syste !e#elope! by Donal! >nuth.
,922
pyp"ot."ine - pyp"ot.p"ot(x$y$ "abe"-/x cubed/*
pyp"ot."egend("oc-/upper "e.t/*
4'cript/ examp"e01p.py" graph/ examp"e01p.png6
The "oc-5 paraeter can takes either a te.t or an integer #alue fro the
following set/
,e!t Number
best 0
upper right 1
upper left 2
lower left 3
lower right 4
right (
center left * K left
center right , K right
lower center -
upper center M
center 10
:e can also attach a title to the legen! with the tit"e-5 paraeter in the
pyp"ot."egend(* function/
pyp"ot."egend(tit"e-/Fhe "egend/*
4'cript/ examp"e01%.py" graph/ examp"e01%.png6
:e can use "oc-5 an! tit"e-5 in the sae callJ they are 0uite
in!epen!ent.
)etting the lines properties
:hen we start plotting ultiple lines we will see lines of #arious colours. For now" we will change the colour
of the single line we are !rawing. :e also obser#e that it is a line. :e ight want to see the specific points"
arke! with !ots or crosses etc.
:e set these properties of the line in the sae way as we set the te.t label property of the line/ with the
pyp"ot.p"ot(* function. This tie we see the properties ie!iately in the line itself" though.
There is an optional foratting paraeter which specifies the colour an! style of the !ata plot with a single
string. This can get to be a cople. little icro%language all of its own. There is an easier" though ore long%
win!e!" way to !o it using a set of nae! paraeters. These paraeters can specify colour" arker style
4line" points" crosses" 56" an! line wi!th.
For e.aple/
pyp"ot.p"ot(x$y$ co"or-/green/$ "inesty"e-/dashed/$
"ineidth-5.0*
4'cript/ examp"e01r.py" graph/ examp"e01r.png6
Aote the 2erican spelling of <color=. Folour can be specifie! by nae"
single character abbre#iate! nae or in he.a!ecial CEB forat as
<GHH==<<=.
The line wi!th is specifie! in points.
-922
The line style can be i!entifie! by a wor! or a short co!e. The basic line styles are these/
Name 'o$e
so"id !
dashed !!
dotted ,
Ione
(empty string)
The nae! colours are these/
*ong form )ingle letter
red r
green g
b"ue b
cyan c
magenta m
ye""o y
b"ack k
hite
:e !on7t ha#e to ha#e a line at all. For scatter plots 4which we will re#iew below6 we want to turn off the line
altogether an! to ark the 4."y6 !ata points in!i#i!ually.
)etting the graphs file format
'trangely" changing the iage7s file forat is one of the har!er things to !o. The matp"ot"ib syste has a
nuber of <back en!s= that generate its final output. To output files in a !ifferent forat we ha#e to select the
appropriate back en! at the #ery start of the script 4before any graphical work is !one6 an! then use
pyp"ot.save.ig(* to sa#e a file with a correspon!ing file nae suffi. 4<.png=" <.svg= etc.6 at the en!.
To pick a back en! we ha#e to iport the matp"ot"ib o!ule itself an! use its matp"ot"ib.use(*
function to i!entify the back en! to use. :e ust !o this before iporting matp"ot"ib.pyp"ot.
4'cript/ examp"e01t.py6/
import matp"ot"ib
matp"ot"ib.use(/JK=/*
import matp"ot"ib.pyp"ot as pyp"ot
2t the top of the script" an!
pyp"ot.save.ig(/examp"e01t.svg/*
at the botto.
!ercise -
Cecreate this graph. You ay start with the file
exercise01.py which will take care of
inclu!ing the !ata for you.
1f the graph is printe! here in greyscale you can
see the target graph in the file
exercise01a.png. The cur#e is re! an! is
2Npt wi!e.
In the achines use! for these courses the three a#ailable back en!s are
the !efault" which sa#es +AE files"
an 'OE back en!" as illustrate! abo#e" an!
a +DF back en! for generating +DF files" examp"e1.pd. etc.
M922
.ultiple graphs on a single set of a!es
To !ate we ha#e plotte! a single cur#e in our graphs. Ae.t we are going to plot ultiple cur#es. :hen we
coe on to plot !ifferent types of graph e.actly the sae approach will apply to the as to ultiple siple
cur#es.
:e will start with a single graph. The +ython script examp"e02a.py plots
the first Fhebyshe# polynoial" which is spectacularly !ull. The !ata for this
graph is in p"otdata.data02ya an! we !raw the graph with
pyp"ot.p"ot(p"otdata.data02x$ p"otdata.data02ya$
"abe"-/$FLC1D(x*$/*
4'cript/ examp"e02a.py" graph/ examp"e02a.png6
The array p"otdata.data02yb contains the !ata for the secon!
Fhebyshe# polynoial" an! p"otdata.data02yc for the thir!. The script examp"e02b.py siply runs
three pyp"ot.p"ot(* functions one after the other/
pyp"ot.p"ot(p"otdata.data02x$ p"otdata.data02ya$ "abe"-/$FLC1D(x*$/*
pyp"ot.p"ot(p"otdata.data02x$ p"otdata.data02yb$ "abe"-/$FLC2D(x*$/*
pyp"ot.p"ot(p"otdata.data02x$ p"otdata.data02yc$ "abe"-/$FLC2D(x*$/*
an! gi#es us the graph we want.
4'cript/ examp"e02b.py" graph/ examp"e02b.png6
:e can a!&ust the properties of these lines by a!!ing paraeters to the
pyp"ot.p"ot(* function calls &ust as we !i! with in!i#i!ual lines.
The !efault colour se0uence is gi#en
here. 4Though the lines arenDt uch use
if this han!out is printe! in in
greyscale86 The colours start fro blue
again if you plot eight or ore cur#es.
2lso note that it !oesnDt atter if later
graphs ha#e !ifferent !ata rangesJ the
actual calculation of the a.es is
!eferre! until the graph is create! with
pyp"ot.save.ig(*. The script
examp"e02c.py e.ten!s outsi!e the
range 1<x<1 an! the y%a.es scale to
the largest nubers seen.
4'cript/ examp"e02c.py" graph/ examp"e02c.png6
!ercise /
Cecreate this graph. You ay start with the file
exercise02.py which will take care of
inclu!ing the !ata for you.
1f the graph is printe! here in greyscale you can
see the target graph in the file
exercise02a.png.
10922
Parametric graphs
To !ate our .%a.es ha#e all been onotonically increasing fro the lower boun! to the upper boun!. There is
no obligation for that to be the case" thoughJ the cur#e siply connects the 4."y6 points in or!er.
!ercise 3
Cecreate this graph. $ere we plot two of the
!ifferent <y%#alue= !atasets against each other.
You ay start with the file exercise02.py
which will take care of inclu!ing the !ata for you.
The target graph is in the file
exercise02a.png.
+lease !o play with other cobinations of
Fhebyshe# polynoials. The !ata is pro#i!e! for T1(x) to T7(x) in
p"otdata.data02ya to p"otdata.data02yg.
)catter graphs
Get7s !o away with the cur#e altogether an! plot the pure !ata points. :e will re#isit the pyp"ot.p"ot(*
function an! see soe ore paraeters to turn off the line entirely an! specify the point arkers. To !o this
we ha#e to !o two things/ turn off the line an! turn on the arkers we will use for the points.
:e can !o this with the pyp"ot.p"ot(* function/
x - p"otdata.data04x
y - p"otdata.data04yb
pyp"ot.p"ot(x$ y$ "inesty"e-//$ marker-/o/*
4'cript/ examp"e04a.py" graph/ examp"e04a.png6
The line is turne! off by setting the "inesty"e-5 paraeter to the epty
string.
There is a con#enience function" pyp"ot.scatter(*" which !oes this autoatically.
pyp"ot.scatter(x$ y*
4'cript/ examp"e04b.py" graph/ examp"e04b.png6
The pyp"ot.scatter(* function is not as fle.ible as pyp"ot.p"ot(*"
though" an! we will continue to use the ore general coan!.
The ost coon set of changes wante! with a scatter graph relate to the
selection of the arker. The !efault arker is a fille! circle. For any shape
of arker we ha#e three or four paraeters we ight want to change an!
each of these has a correspon!ing paraeter in the call to pyp"ot.p"ot(*/
the siHe of the arker as a whole
markersiAe-5
the colour of the area insi!e the arker 4for those shapes that enclose an area6
marker.aceco"or-5
the wi!th of the line that fors the arker7s perieter
markeredgeidth-5
the colour of the line that fors the arker7s perieter
markeredgeco"or-5
The markersiAe-5 an! markeredgeidth-5 paraeters take a floating point nuber which is the
!iension in points. The marker.aceco"or-5 an! markeredgeco"or-5 paraeters take any of the
colour naes or co!es that worke! for lines.
The following script uses all four paraeters/
11922
pyp"ot.p"ot(x$ y$ "inesty"e-//$ marker-/o/$
markersiAe-15.0$ markeredgeidth-5.0$
marker.aceco"or-/green/$ markeredgeco"or-/red/*
4'cript/ examp"e04c.py" graph/ examp"e04c.png6
The matp"ot"ib syste supports a wi!e #ariety of arkers" inclu!ing
soe you can !efine yoursel#es. The pre%!efine! ones are gi#en in the
following table/
4File/ markers.png6
For scatter graphs in#ol#ing large aounts of !ata" howe#er" large arkers are inappropriate an! the graph
uses points on the graph to in!icate !ata points. For this the /$/ arker P a single pi.el P is ost
appropriate. 4Aote that this takes the marker.aceco"or paraeter to !efine its colour.6
The script examp"e04d.py !raws a scatter graph with 10"000 blue pi.els/
x - p"otdata.data04u
y - p"otdata.data04v
pyp"ot.p"ot(x$ y$ "inesty"e-//$ marker-/$/$
marker.aceco"or-/b"ue/*
4'cript/ examp"e04d.py" graph/ examp"e04d.png6
The proble with pi.els is that they can be too sall. :here the transition
between marker-/$/ an! marker-/./ falls !epen!s on your !ata.
!ercise 0
The script exercise04.py runs soe iterations
o#er an initial set of points an! then nee!s to plot
the resultant points as a series of scatter graphs
on the sae a.es. The coents in the script
e.plain what you nee! to write +ython for.
You shoul! get a graph like this
4exercise04a.png6
Feel free to play with other paraeter #alues.
12922
rror bars
).periental !ata points" whether !rawn as lines or points typically coe with error bars to in!icate the
uncertainties in the !ata. These error bars can be syetric or asyetric an! can be in &ust the
y%coor!inate or in both the .% an! y%coor!inate.
:e will start with a graph with asyetric error bars in the y%coor!inate but no error bars for ..
The pyp"ot o!ule contains a function pyp"ot.errorbar(* which has the sae arguents as
pyp"ot.p"ot(* but with soe a!!itional ones for plotting the error bars. Because of this it can be use! for
scatter graphs with error bars by turning off the line 4"inesty"e-//6. 1n its siplest for we can use it &ust
as we use pyp"ot.p"ot(*/
x - p"otdata.data05x
y - p"otdata.data05y
pyp"ot.errorbar(x$y*
4'cript/ examp"e05a.py" graph/ examp"e05a.png6
Ib#iously" we want to a!! soe error bars to this. :e can a!! the error
bars with the yerr-5 paraeter. This takes a pair of #alues"
yerr-(yminus$yp"us*. )ach #alue is a list of errors" as long as the . an! y lists. 1n each case the error
#alue is positi#e an! represents the offset of the error bar fro the base cur#e.
To ake it clear" consi!er the following e.aple where the yminus list is 00.25$ 0.25 M$ 0.251 an! the
yp"us list is 00.5$ 0.5$ M$ 0.51/
ha". - p"otdata.data05ha".
%uarter - p"otdata.data05%uarter
pyp"ot.errorbar(x$y$ yerr-(%uarter$ha".**
4'cript/ examp"e05b.py" graph/ examp"e05b.png6
Future e.aples will use rather ore realistic error !ata/
yminus - p"otdata.data05ym
yp"us - p"otdata.data05yp
pyp"ot.errorbar(x$y$ yerr-(yminus$yp"us**
4'cript/ examp"e05c.py" graph/ examp"e05c.png6
There are a few aspects of these error bars that users typically want to
change/
the colours of the error bars"
the wi!th of the error bars" an!
the wi!th of the caps on the error bars.
To set the colour of the error bar" pyp"ot.errorbar(* supports a paraeter eco"or-5 to o#erri!e the
error bars ha#ing the sae colour as the ain cur#e/
pyp"ot.errorbar(x$y$ yerr-(yminus$yp"us*$
eco"or-/green/*
4'cript/ examp"e05d.py" graph/ examp"e05d.png6
The 4blue6 !ata cur#e is !rawn in front of the 4green6 error bars. There is no
paraeter to ake the upper an! lower error bars !ifferent colours.
13922
The e"ineidth-5 paraeter sets the wi!th of the error bar line an! is easure! in points an! gi#en as a
floating point nuber. 1f the paraeter is not gi#en then the sae wi!th is use! for the error bar as for the
ain cur#e.
pyp"ot.errorbar(x$y$ yerr-(yminus$yp"us*$
e"ineidth-20.0*
4'cript/ examp"e05e.py" graph/ examp"e05e.png6
Aote that the caps on the error bars are not wi!ene! proportionately to the
wi!th of the error bar itself. That wi!th ust be separately !efine! an! the
pyp"ot.errorbar(* function supports the capsiAe-5 paraeter to !o
that. This specifies the length of the cap line in pointsJ the wi!th of the cap
line cannot be set. 'etting capsiAe-0 eliinates the cap altogether.
pyp"ot.errorbar(x$y$ yerr-(yminus$yp"us*$ capsiAe-20.0*
4'cript/ examp"e05..py" graph/ examp"e05..png6
The cap line is always !rawn in the sae colour as the error bar line itself.
2s a 4rather gau!y6 e.aple of cobining the ain pyp"ot.p"ot(*
paraeters with the error bar%specific paraeters" consi!er the following
e.aple that !raws a (pt re! !ashe! !ata line" re! an! blue !ata point
arkers" an! 10pt error bars without caps in black/
pyp"ot.errorbar(x$y$ yerr-(yminus$yp"us*$
"inesty"e-/dashed/$ co"or-/red/$ "ineidth-5.0$
marker-/o/$ markeredgeco"or-/red/$ markeredgeidth-5$
marker.aceco"or-/hite/$ markersiAe-15$
eco"or-/b"ack/$ e"ineidth-10.0$ capsiAe-0*
4'cript/ examp"e05g.py" graph/ examp"e05g.png6
:e often want error bars in the .%!irection as well as the y%!irection. The pyp"ot.errorbar(* function
has an xerr-5 paraeter which beha#es in e.actly the sae way as yerr-5/
xminus - p"otdata.data05xm
xp"us - p"otdata.data05xp
pyp"ot.errorbar(x$y$ xerr-(xminus$xp"us*$
yerr-(yminus$yp"us**
4'cript/ examp"e05h.py" graph/ examp"e05h.png6
The line can be suppresse! with "inesty"e-// as usual.
The settings for the error bar lines 4colour" wi!th" cap siHe" etc.6 ust be the
sae in both !irections.
!ercise 1
The script exercise05.py sets up soe !ata
for a graph like this with <inner= an! <outer= error
ranges 4e.g. for 0uartiles an! e.trea6.
:rite the pyp"ot.errorbar(* lines to
generate the graph shown.
14922
Polar graphs
Aot all graphs want orthogonal a.es" x an! y. Fyclical !ata is typically !rawn on polar a.es" an! r. The
pyp"ot o!ule pro#i!es a function pyp"ot.po"ar( $r$5* which is takes e.actly the sae arguents
as pyp"ot.p"ot(x$y$5* but !raws a polar graph. The list of #alues ust be in ra!ians.
!
'oe of the polar plotting functions isbeha#e when the #alues of r are negati#e.
1t is better to a#oi! negati#e #alues altogether.
:hile we can get away without it in certain circustances" it is a goo! i!ea to let pyp"ot know that we are
going to be working with polar a.es rather than orthogonal ones as early in the process as possible. :e !o
this with a function call
pyp"ot.axes(po"ar-Frue*
The !efault is Na"se an! is what we ha#e been using for our pre#ious graphs.
The +ython script examp"e09a.py plots a graph of r=t for 0<<. The laying !own of the line is !one with
this pyp"ot.po"ar(* coan!/
t - p"otdata.data09t
r - p"otdata.data09r
pyp"ot.po"ar(t$r*
4'cript/ examp"e09a.py" graph/ examp"e09a.png.6
2s with the orthogonal a.is graphs" there are a nuber of properties we
ight want to change/
the line paraeters 4colour" style" points rather than lines6"
the angular position of the ra!ial labels 4which !efaults to 22NQ
abo#e the horiHontal 0Q line6"
the ra!ial labels 41" 2" 5" ,6"
the angular labels 4which !efault to e#ery 4(Q an! are labelle! in !egrees6"
the !otte! polar gri!.
:e will work through these as we !i! for the orthogonal graphs.
*ine parameters
The properties of the !ata line can be set with e.actly the sae paraeters as are use! for
pyp"ot.p"ot(*/
"inesty"e
'tyle of the line. 3se // for no line.
"ineidth
:i!th of the line in points.
co"or
Folour of the line. n.b. 3'2 spelling.
marker
'election of the !ata point arker.
markersiAe
'iHe of the !ata point arker in points.
markeredgeidth
:i!th of the line !rawing the arker.
markeredgeco"or
Folour of the line !rawing the arker.
marker.aceco"or
Folour of the area within the arker if any.
'o" if we go o#erboar! for illustrati#e purposes we coul! !efine a plot like
this/
pyp"ot.po"ar(t$r$ "inesty"e-/dashed/$ "ineidth-2.5$
co"or-/red/$ marker-/./$ markersiAe-10.0$
markeredgeco"or-/b"ue/$ markeredgeidth-1.5$
marker.aceco"or-/green/*
1(922
4'cript/ examp"e09b.py" graph/ examp"e09b.png.6
,he angular gri$ lines an$ their labels
The pyp"ot.thetagrids(* function controls the position an! labels of the lines running fro the centre to
the e!ge of the graph. This allows us to set the necessary properties/
what angles the lines shoul! be at"
what their labels shoul! be"
how far out their labels shoul! be.
:e specify the angular position of the ra!ial lines with the function7s
copulsory arguent of a list of #alues as its arguent.
pyp"ot.thetagrids(00.0$ 80.0$ 1:0.0$ 230.01*
4'cript/ examp"e09c.py" graph/ examp"e09c.png.6
!
The angles are specifie! in !egrees.
Yes" this is inconsistent with pyp"ot.po"ar(* 8
There are two ways to specify the labels appearing at the en!s of the lines. 1f neither is use! then you get the
!egree #alues as seen in the graphs abo#e.
You can specify a "abe"s-5 paraeter &ust as we !i! with the tick arks on orthogonal graphs. This takes
a list of te.t ob&ects an! ust ha#e the sae length as the list of angles.
For e.aple <"abe"s-0/>/$ /I/$ /O/$ /J/1=.
'o we coul! label the graph in our running e.aple as follows/
pyp"ot.thetagrids(00$ 80$ 1:0$ 2301$
"abe"s-0/>/$ /I/$ /O/$ /J/1*
4'cript/ examp"e09d.py" graph/ examp"e09d.png.6
Finally we can change the position of the labels. :e specify their position
relati#e to the position of the outer ring with a paraeter .rac-5. This
gi#es their ra!ial !istance as a fraction of the outer ring7s ra!ius an! !efaults
to a #alue of 1.1. 2 #alue less than 1.0 puts the labels insi!e the circle/
pyp"ot.thetagrids(00$ 80$ 1:0$ 2301$
"abe"s-0/>/$ /I/$ /O/$ /J/1$ .rac-0.8*
4'cript/ examp"e09e.py" graph/ examp"e09e.png.6
,he concentric gri$ lines an$ their labels
The pyp"ot.rgrids(* function is the e0ui#alent of
pyp"ot.thetagrids(* for the concentric circles 4labelle! 1 to , in our graphs so far6.
1n its siplest use it specifies the ra!ii of the circles as a list of #alues/
pyp"ot.rgrids(02.0$ 4.0$ 9.0$ :.01*
4'cript/ examp"e09..py" graph/ examp"e09..png.6
1*922
!
Aote that we !on7t get a ring at r=".08
The polar graph only e.ten!s out as far as the !ata.
Yes" this is a bug.
:e can e.plicitly set the outer liit of the rings" but we ha#e to e.pose the inner workings of pyp"ot to !o it.
1nternally" pyp"ot treats as an x%coor!inate an! r as a y%coor!inate. :e can e.plicitly set the upper #alue
of r with this line/
pyp"ot.y"im(ymax-:.0*
'o the following lines gi#e us the graph we want/
pyp"ot.y"im(ymax-:.0*
pyp"ot.rgrids(02.0$ 4.0$ 9.0$ :.01*
4'cript/ examp"e09g.py" graph/ examp"e09g.png.6
:e can set our own labels for these #alues in the sae way as for the ra!ial
gri!/
pyp"ot.y"im(ymax-:.0*
pyp"ot.rgrids(01.53$ 2.14$ 4.31$ 9.2:1$ "abe"s-0/P/2/$
/P/$ /2P/2/$ /2P/1*
4'cript/ examp"e09h.py" graph/ examp"e09h.png.6
For those of you not cofortable with !irect use of non%keyboar! characters
you can get the ore atheatical #ersion with the R5R notation/
pyp"ot.y"im(ymax-:.0*
pyp"ot.rgrids(01.53$ 2.14$ 4.31$ 9.2:1$
"abe"s-0/$@pi/2$/$ /$@pi$/$ /$2@pi/2$/$ /$2@pi$/1*
4'cript/ examp"e09i.py" graph/ examp"e09i.png.6
There is also a control o#er the angle at which the line of labels is !rawn. By
!efault it is 22NQ abo#e the =0 line" but this can be a!&uste! with the
ang"e-5 paraeter/
pyp"ot.y"im(ymax-:.0*
pyp"ot.rgrids(01.53$ 2.14$ 4.31$ 9.2:1$
"abe"s-0/P/2/$ /P/$ /2P/2/$ /2P/1$ ang"e-!22.5*
4'cript/ examp"e09j.py" graph/ examp"e09j.png.6
2ngle takes its #alue in !egrees.
!ercise 2
The script exercise09.py sets up soe !ata
for this graph. :rite the pyp"ot lines to
generate the graph shown.
4The cur#e is r=sin
#
($).6
1,922
3istograms
!
For the purposes of this tutorial we are going to be pe!antic about the !ifferent
!efinitions of histogras an! bar charts.
2 histogram counts how any !ata ites fit in ranges known as <bins=.
2 bar chart is siply a set of y%#alues arke! with #ertical bars rather than by
points or a cur#e.
The basic pyp"ot function for histogras is pyp"ot.hist(* an! it works with raw !ata. You !o not gi#e it
fifty #alues 4say6 an! ask for those heights to be plotte! as a histogra. 1nstea! you gi#e it a list of #alues
an! tell it how any bins you want the histogra to ha#e.
The siplest use of the function is this/
data - p"otdata.data03
pyp"ot.hist(data*
4'cript/ examp"e03a.py" graph/ examp"e03a.png.6
Aote that the !efaults pro#i!e for ten bins" an! blue bo.es with black
bor!ers. :e will a!&ust these shortly.
:e can a!&ust the liits of the a.es in the usual way/
pyp"ot.axis(0!10.0$ 10.0$ 0.0$ 2501*
pyp"ot.hist(data*
4'cript/ examp"e03b.py" graph/ examp"e03b.png.6
'osmetic changes
:e will start with the cosetic appearance of the histogra.
:e can set the colour of the bo.es with the co"or-5 paraeter/
pyp"ot.hist(data$ co"or-/green/*
4'cript/ examp"e03d.py" graph/ examp"e03d.png.6
4There is no examp"e03c.pyJ you ha#enDt skippe! it by istake.6
:e can set the wi!th of the bars with the ridth-5 paraeter. This sets
the wi!th of the bar relati#e to the wi!th of the bin. 'o it takes a #alue
between 0 an! 1. 2 #alue of 0.,( woul! gi#e bars that spanne! three
0uarters of the wi!th of a bin/
pyp"ot.hist(data$ ridth-0.35*
4'cript/ examp"e03e.py" graph/ examp"e03e.png.6
:e can also ha#e the bars run horiHontally.
1-922
The pyp"ot.hist(* function has an orientation-5 paraeter. There are two accepte! #ales/
/vertica"/ an! /horiAonta"/.
pyp"ot.hist(data$ orientation-/horiAonta"/*
4'cript/ examp"e03g.py" graph/ examp"e03g.png.6
)etting the bins
The nuber of bins in the histogra is set with the bins-5 paraeter. 1n
its siplest for it can be an integer" specifying the nuber of bins to use/
pyp"ot.hist(data$ bins-20*
4'cript/ examp"e03h.py" graph/ examp"e03h.png.6
2lternati#ely we can specify e.actly what the bins shoul! be. To !o this we
specify the boun!aries of the bins" so for % bins we nee! to specify %&1
boun!aries/
pyp"ot.hist(data$
bins-0!2.0$ !2.0$ !1.0$ 0.0$ 1.0$ 2.0$ 2.01*
4'cript/ examp"e03i.py" graph/ examp"e03i.png.6
Aote that any !ata that lies outsi!e the boun!aries is ignore!.
Plotting multiple $ata sets
:e can plot ultiple histogras with repeate! calls to pyp"ot.hist(* but
a easure of care is calle! for. )ach call calculates its own bin siHes so if
the siHes of the !atasets are too !ifferent one set of bars can be noticeably
wi!er than the others/
pyp"ot.hist(data0,3501$ ridth-0.5*
pyp"ot.hist(data0350,1$ ridth-0.5*
4'cript/ examp"e03..py" graph/ examp"e03..png.6
2t a iniu you shoul! set the bins e.plicitly. There is" howe#er" a better way to !o it.
Because repeate! calls to pyp"ot.hist(* can pro#e so probleatic the
function can take a list of !atasets 4not necessarily all of the sae siHe6 an!
plot the together/
pyp"ot.hist(0data0,3501$ data0350,11*
4'cript/ examp"e03j.py" graph/ examp"e03j.png.6
1f it is plotting ultiple histogras the bin siHes are base! on the union of all
the !atasets. The wi!ths of the blocks are autoatically scale! !own to fit
the bars alongsi!e each other with a thin gap between the.
The pyp"ot.hist(* function pro#i!es a way to pro#i!e ultiple !atasets
as <stacke!= histogras. This is enable! with the histtype-5 paraeter
which specifies what type of histogra we want. To !ate" all our histogras
ha#e use! the !efault histtype-/bar/ setting. 1f we change this to
histtype-/barstacked/ we get the secon! !ataset abo#e the first/
1M922
pyp"ot.hist(0data0,3501$ data0350,11$ histtype-/barstacked/*
4'cript/ examp"e03k.py" graph/ examp"e03k.png.6
1f you use a list of !atasets then you can use a list of colours with co"or-5
too/
pyp"ot.hist(0data0,3501$ data0350,11$
co"or-0/red/$ /ye""o/1*
4'cript/ examp"e03".py" graph/ examp"e03".png.6
!ercise 4
The script exercise03.py sets up soe !ata
for this graph. :rite the pyp"ot lines to
generate the histogra shown.
4Ereen is data1" yellow is data2" an! re! is
data2.6
5ar charts
!
Cecall that we are being pe!antic about the !ifferent !efinitions of histogras an!
bar charts.
2 histogram counts how any !ata ites fit in ranges known as <bins=.
2 bar chart is siply a set of uniforly space! y%#alues arke! with #ertical bars
rather than by points or a cur#e.
The basic pyp"ot function for !rawing bar charts is pyp"ot.bar(*.
1n its siplest use it takes a series of .% an! y%#alues" &ust like
pyp"ot.p"ot(*/
x - p"otdata.data0:x
y - p"otdata.data0:y
pyp"ot.bar(x$y*
4'cript/ examp"e0:a.py" graph/ examp"e0:a.png.6
Technically" the .%#alues are the #alues at the left e!ge of the bar. 1n the e.aple shown the .%#alues run
fro 1 to 10 inclusi#e. The left%ost bar starts at .K1 an! the right%ost one starts at .K10.
:e can change this with the a"ign-5 paraeter. This can take two
#alues/ a"ign-/edge/" which is the !efault" or a"ign-/center/ which
centres the bar on the .%#alue/
pyp"ot.bar(x$y$ a"ign-/center/*
4'cript/ examp"e0:b.py" graph/ examp"e0:b.png.6
The bars !efault to ha#ing a wi!th of 0.-. The wi!th can be change! with the
paraeter idth-5/
pyp"ot.bar(x$y$ idth-0.25*
4'cript/ examp"e0:c.py" graph/ examp"e0:c.png.6
20922
:e can also set the wi!ths of each bar in!epen!ently by passing a list of
#alues. This list ust be the sae length as the .% an! y%#alue lists/
"ist - p"otdata.data0:
pyp"ot.bar(x$y$ idth-"ist*
4'cript/ examp"e0:d.py" graph/ examp"e0:d.png.6
#n$icating ranges with bar charts
2s well as #arying with wi!ths of the bars we can also #ary their bases" or <bottos= as pyp"ot calls the.
This can be #ery useful for showing ranges of #alues an! coul! be use!" for e.aple" to in!icate ranges of
#alues either siHe of a line or scatter graph !rawn with pyp"ot.p"ot(*.
For e.aple" if we ha#e arrays of upper an! lower #alues we can !o this/
pyp"ot.bar(x$upper$ bottom-"oer*
4'cript/ examp"e0:i.py" graph/ examp"e0:i.png.6
'osmetic changes to bar charts
:e can set the colour of the bars with co"or-5" taking the usual nae!
#alues. :e can set the colour of the lines aroun! the bars an! the wi!ths of
those lines with edgeco"or-5 an! "ineidth-5 respecti#ely/
pyp"ot.bar(x$y$ co"or-/green/$ edgeco"or-/red/$
"ineidth-5.0*
4'cript/ examp"e0:e.py" graph/ examp"e0:e.png.6
+lotting ultiple !atasets on a single graph re0uires soe finesse. ;ultiple calls to pyp"ot.bar(* siply
superiposes the graphs. :hile this ight work for line graphs or scatter graphs it is no use for bar graphs.
1nstea!" we call pyp"ot.bar(* ultiple ties an! use the idth-5 paraeter to narrow the bars. Then
we e.plicitly offset the .%#alue for each !ataset so that the bars !o not o#erlap.
!
+eople using plain +ython lists ha#e to generate new lists of offset .%#alues for
this purpose. +eople using Au+y arrays ha#e a short cut. :e will !o each in
turn. Cea!ers unfailiar with Au+y arrays can siply skip that bit with no
ipact on their ability to create bar charts.
:e will plot three !atasets in parallel" with each bar being S wi!th" lea#ing a thin gap between sets. Both
scripts below pro!uce the sae graph/
.ultiple bar charts using Python lists
3sing +ython lists we ha#e to create new .%#alue lists. The siplest way to !o this is with the bit of syntactic
sugar calle! a <list coprehension= that we et earlier when we set the tick arks.
x1 - p"otdata.data0:x
x2 - 0 x Q 0.25 .or x in x1 1
x2 - 0 x Q 0.50 .or x in x1 1
y1 - p"otdata.data0:y1
y2 - p"otdata.data0:y2
y2 - p"otdata.data0:y2
21922
pyp"ot.bar(x1$y1$ idth-0.25$ co"or-/b"ue/*
pyp"ot.bar(x2$y2$ idth-0.25$ co"or-/green/*
pyp"ot.bar(x2$y2$ idth-0.25$ co"or-/red/*
4'cript/ examp"e0:g.py" graph/ examp"e0:g.png.6
.ultiple bar charts using NumPy arrays
1f we use Au+y arrays then we can create the offset #ersions with a sipler e.pression. )#erything else is
the sae/
import numpy
x1 - numpy.array(p"otdata.data0:x*
x2 - x1 Q 0.25
x2 - x2 Q 0.50
y1 - p"otdata.data0:y1
y2 - p"otdata.data0:y2
y2 - p"otdata.data0:y2
pyp"ot.bar(x1$y1$ idth-0.25$ co"or-/b"ue/*
pyp"ot.bar(x2$y2$ idth-0.25$ co"or-/green/*
pyp"ot.bar(x2$y2$ idth-0.25$ co"or-/red/*
4'cript/ examp"e0:h.py" graph/ examp"e0:h.png.6
If course" if we were using Au+y arrays we woul! usually ha#e Au+y arrays for the y%#alues too.
!ercise 6
The script exercise0:.py sets up soe !ata
for this graph. :rite the pyp"ot lines to
generate the bar chart shown.
22922

You might also like