python graphs

Upload: aswathy-cj

Post on 01-Jun-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 Python Graphs

    1/22

    Python 3: Plotting simple graphsBruce [email protected]

    Bob Dowling [email protected]

    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 firstthree 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 eercises/

  • 8/9/2019 Python Graphs

    2/22

    Prerequisites

    This self%pace! course assues that you ha#e a knowle!ge of +ython 3 eui#alent to ha#ing coplete! oneor other of

    +ython 3/ ntro!uction for bsolute Beginners" or

    +ython 3/ ntro!uction for Those with +rograing )perience

    'oe eperience beyon! these courses is always useful but no other course is assue!.

    The course also assues that you know how to use a ni tet e!itor gedit" emacs" vi" 56.

    !The +ython o!ule use! in this course is built on top of the nuerical pythono!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 oneplace" in the bar charts chapter" where using numpyakes life

    uch easier" an! we will !o it both ways. You can safely skip the numpyway 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!ylogge! in with course Ds an! ha#e hoe !irectories specially prepare!. +lease !o not log in un!erany other D.

    These courses are hel! in a roo with two !eonstrators. f you get stuck or confuse!" or if you &ustha#e a uestion raise! by soething you rea!" please ask8

    The hoe !irectories contain a nuber of sub!irectories one for each topic. For this topic pleaseenter !irectory graphs. ll work will be coplete! there/

    $ cd graphs

    $ pwd

    /home/x250/graphs

    $

    t the en! of this session the hoe !irectories will be cleare!. ny 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 atmatp"ot"ib.org/1.2.0/index.htm"

    2922

  • 8/9/2019 Python Graphs

    3/22

    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 eiusmodtempor 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. Bol! face" typewriter font.6

    The aterial the coputer respon!s with is presente! like this/ eys on the keyboar! will be shown as the sybol on the keyboar! surroun!e! by suare brackets" so the

  • 8/9/2019 Python Graphs

    4/22

    !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!

  • 8/9/2019 Python Graphs

    5/22

    $ eog example01.png &

    1 553

    $

    This eaple runs eogin 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 aes eactly atch the !ata ranges

    the tick arks are e#ery 0.( units

    there is no title

    there are no labels on the aes

    there is no legen!

    the line is blue

    :e will a!!ress these points one%by%one. series of eaple scripts calle!

  • 8/9/2019 Python Graphs

    6/22

    pyp"ot.xticks(0.256k or k in range(!45**

    where we use +ython7s

  • 8/9/2019 Python Graphs

    7/22

  • 8/9/2019 Python Graphs

    8/22

  • 8/9/2019 Python Graphs

    9/22

    The line style can be i!entifie! by a wor! or a short co!e. The basic line styles are these/

    Name 'o$eso"id !dashed !!dotted ,Ione (empty string)

    The nae! colours are these/

    *ong form )ingle letterred rgreen gb"ue bcyan cmagenta mye""o yb"ack khite

    :e !on7t ha#e to ha#e a line at all. For scatter plots which we will re#iew below6 we want to turn off the line

    altogether an! to ark the "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"ibsyste has a

    nuber of

  • 8/9/2019 Python Graphs

    10/22

    .ultiple graphs on a single set of aes

    To !ate we ha#e plotte! a single cur#e in our graphs. Aet we are going to plot ultiple cur#es. :hen wecoe on to plot !ifferent types of graph eactly the sae approach will apply to the as to ultiple siplecur#es.

    :e will start with a single graph. The +ython script examp"e02a.pyplots

    the first hebyshe# 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*$*

    'cript/ examp"e02a.py" graph/ examp"e02a.png6

    The array p"otdata.data02yb contains the !ata for the secon!

    hebyshe# polynoial" an! p"otdata.data02ycfor the thir!. The script examp"e02b.pysiply 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"-$FLCD(x*$*

    an! gi#es us the graph we want.

    'cript/ examp"e02b.py" graph/ examp"e02b.png6

    :e can a!&ust the properties of these lines by a!!ing paraeters to thepyp"ot.p"ot(*function calls &ust as we !i! with in!i#i!ual lines.

    The !efault colour seuence is gi#enhere. Though the lines arent uch useif this han!out is printe! in ingreyscale86 The colours start fro blueagain if you plot eight or ore cur#es.

    lso note that it !oesnt atter if latergraphs ha#e !ifferent !ata rangesJ theactual calculation of the aes is!eferre! until the graph is create! withpyp"ot.saveig(*. The script

    examp"e02c.pyeten!s outsi!e the

    range1

  • 8/9/2019 Python Graphs

    11/22

    Parametric graphs

    To !ate our %aes ha#e all been onotonically increasing fro the lower boun! to the upper boun!. There isno obligation for that to be the case" thoughJ the cur#e siply connects the "y6 points in or!er.

    ercise 3

    Cecreate this graph. $ere we plot two of the!ifferent

  • 8/9/2019 Python Graphs

    12/22

    pyp"ot.p"ot(x y "inesty"e- marker-omarkersiAe-15.0 markeredgeidth-5.0markeraceco"or-green markeredgeco"or-red*

    'cript/ examp"e04c.py" graph/ examp"e04c.png6

    The matp"ot"ibsyste supports a wi!e #ariety of arkers" inclu!ing

    soe you can !efine yoursel#es. The pre%!efine! ones are gi#en in thefollowing table/

    File/ markers.png6

    For scatter graphs in#ol#ing large aounts of !ata" howe#er" large arkers are inappropriate an! the graphuses points on the graph to in!icate !ata points. For this the arker P a single piel P is ost

    appropriate. Aote that this takes the markeraceco"orparaeter to !efine its colour.6

    The script examp"e04d.py!raws a scatter graph with 10"000 blue piels/

    x - p"otdata.data04uy - p"otdata.data04v

    pyp"ot.p"ot(x y "inesty"e- marker-markeraceco"or-b"ue*

    'cript/ examp"e04d.py" graph/ examp"e04d.png6

    The proble with piels is that they can be toosall. :here the transitionbetween marker-an! marker-.falls !epen!s on your !ata.

    ercise 0

    The script exercise04.pyruns soe iterations

    o#er an initial set of points an! then nee!s to plot

    the resultant points as a series of scatter graphson the sae aes. The coents in the scripteplain what you nee! to write +ython for.You shoul! get a graph like thisexercise04a.png6

    Feel free to play with other paraeter #alues.

    12922

  • 8/9/2019 Python Graphs

    13/22

    rror bars

    )periental !ata points" whether !rawn as lines or points typically coe with error bars to in!icate theuncertainties in the !ata. These error bars can be syetric or asyetric an! can be in &ust they%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"oto!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 "inesty"e-6. n its siplest for we can use it &ust

    as we use pyp"ot.p"ot(*/

    x - p"otdata.data05xy - p"otdata.data05y

    pyp"ot.errorbar(xy*

    '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-(yminusyp"us*. )ach #alue is a list of errors" as long as the an! y lists. n 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 eaple where the yminuslist is 0.25 0.25 M 0.25an! the

    yp"uslist is 0.5 0.5 M 0.5/

    ha" - p"otdata.data05ha"%uarter - p"otdata.data05%uarter

    pyp"ot.errorbar(xy yerr-(%uarterha"**

    'cript/ examp"e05b.py" graph/ examp"e05b.png6

    Future eaples will use rather ore realistic error !ata/

    yminus - p"otdata.data05ymyp"us - p"otdata.data05yp

    pyp"ot.errorbar(xy yerr-(yminusyp"us**

    'cript/ examp"e05c.py" graph/ examp"e05c.png6

    There are a few aspects of these error bars that users typically want tochange/

    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(xy yerr-(yminusyp"us*eco"or-green*

    'cript/ examp"e05d.py" graph/ examp"e05d.png6

    The blue6 !ata cur#e is !rawn in front of the green6 error bars. There is noparaeter to ake the upper an! lower error bars !ifferent colours.

    13922

  • 8/9/2019 Python Graphs

    14/22

    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. f the paraeter is not gi#en then the sae wi!th is use! for the error bar as for theain cur#e.

    pyp"ot.errorbar(xy yerr-(yminusyp"us*e"ineidth-20.0*

    'cript/ examp"e05e.py" graph/ examp"e05e.png6

    Aote that the caps on the error bars are not wi!ene! proportionately to thewi!th of the error bar itself. That wi!th ust be separately !efine! an! thepyp"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 capline cannot be set. 'etting capsiAe-0eliinates the cap altogether.

    pyp"ot.errorbar(xy yerr-(yminusyp"us* capsiAe-20.0*

    'cript/ examp"e05.py" graph/ examp"e05.png6

    The cap line is always !rawn in the sae colour as the error bar line itself.

    s a rather gau!y6 eaple of cobining the ain pyp"ot.p"ot(*

    paraeters with the error bar%specific paraeters" consi!er the following

    eaple that !raws a (pt re! !ashe! !ata line" re! an! blue !ata pointarkers" an! 10pt error bars without caps in black/

    pyp"ot.errorbar(xy yerr-(yminusyp"us*"inesty"e-dashed co"or-red "ineidth-5.0marker-o markeredgeco"or-red markeredgeidth-5markeraceco"or-hite markersiAe-15eco"or-b"ack e"ineidth-10.0 capsiAe-0*

    '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 eactly the sae way as yerr-5/

    xminus - p"otdata.data05xmxp"us - p"otdata.data05xp

    pyp"ot.errorbar(xy xerr-(xminusxp"us*yerr-(yminusyp"us**

    '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 colour" wi!th" cap siHe" etc.6 ust be thesae in both !irections.

    ercise 1

    The script exercise05.pysets up soe !ata

    for a graph like this with

  • 8/9/2019 Python Graphs

    15/22

    Polar graphs

    Aot all graphs want orthogonal aes"xan!y. yclical !ata is typically !rawn on polar aes" an! r. Thepyp"oto!ule pro#i!es a function pyp"ot.po"ar( r5*which is takes eactly the sae arguents

    as pyp"ot.p"ot(xy5*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 rare negati#e.t 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"otknow that we are

    going to be working with polar aes rather than orthogonal ones as early in the process as possible. :e !othis with a function call

    pyp"ot.axes(po"ar-Frue*

    The !efault is Na"sean! is what we ha#e been using for our pre#ious graphs.

    The +ython script examp"e09a.pyplots a graph of r=tfor 0

  • 8/9/2019 Python Graphs

    16/22

    '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 function7scopulsory arguent of a list of #alues as its arguent.

    pyp"ot.thetagrids(0.0 80.0 1:0.0 230.0*

    '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. f 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 tet ob&ects an! ust ha#e the sae length as the list of angles.

    For eaple I O J=.

    'o we coul! label the graph in our running eaple as follows/

    pyp"ot.thetagrids(0 80 1:0 230"abe"s-> I O J*

    'cript/ examp"e09d.py" graph/ examp"e09d.png.6

    Finally we can change the position of the labels. :e specify their positionrelati#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! !efaultsto a #alue of 1.1. #alue less than 1.0 puts the labels insi!e the circle/

    pyp"ot.thetagrids(0 80 1:0 230"abe"s-> I O J rac-0.8*

    'cript/ examp"e09e.py" graph/ examp"e09e.png.6

    ,he concentric gri$ lines an$ their labels

    The pyp"ot.rgrids(*function is the eui#alent of

    pyp"ot.thetagrids(*for the concentric circles labelle! 1 to , in our graphs so far6.

    n its siplest use it specifies the ra!ii of the circles as a list of #alues/

    pyp"ot.rgrids(2.0 4.0 9.0 :.0*

    'cript/ examp"e09.py" graph/ examp"e09.png.6

    1*922

  • 8/9/2019 Python Graphs

    17/22

    !Aote that we !on7t get a ring at r=".08

    The polar graph only eten!s out as far as the !ata.

    Yes" this is a bug.

    :e can eplicitly set the outer liit of the rings" but we ha#e to epose the inner workings of pyp"otto !o it.

    nternally" pyp"ottreats as anx%coor!inate an! ras ay%coor!inate. :e can eplicitly set the upper #alue

    of rwith 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(2.0 4.0 9.0 :.0*

    '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!ialgri!/

    pyp"ot.y"im(ymax-:.0*

    pyp"ot.rgrids(1.53 .14 4.31 9.2: "abe"s-P/2P P/2 2P*

    'cript/ examp"e09h.py" graph/ examp"e09h.png.6

    For those of you not cofortable with !irect use of non%keyboar! charactersyou can get the ore atheatical #ersion with the R5R notation/

    pyp"ot.y"im(ymax-:.0*pyp"ot.rgrids(1.53 .14 4.31 9.2:"abe"s-$pi/2$ $pi$ $pi/2$ $2pi$*

    '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 =0line" but this can be a!&uste! with theang"e-5 paraeter/

    pyp"ot.y"im(ymax-:.0*

    pyp"ot.rgrids(1.53 .14 4.31 9.2:"abe"s-P/2 P P/2 2P ang"e-!22.5*

    'cript/ examp"e09j.py" graph/ examp"e09j.png.6

    ngle takes its #alue in !egrees.

    ercise 2

    The script exercise09.pysets up soe !ata

    for this graph. :rite the pyp"otlines to

    generate the graph shown.The cur#e is r=sin#($).6

    1,922

  • 8/9/2019 Python Graphs

    18/22

    istograms

    !

    For the purposes of this tutorial we are going to be pe!antic about the !ifferent!efinitions of histogras an! bar charts.

    histogramcounts how any !ata ites fit in ranges known as

  • 8/9/2019 Python Graphs

    19/22

    The pyp"ot.hist(*function has an orientation-5 paraeter. There are two accepte! #ales/

    vertica"an! horiAonta".

    pyp"ot.hist(data orientation-horiAonta"*

    '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. n

    its siplest for it can be an integer" specifying the nuber of bins to use/

    pyp"ot.hist(data bins-20*

    'cript/ examp"e03h.py" graph/ examp"e03h.png.6

    lternati#ely we can specify eactly what the bins shoul! be. To !o this we

    specify the boun!aries of the bins" so for %bins we nee! to specify %&1boun!aries/

    pyp"ot.hist(databins-!.0 !2.0 !1.0 0.0 1.0 2.0 .0*

    '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 noticeablywi!er than the others/

    pyp"ot.hist(data,350 ridth-0.5*pyp"ot.hist(data350, ridth-0.5*

    'cript/ examp"e03.py" graph/ examp"e03.png.6

    t a iniu you shoul! set the bins eplicitly. 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 not necessarily all of the sae siHe6 an!plot the together/

    pyp"ot.hist(data,350 data350,*

    'cript/ examp"e03j.py" graph/ examp"e03j.png.6

    f it is plotting ultiple histogras the bin siHes are base! on the union of allthe !atasets. The wi!ths of the blocks are autoatically scale! !own to fitthe 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

  • 8/9/2019 Python Graphs

    20/22

  • 8/9/2019 Python Graphs

    21/22

    :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(xy idth-"ist*

    'cript/ examp"e0:d.py" graph/ examp"e0:d.png.6

    #n$icating ranges with bar charts

    s well as #arying with wi!ths of the bars we can also #ary their bases" or

  • 8/9/2019 Python Graphs

    22/22