Advance Python Unit - 3
Advance Python Unit - 3
PyLab is a Python standard library module that provides many of the facilities of MATLAB, “a
high- level technical computing language and interactive environment for algorithm
development, data visualization, data analysis, and numeric computation.
1) Simple
import pylab
pylab.figure(1)
pylab.plot([1,2,3,4,5],[1,7,3,5,12])
pylab.show()
The two parameters of pylab.plot must be sequences of the same length. The first specifies
the x-coordinates of the points to be plotted, and the second specifies the y-coordinates.
Together, they provide a sequence of four <x, y> coordinate pairs,[(1,1), (2,7), (3,3), (4,5)].
These are plotted in order. As each point is plotted, a line is drawn connecting it to the
previous point. The final line of code, pylab.show(), causes the window to appear on the
computer screen.
It is possible to produce multiple figures and to write them to files. These files can have any
name you like, but they will all have the file extension .png. The file extension .png indicates
that the file is in the Portable Networks Graphics format. This is a public domain standard
for representing images.
pylab.title('My Graph')
pylab.xlabel('x-axis')
pylab.ylabel('y-axis')
Title can be given using title(). Label on x-axis and y-axis given using xlable() and ylable().
Matplotlib is a plotting library for Python. It is used along with NumPy to provide an
environment that is an effective open source alternative for MatLab
The package is imported into the Python script by adding the following statement − from
matplotlib import pyplot as plt
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
x = np.arange(1,11)
y = 2 * x + 5
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y)
plt.show()
An ndarray object x is created from np.arange() function as the values on the x axis. The
corresponding values on the y axis are stored in another ndarray object y. These values are
plotted using plot() function of pyplot submodule of matplotlib package.
The graphical representation is displayed by show() function.
Instead of the linear graph, the values can be displayed discretely by adding a format string
to the plot() function. Following formatting characters can be used. The letters and symbols
of the format string are derived from those used in MATLAB, and are composed of a color
indicator followed by an optional line-style indicator.
1 '-'
Solid line style
2 '--'
Dashed line style
3 '-.'
Dash-dot line style
4 ':'
Dotted line style
5 '.'
Point marker
6
','
Pixel marker
7 'o'
Circle marker
8 'v'
Triangle_down marker
9 '^'
Triangle_up marker
10
'<'
Triangle_left marker
11 '>'
Triangle_right marker
12 '1'
Tri_down marker
13 '2'
Tri_up marker
14 '3'
Tri_left marker
15 '4'
Tri_right marker
16 's'
Square marker
17 'p'
Pentagon marker
18 '*'
Star marker
19 'h'
Hexagon1 marker
20 'H'
Hexagon2 marker
21 '+'
Plus marker
22 'x'
X marker
23 'D'
Diamond marker
24 'd'
Thin_diamond marker
25 '|'
Vline marker
26 '_'
Hline marker
Character Color
'b' Blue
'g' Green
'r' Red
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White
To display the circles representing points, instead of the line in the above example,
use “ob”as the format string in plot() function.
Example
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(1,11)
y = 2 * x + 5
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y,"ob")
plt.show()
With a simple chart under our belts, now we can opt to output the chart to a file instead of
displaying it (or both if desired), by using the .savefig() method.
plt.savefig('books_read.png')
The .savefig() method requires a filename be specified as the first argument. This filename
can be a full path and as seen above, can also include a particular file extension if desired. If
no extension is provided, the configuration value of savefig.format is used instead.
# line 1 points
x1 = [1,2,3]
y1 = [2,4,1]
# plotting the line 1 points
plt.plot(x1, y1, label = "line 1")
# line 2 points
x2 = [1,2,3]
y2 = [4,1,3]
# plotting the line 2 points
plt.plot(x2, y2, label = "line 2")
Here, we plot two lines on same graph. We differentiate between them by giving them
a name(label) which is passed as an argument of .plot() function.
The small rectangular box giving information about type of line and its color is called
legend. We can add a legend to our plot using .legend() function.
Customization of Plots
# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]
Bar chart
import matplotlib.pyplot as plt
# heights of bars
height = [10, 24, 36, 40, 5]
Pie chart
# defining labels
activities = ['eat', 'sleep', 'work', 'play']
# plotting legend
plt.legend()
Compound interest
Import pylab
principal = 10000 #initial investment
interestRate = 0.05
years = 20
values = []
for i in range(years + 1):
values.append(principal)
principal += principal*interestRate
pylab.plot(values, linewidth = 30)
pylab.savefig('FigurePlottingCompoundGrowth')
pylab.title('5% Growth, Compounded Annually')
pylab.xlabel('Years of Compounding')
pylab.ylabel('Value of Principal ($)')
pylab.show()
It is also possible to change the type size and line width used in plots. This can be done using
keyword arguments in individual calls to functions.
Thread
Threading in python is used to run multiple threads (tasks, function calls) at the same time.
Note that this does not mean that they are executed on different CPUs. Python threads will
NOT make your program faster if it already uses 100 % CPU time.
Python threads are used in cases where the execution of a task involves some waiting. One
example would be interaction with a service hosted on another computer, such as a
webserver. Threading allows python to execute other code while waiting.
Running several threads is similar to running several different programs concurrently, but
with the following benefits −
Multiple threads within a process share the same data space with the main thread
and can therefore share information or communicate with each other more easily
than if they were separate processes.
Threads sometimes called light-weight processes and they do not require much
memory overhead; they are cheaper than processes.
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction
pointer that keeps track of where within its context it is currently running.
It can be pre-empted (interrupted)
It can temporarily be put on hold (also known as sleeping) while other threads are
running - this is called yielding.
import thread
import time
while 1:
pass
To implement a new thread using the threading module, you have to do the following −
Define a new subclass of the Thread class.
Override the __init__(self [,args]) method to add additional arguments.
Then, override the run(self [,args]) method to implement what the thread should do
when started.
Once you have created the new Thread subclass, you can create an instance of it and then
start a new thread by invoking the start(), which in turn calls run() method.
Example
#!/usr/bin/python
import threading
import time
exitFlag = 0
Synchronizing Threads
The threading module provided with Python includes a simple-to-implement locking
mechanism that allows you to synchronize threads. A new lock is created by calling
the Lock() method, which returns the new lock.
The acquire(blocking) method of the new lock object is used to force threads to run
synchronously. The optional blocking parameter enables you to control whether the thread
waits to acquire the lock.
If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be
acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and
wait for the lock to be released.
The release() method of the new lock object is used to release the lock when it is no longer
required.
Example
#!/usr/bin/python
import threading
import time
threadLock = threading.Lock()
threads = []
import Queue
import threading
import time
exitFlag = 0