Week 7 – Libraries and Graphing Data

Week 7 – Libraries and Graphing Data

[ad_1]

Weekly Topics
• In this weeks lecture and lab we will look at the following areas:
• What libraries are,
• How we can write our own libraries and use built-in and third-party libraries
in our programs,
• Importing functionality from Pythons standard library, and
• Using matplotlib to graph data in various ways, including:
• Bar charts,
• Scatter plots,
• Pie charts,
• Histograms, and
• Venn diagrams.
3
Why Use Libraries?
• When you want to solve some kind of programming problem and want to use
anything more than the standard built-in functionality of a programming
language then you have precisely two options:
• You can write the new functionality yourself,
or
• You can find and use a library that has the ability to perform the
desired functionality.
• Another way of looking at this would be to say that you either have to build your
own tools to perform the job, or you can use the tools that other people have
built to perform similar jobs.
• Pretty much every conceivable tool that people need has already been
developed and can be used, so there’s often little point in ‘re-inventing the
wheel’ – the wheel exists! So let’s use it!
4
So What Exactly is a Library?
• In essence, a library is just a piece of code that can be used to provide some
functionality.
• This can mean that it’s something as simple as a class with one or more
functions. Once written, we can distribute the class for other people to use.
• In Python, libraries are commonly called modules – but that’s just a naming
difference, they still act and work the same as libraries do in any other
language.
• Let’s start by doing some Python stuff with fractions – you know, ½ , ¼ etc.
• By default Python can’t really do much with fractions, but it does come with a
fractions module that we can use which allows us to do pretty much whatever
we might want to with them, so let’s give it a shot!
5
Using Built-In Modules
• As we’ve said, we can think of a module as a program written by someone else
that you can use in your own programs.
• A module can include classes, functions, and even label definitions.
• It can be part of Python’s standard library or distributed from a third-party
location. In the latter case, we’d have to install the module before you could use
it (but more on that later).
• The fractions module is part of the standard library, meaning that it’s already
installed. It defines a class called Fraction, which is what we’ll use to enter
fractions into our programs.
• Before we can use it, we’ll need to import it, which is a way of telling Python
that we want to use the class from this module.
6
Using Built-In Modules (Cont’d)
• Let’s see a quick example – we’ll import the Fraction class, create a new
Fraction object called f which refers to the fraction ¾, and then print it out.
from fractions import Fraction
f = Fraction(3, 4)
print(f)
• Which gives us the output:
3/4
• The basic mathematical operations, including the comparison operations, are
all valid for fractions.
7
Using Built-In Modules (Cont’d)
• We can also combine a fraction, an integer, and a floating point number in a single
expression – like this:

from fractions import Fraction
f = Fraction(3, 4) + 1 + 1.5
f
3.25
• When we have a floating point number in an expression then the result of the
expression is returned as a float.
• On the other hand, when we only have fractions and integers in the expression then
the result is returned as a fraction, even if the denominator (bottom part of the
fraction) is 1:
from fractions import Fraction
f = Fraction(3, 4) + 1 + Fraction(1, 4)
f
Fraction(2, 1)
8
Creating our own libraries
• Now that we’ve seen the use of a built-in Python module, let’s try creating one
of our own.
• Just to keep things simple, we’ll start by writing a small class that allows us to
work with circles, and which we’ll rather inventively call Circle.
II”m aa CCiirrccllee!!
9
A Simple Circle Library
• To do this we can create a Circle.py file, then put something like the following
in it:
“””Library to work with Circles.”””
import math.pi
def calcCircumference(radius):
“””Calculate and return the radius of a circle.”””
return 2 * math.pi * radius;
• Once, done we can create a second file called maybe CircleTest.py that uses
our Circle library, like this:
from Circle import calcCircumference
print( “Circumference of circle with radius 5 is: ” +
str( calcCircumference(5) ) )
10
A Simple Circle Library (Cont’d)
• Looking at our simple Circle library with it’s single method, we can see the
following line near the top of the file:
import math.pi
• What this now means is that our library depends on the math library…
• …and if the math library for some reason isn’t available then our Circle library
will stop working.
• However, the math library is such an intrinsic part of Python that it will always
be available. Other libraries may not be, so the point being made is:
When you build libraries, think a little about library dependencies and
minimise them where possible!
Quiz: Why do you think it was decided to import math.pi instead of using import math?
11
A Simple Circle Library (Cont’d)
• Another way to access the math module’s pi constant would be to write it like this:
“””Library to work with Circles.”””
from math import pi
def calcCircumference(radius):
“””Calculate and return the radius of a circle.”””
return 2 * pi * radius;
• Notice that we changed import math.pi to from math import pi – the
side-effect of this is that we no longer access the constant like this:
return 2 * math.pi * radius;
• And can instead reference it directly without needing to tell Python that the
constant comes from the math module, like this:
return 2 * pi * radius;
12
A Simple Circle Library (Cont’d)
• Staying very briefly on the topic of library dependencies and taking another look
at our initial version of the import line in our Circle class:
import math.pi
• Question: How could we remove the dependency on the math library entirely?
• Answer: …
13
A Simple Circle Library (Cont’d)
• Staying very briefly on the topic of library dependencies and taking another look
at our initial version of the import line in our Circle class:
import math.pi
• Question: How could we remove the dependency on the math library entirely?
• Answer: We could define our own PI constant in the Circle library and use that
instead. To do this we might modify our library as follows:
“””Library to work with Circles.”””
PI = 3.141592
def calcCircumference(radius):
“””Calculate and return the radius of a circle.”””
return 2 * PI * radius;
Note: We put PI in upper-case to indicate that it’s value should be constant (i.e. shouldn’t be changed!)
14
A Simple Circle Library (Cont’d)
• If we wanted, we could change our Circle library from just having methods to being a complete class that
contains objects we can use. Let’s give it a go and modify our Circle.py code to be the following:
“””Library to work with Circles.”””
class Circle:
PI = 3.141592

Constructor

def init(self, radius):
self.radius = radius
def circumference(self)
return 2 * Circle.PI * self.radius;
def area(self):
return Circle.PI * self.radius * self.radius

‘toString’ method

def str(self):
return “””Radius:
Circumference:
Area: “””.format( self.radius, self.circumference(), self.area() );
Substitute result of
method calls as we
didn’t declare
circumference and
area properties…
15
A Simple Circle Library (Cont’d)
• Finally, using our Circle library is as simple as calling something like this:
import Circle # This pulls in the class and all methods
myCircle = Circle(5)
print(myCircle)
• Which will give us the following output:
Radius: 5
Circumference: 31.41592
Area: 78.5398
16
So are we saying that a Library is simply a Class?
• Well… yes and no.
• A library certainly CAN be just a single class that performs some piece of
functionality that isn’t natively available in a language…
• For example: stb is a series of single file libraries (for C/C++ in this
instance) which do useful things like load images into memory, or
decode audio, or render fonts. See: https://github.com/nothings/stb
• …but more commonly, libraries consist of multiple files or classes that work
together to provide some higher-level functionality.
• Taken to extremes, you could reasonably think of a game engine like Unity or
Unreal Engine as a library of sorts that provides a wide variety of different
functionality all tied together into a cohesive framework.
17
So are we saying that a Library is simply a Class? (Cont’d)
• A more ‘medium sized’ example of a library (and blatant self-promotion aside!)
might be the Caliko library to solve inverse kinematics problems so it can
control robot arms and the like. It ended up using a fair few classes.
Note: If you’re interested you can take a look at Caliko at: https://github.com/FedUni/caliko
Core
classes
Utility
classes
18
Modules Vs Libraries
• All the libraries that natively come with Python (i.e. the ones we don’t have to
go and fetch them separately – they come with a standard installation) are what
Python refers to as modules.
• If we wanted to see which modules come with Python then we could write a
simple script like this to list them all:
import sys
count = 0
for module in sys.modules.keys():
print(module)
count += 1
print(“Total built-in module count: ” + str(count))
Note: Another way is to look at the Python Module Index online at: https://docs.python.org/3/py-modindex.html
19
External Libraries in Python
• However, the built-in modules are not the only available libraries that we can
use in our Python programs – in fact, they’re only a small percentage them!
• Python comes with a built-in package manager called pip.
• Using pip, we can install what Python refers to as packages (which is really just
yet another name for libraries!).
• First of all, just to make sure that pip is installed and working (it should be – it
comes with a standard Python installation) we can open up a command prompt
and enter pip –version
• So far, so good! We have pip version 9.0.1 installed and ready for use!
20
External Libraries in Python (Cont’d)
• The next thing we might want to do is go and take a look at some of the
potential libraries / packages that we can install.
• To do this, we can go to the website https://pypi.python.org/pypi and take a look
around!
• Guesswork: Without looking it up, how many packages do you think we might
find? ?
21
External Libraries in Python (Cont’d)
• The next thing we might want to do is go and take a look at some of the
potential libraries / packages that we can install.
• To do this, we can go to the website https://pypi.python.org/pypi and take a look
around!
• Guesswork: Without looking it up, how many packages do you think we might
find?

  • = as of 2018/01/08
    Presently – 126,047 aanndd ccoouunnttiinngg*!! 22 External Libraries in Python (Cont’d) • And what do these libraries do? Pretty much any and everything! Source: https://pypi.python.org/pypi?%3Aaction=browse 23 External Libraries in Python (Cont’d) • Because some of you taking this course will be doing business data / analytics courses – let’s pick a Python library that might be useful to you and do a little experimentation with. • As such, we’ll be using the matplotlib library to make graphs with Python. • Matplotlib is a package, which means it’s a collection of modules with related functionality – in this case, the modules are useful for plotting numbers and making graphs. • Because matplotlib doesn’t come built-in with Python’s standard library, we’ll need to go and install it ourselves via pip. • To do this, we can simply call the following from a command prompt: pip install matplotlib Note: In the labs you’re more likely to be using the Anaconda installation of Python that comes with a number of more commonly used libraries rather than installing matplotlib yourself. 24 External Libraries in Python (Cont’d) • Because the matplotlib library depends on other libraries, it has to go and get them during the install process – but this is completely automatic. Phew! 25 External Libraries in Python (Cont’d) • Now that we have matplotlib installed it will always be there for to use… • …only, how do we actually use it?! ¯_(ツ)_/¯ • This is where we might want to go and look at the package’s page on the Python package index – so in this case it’s: https://pypi.python.org/pypi/matplotlib/2.1.1 • From here we can read a little about the library, and also see that it has its own homepage, which is likely where we’ll find the library’s documentation. Very Useful Tip (Seriously) There are commonly many libraries that can be used to perform the same task. When you find yourself in this situation (and believe me, you will) choose the library with the best documentation. A library with poor documentation is typically one that only the library author understands, and it will end up wasting your time and causing you grief in the long run. Trust me on this one. 26 External Libraries in Python (Cont’d) • Matplotlib comes with not only the standard API documentation (i.e. list of classes / functions and how to use them), but also a nice user guide including tutorials on using various aspects of the library. • As such, we can be pretty sure that this is a high quality library that respects its users’ time and sanity! • So now that we’ve got it installed and ready to go, let’s take it for a test drive! 27 Using the matplotlib Library • We’ll start with a simple graph with just three points: (1, 2), (2, 4), and (3, 6). • To create this graph, we’ll want to import the plot and show functions. • The plot function creates and returns a graph object, while the show function displays a graph object on the screen. • If we add to this the creation of our two lists x_numbers and y_numbers – then our entire program including plotting and showing the graph simply becomes: from pylab import plot, show x_numbers = [1, 2, 3] y_numbers = [2, 4, 6] show( plot(x_numbers, y_numbers) ) This section of the course is based on the book Doing Math in Python (No Starch Press, 2015). 28 Using the matplotlib Library • In our graph, notice that instead of starting from the origin (0, 0), the x-axis starts from the number 1 and the y-axis starts from the number 2. • These are the lowest numbers from each of the two lists. Also, you can see increments marked on each of the axes (such as 2.5, 3.0, 3.5, etc., on the yaxis). x_numbers = [1, 2, 3] y_numbers = [2, 4, 6] FFiirrsstt ppooiinntt SSeeccoonndd ppooiinntt TThhiirrdd ppooiinntt 29 Marking Points on a Graph • If we want the graph to mark the points that we supplied for plotting, we can use an additional keyword argument while calling the plot() function: show( plot(x_numbers, y_numbers, marker=’o’) ) • Which now results in our graph looking like this: • We can choose from several marker options including ‘o’, ‘‘, ‘x’ and ‘+’.
    30
    Marking Points on a Graph (Cont’d)
    • The default behaviour is to draw a line between each point in our graph. If we
    only wanted to display the points themselves then we can remove the marker=
    part of the third parameter and just give it the symbol to use to show the points
    on their own:
    show( plot(x_numbers, y_numbers, ‘*’) )
    • This results in our graph now looking like this:
    31
    Graphing the Average Annual Temperature of New York City
    • The average annual temperatures for New York City (Central Park, specifically)
    during the years 2000 to 2012 are as follows: 53.9, 56.3, 56.4, 53.4, 54.5, 55.8,
    56.8, 55.0, 55.3, 54.0, 56.7, 56.4, and 57.3 degrees Fahrenheit.
    • Right now, that just looks like a random jumble of numbers, but we can plot this set
    of temperatures on a graph to make the rise and fall in the average temperature
    from year to year much clearer:
    nyc_temp = [53.9, 56.3, 56.4,
    53.4, 54.5, 55.8, 56.8, 55.0,
    55.3, 54.0, 56.7, 56.4, 57.3]
    show( plot(nyc_temp, marker=’o’) )
    • Notice that when we call plot and pass it
    a single list, then those numbers are
    automatically plotted on the y-axis, and
    the position of the number in the list is
    used for the x-axis (i.e. each of the years
    we have data for in this instance).
    32
    Graphing the Average Annual Temperature of New York City (Cont’d)
    • Even though the numbers in our list don’t actually vary much, the graph makes
    them look as if they’re changing dramatically…
    • The reason for this is that matplotlib chooses the range of the y-axis so that it’s
    just enough to enclose the data supplied for plotting.
    • So in this graph, the y-axis starts at 53.0 and its highest value is 57.5. This
    makes even small differences look magnified because the range of the y-axis is
    so small! We’ll come back and fix this up a little later on…
    33
    Graphing the Average Annual Temperature of New York City (Cont’d)
    • Previously, while we can see that the number along the x-axis represents the
    position in the list of that value, it’d be much nicer to display the actual year
    number along that axis.
    • To do so, we can simply generate a set of values between 2000 and 2012 and
    use that list in our plot:
    nyc_temp = [53.9, 56.3, 56.4,
    53.4, 54.5, 55.8, 56.8, 55.0,
    55.3, 54.0, 56.7, 56.4, 57.3]
    years = range(2000, 2013)
    show( plot(years, nyc_temp, marker=’o’) )
    • Quiz: Do you recall why we might call range(2000, 2013) to get a set of values
    that includes 2000 but does not include 2013?
    34
    Comparing Temperature Trends
    • While still looking at New York City, let’s see how the average monthly
    temperature has varied over the years. This will give us a chance to understand
    how to plot multiple lines on a single graph.
    • We’ll choose three years: 2000, 2006, and 2012 – and for each of these years,
    we’ll plot the average temperature for all 12 months.
    temp_2000 = [31.3, 37.3, 47.2, 51.0, 63.5, 71.3, 72.3, 72.7,
    66.0, 57.0, 45.3, 31.1]
    temp_2006 = [40.9, 35.7, 43.1, 55.7, 63.1, 71.0, 77.9, 75.8,
    66.6, 56.2, 51.9, 43.6]
    temp_2012 = [37.3, 40.9, 50.9, 54.8, 65.1, 71.0, 78.8, 76.7,
    68.8, 58.0, 43.9, 41.5]
    • Now that we have our data, the clearest way to compare all these
    temperatures is to plot all three data sets on a single graph, like this…
    35
    Comparing Temperature Trends (Cont’d)
    mon = range(1, 13)
    show( plot(mon, temp_2000, mon, temp_2006, mon, temp_2012) )
    • By using multiple sets of x-axis and y-axis values we can plot multiple sets of
    data on the same graph, and matplotlib will even automatically choose different
    colours for us for each set of data
    xx//yy sseettss
    36
    Comparing Temperature Trends (Cont’d)
    • This is all fine and good – but which colour represents which year?! To know this
    we need to use a legend – which is a functional available in matplotlib:
    from pylab import plot, show, legend
    temp_2000 = [31.3, 37.3, 47.2, 51.0, 63.5, 71.3, 72.3, 72.7,
    66.0, 57.0, 45.3, 31.1]
    temp_2006 = [40.9, 35.7, 43.1, 55.7, 63.1, 71.0, 77.9, 75.8,
    66.6, 56.2, 51.9, 43.6]
    temp_2012 = [37.3, 40.9, 50.9, 54.8, 65.1, 71.0, 78.8, 76.7,
    68.8, 58.0, 43.9, 41.5]
    mon = range(1, 13)
    myPlot = plot(mon, temp_2000, mon, temp_2006, mon, temp_2012)
    legend([2000, 2006, 2012])
    show(myPlot)
    Notice how rather than passing the returned
    object from calling plot directly into the show
    method – we now keep a reference to it
    (myPlot) and THEN we set the legend.
    Without doing this the legend won’t show up!
    37
    Comparing Temperature Trends (Cont’d)
    • With our legend in place we can now identify which line is which dataset – hurrah!
    38
    Adding a Title and Labels
    • Any good graph should have a title (i.e. what it is), and labels for the x and y
    axes.
    • This is all pretty straight forward in matplotlib – we just need to import a couple
    of extra functions and use ’em!
    from pylab import plot, show, legend, title, xlabel, ylabel

    title(‘Average monthly temp in NYC’)
    xlabel(‘Month’)
    ylabel(‘Temperature (F)’)
    show(myPlot)
    39
    Customising Axes
    • So far, we’ve allowed the numbers on both axes to be automatically determined
    by Python based on the data supplied to the plot() function.
    • This may be fine for most cases, but sometimes this automatic range isn’t the
    clearest way to present the data, as we saw in the graph where we plotted the
    average annual temperature of NYC.
    • There, even small changes in the temperature
    seemed large because the automatically
    chosen y-axis range was very narrow.
    • We can adjust the range of the axes using
    the axis() function.
    • This function can be used both to retrieve the current range and to set a new
    range for the axes.
    40
    Customising Axes (Cont’d)
    • Let’s modify the code used to create that graph so that we can set the ranges
    ourselves:
    from pylab import plot, show
    nyc_temp = [53.9, 56.3, 56.4, 53.4, 54.5, 55.8, 56.8, 55.0,
    55.3, 54.0, 56.7, 56.4, 57.3]
    myPlot = plot(nyc_temp, marker=’o’)
    from pylab import axis
    print ( axis() )
    • By calling the axis function, we are shown the current x and y axis ranges, so
    for this particular graph it returns us:
    (-0.6, 12.6, 53.20, 57.5)
    Yes, it’s fine to have multiple import
    lines – and we can place them
    wherever we want in our code
    xx–aaxxiiss miinn//maaxx yy–aaxxiiss miinn//maaxx
    41
    Customising Axes (Cont’d)
    • The reason our min and max values don’t precisely match the exact minimum
    and maximums of our x and y axes is that there’s some padding applied to the
    ranges so that points don’t fall precisely on the edges where they might be
    difficult to see.
    • If we wanted them to ‘stick-to-the-edges’ then we could specify our own axes
    ranges, like this:
    newAxisRange = [0, 12, 53.4, 57.3]
    axis(newAxisRange)
    42
    Customising Axes (Cont’d)
    • It looks better (and is clearer) with the padding – but the y-axis is still over
    exaggerating the extent of the temperature changes because it doesn’t start at
    zero – it only goes from the minimum to maximum temperature (53.4 to 57.3).
    • The easiest way to change the minimum value of an axis such as the y-axis is
    to simply issue a command like this:
    axis(ymin = 0)
    • With that done, our changes to
    average temperature start to
    look a lot different!
    • However, we’re now butting up
    against the top of the graph, so
    we should probably pad that out
    a little. A simple call to axis(ymax = 60)
    will do the job just fine.
    43
    Alternate Ways of Importing Functionality
    • If we go back to our very first plot, we imported the functionality and used it in a
    way which is more commonly used when plotting graphs from Python’s
    interactive shell:
    from pylab import plot, show
    x_numbers = [1, 2, 3]
    y_numbers = [2, 4, 6]
    show( plot(x_numbers, y_numbers) )
    44
    Alternate Ways of Importing Functionality (Cont’d)
    • This isn’t typically the way we’ll see other code perform the same action – what
    we’d see instead is likely to be something kind of like this:
    import matplotlib.pyplot
    def create_graph():
    x_numbers = [1, 2, 3]
    y_numbers = [4, 5, 6]
    matplotlib.pyplot.plot(x_numbers, y_numbers)
    matplotlib.pyplot.show()
    create_graph()
    • It’s a little verbose though, don’t you think – compared to our original 4 line
    version?
    45
    Alternate Ways of Importing Functionality (Cont’d)
    • Thankfully, there’s a way to cut out a lot of that mathplotlib.pyplot.
    typing, and that’s to assign a short name to our imported library.
    • We can do so like this:
    import matplotlib.pyplot as plt
    def create_graph():
    x_numbers = [1, 2, 3]
    y_numbers = [4, 5, 6]
    plt.plot(x_numbers, y_numbers)
    plt.show()
    create_graph()
    • That’s a bit cleaner to work with, and saves us some keystrokes as well =D
    46
    Saving Graphs
    • Once we’ve got some nice graphs generated, then we can always screenshot
    them – but we also have the ability to save an image of the graph.
    • To do this, we can simply call savefig(‘some_filename.png’), for example:
    from pylab import plot, savefig
    x = [1, 2, 3]
    y = [2, 4, 6]
    plot(x, y)
    savefig(‘mygraph.png’)
    • This will save the graph to an image file, mygraph.png, in your current directory.
    • If you wanted to save the image to a different directory, then you can specify
    the complete path. For example, to save the image under C: on Windows as
    mygraph.png, you’d call savefig(‘C:mygraph.png’).
    Top tip: To grab just the current window ready for pasting into a paint package or document use: Alt + PrntScrn – this
    can save you the need to crop the entire desktop to just the part you want later on!
    47
    Plotting Formulas
    • Until now, we’ve been plotting points on our graphs based on known values –
    for example, recorded temperatures and dates that were already available to us
    at the time we wanted to create the New York City graphs.
    • In this next section, we’re going to create graphs from mathematical formulas –
    and in this instance we’ll use Newton’s Law of Universal Gravitation (i.e. the
    gravitational force between two bodies, like the sun and the moon). The formula
    for this is:
    • In this formula:
    • F is the force between the bodies that we’ll calculate (unit: newtons),
    • G is the gravitational constant (6.674 x 10-11),
    • m1 and m2 are the masses of the bodies (unit: kilograms), and
    • r is the distance between the two bodies (unit: metres).
    48
    Plotting Formulas (Cont’d)
    import matplotlib.pyplot as plt

Draw the graph – takes the x and y sets of data as parameters

def draw_graph(x, y):
plt.plot(x, y, marker=’o’)
plt.xlabel(‘Distance (metres)’)
plt.ylabel(‘Gravitational force (newtons)’)
plt.title(‘Gravitational force and distance’)
plt.show()
def generate_F_r():
r = range(100, 1001, 50) # Set from 100 to 1000 in steps of 50
F = [] # Empty set ready to fill with values
G = 6.674 * (10**-11) # Gravitational constant
m1 = 0.5 # First mass in kg
m2 = 1.5 # Second mass in kg

Calculate force and add it to the list, F

for dist in r:
force = G * (m1 * m2) / (dist ** 2)
F.append(force)
draw_graph(r, F)
generate_F_r()
49
Plotting Formulas (Cont’d)
• The result of our work is this graph
50
Plotting Formulas – Sine and Cosine
import math
import matplotlib.pyplot as plt
DEG_2_RAD = 3.14159 / 180.0 # Constant to convert degrees to radians
def draw_graph(sinVals, cosVals, angles):
plt.plot(angles, sinVals, marker=’o’) # Plot sine values
plt.plot(angles, cosVals, marker=’x’) # Plot cosine values
plt.show()
def generate_data():
angles = range(0, 360, 10) # 0 to 350 in 10 degree increments
angles = [x * DEG_2_RAD for x in angles] # Convert to radians
sinVals = []
cosVals = []
for a in angles:
sinVals.append( math.sin(a) )
cosVals.append( math.cos(a) )
draw_graph(sinVals, cosVals, angles)
generate_data()
51
Plotting Formulas – Sine and Cosine (Cont’d)
• Sine (circles) and cosine (crosses) graphed for values between 0 and 2π radians.
52
Adding a Legend
import math
import matplotlib.pyplot as plt
DEG_2_RAD = 3.14159 / 180.0 # Constant to convert degrees to radians
def draw_graph(sinVals, cosVals, angles):
plt.plot(angles, sinVals, marker=’o’, label=’Sine’) # Plot sines
plt.plot(angles, cosVals, marker=’x’, label=’Cosine’) # Plot cosines
plt.legend()
plt.show()
def generate_data():
angles = range(0, 360, 10) # 0 to 350 in 10 degree increments
angles = [x * DEG_2_RAD for x in angles] # Convert to radians
sinVals = []
cosVals = []
for a in angles:
sinVals.append( math.sin(a) )
cosVals.append( math.cos(a) )
draw_graph(sinVals, cosVals, angles)
generate_data()
Add labels and then call
the legend function to add
a legend to the graph!
53
Adding a Legend (Cont’d)
• Our graph will now have a legend added which allows the user to determine
which plotted line represents which data:
54
Bar Charts
• Let’s take a whirlwind tour of some of the other types of graphs we can create – we’ll start by creating a bar
chart via matplotlib’s bar method:
import matplotlib.pyplot as plt
def create_bar_chart(data, labels):
num_bars = len(data) # Number of bars to draw
positions = range(1, num_bars+1) # Positions of bars on y-axis
plt.bar(positions, data, align=’center’) # Generate the bar chart
plt.xticks(positions, labels) # Add little markers to each label on x-axis
plt.xlabel(‘Day’) # At x-axis label
plt.ylabel(‘Steps’) # Add y-axis label
plt.title(‘Number of steps walked’) # Add title
plt.grid() # Add a grid for easier visual estimation of values
plt.show()
stepsWalked = [6534, 7000, 8900, 10786, 3467, 11045, 5095]
labels = [‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’, ‘Sun’]
create_bar_chart(stepsWalked, labels)
55
Bar Charts (Cont’d)
• Which results in this:
56
Bar Charts (Cont’d)
• If we wanted the bar chart to be horizontal, then we can simply use matplotlib’s barh method:
import matplotlib.pyplot as plt
def create_bar_chart(data, labels):
num_bars = len(data) # Number of bars to draw
positions = range(1, num_bars+1) # Positions of bars on y-axis
plt.barh(positions, data, align=’center’) # Draw the horiz bar chart
plt.yticks(positions, labels) # Add little markers to each label on y-axis
plt.xlabel(‘Steps’) # At x-axis label
plt.ylabel(‘Day’) # Add y-axis label
plt.title(‘Number of steps walked’) # Add title
plt.grid() # Add a grid for easier visual estimation of values
plt.show()
stepsWalked = [6534, 7000, 8900, 10786, 3467, 11045, 5095]
labels = [‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’, ‘Sun’]
create_bar_chart(stepsWalked, labels)
57
Bar Charts (Cont’d)
• Which results in this:
58
Histograms
• It’s pretty straight forward to draw histograms, too.
import matplotlib.pyplot as plt
import numpy as np

Generate a list of 1000 random values between 0.0 and 1.0

x = np.random.normal(size = 1000)

Plot a histogram of this data, dividing it up into 30 bins

plt.hist(x, normed=True, bins=30)

Add a label and show the histogram

plt.ylabel(‘Probability’);
plt.show()
59
Histograms (Cont’d)
• Which results in:
60
Venn Diagrams
import matplotlib.pyplot as plt
import matplotlib_venn as vn

Subset sizes

s = (
2, # Ab
3, # aB
1, # AB
)
v = vn.venn2(subsets=s, set_labels=(‘A’, ‘B’))

Subset labels

v.get_label_by_id(’10’).set_text(‘A but not B’)
v.get_label_by_id(’01’).set_text(‘B but not A’)
v.get_label_by_id(’11’).set_text(‘A and B’)
Note: Requires you to add venn package first. From cmd line use: pip install matplotlib-venn
61
Venn Diagrams (Cont’d)

Subset colours

v.get_patch_by_id(’10’).set_color(‘c’)
v.get_patch_by_id(’01’).set_color(‘#993333’)
v.get_patch_by_id(’11’).set_color(‘blue’)

Subset alphas

v.get_patch_by_id(’10’).set_alpha(0.4)
v.get_patch_by_id(’01’).set_alpha(1.0)
v.get_patch_by_id(’11’).set_alpha(0.7)

Border styles

c = vn.venn2_circles(subsets=s, linestyle=’solid’)
c[0].set_ls(‘dashed’) # Line style
c[0].set_lw(2.0) # Line width
plt.show()
Source: http://matthiaseisen.com/pp/patterns/p0144/
62
Venn Diagrams (Cont’d)
• Ta-da!
63
Wrap Up
• We’ve seen what libraries are and how we can write our own libraries,
• We’ve uses pip to find and install external / third-party libraries such as
matplotlib,
• We’ve looked at how we can graph simple data (including adding titles and
axes, and adjust the scales of our axes)…
• …as well as how we can graph functions and other data that we might
generate.
• We’ve also see how we can put together a wide variety of different graphical
representations of data such as histograms, pie charts, and venn diagrams etc.
• In this weeks lab you’ll get a chance to experiment further with libraries and
graphing.

[Button id=”1″]


[ad_2]
Source link

"96% of our customers have reported a 90% and above score. You might want to place an order with us."

Essay Writing Service
Affordable prices

You might be focused on looking for a cheap essay writing service instead of searching for the perfect combination of quality and affordable rates. You need to be aware that a cheap essay does not mean a good essay, as qualified authors estimate their knowledge realistically. At the same time, it is all about balance. We are proud to offer rates among the best on the market and believe every student must have access to effective writing assistance for a cost that he or she finds affordable.

Caring support 24/7

If you need a cheap paper writing service, note that we combine affordable rates with excellent customer support. Our experienced support managers professionally resolve issues that might appear during your collaboration with our service. Apply to them with questions about orders, rates, payments, and more. Contact our managers via our website or email.

Non-plagiarized papers

“Please, write my paper, making it 100% unique.” We understand how vital it is for students to be sure their paper is original and written from scratch. To us, the reputation of a reliable service that offers non-plagiarized texts is vital. We stop collaborating with authors who get caught in plagiarism to avoid confusion. Besides, our customers’ satisfaction rate says it all.

© 2022 Homeworkcrew.com provides writing and research services for limited use only. All the materials from our website should be used with proper references and in accordance with Terms & Conditions.

Scroll to Top