[go: up one dir, main page]

0% found this document useful (0 votes)
3 views14 pages

Advance Python Unit - 3

This document covers the use of PyLab and Matplotlib for plotting in Python, detailing how to create various types of plots including line, bar, and pie charts, as well as customizing these plots. It also introduces threading in Python, explaining how to create and manage threads using both the thread and threading modules. Key concepts include plotting functions, customization options, and the benefits of using threads for concurrent execution.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Advance Python Unit - 3

This document covers the use of PyLab and Matplotlib for plotting in Python, detailing how to create various types of plots including line, bar, and pie charts, as well as customizing these plots. It also introduces threading in Python, explaining how to create and manage threads using both the thread and threading modules. Key concepts include plotting functions, customization options, and the benefits of using threads for concurrent execution.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT 3

Plotting using PyLab & Multithreading

Plotting using PyLab


PyLab is a module that belongs to the Python mathematics library Matplotlib. PyLab
combines the numerical module numpy with the graphical plotting module pyplot.
PyLab was designed with the interactive Python interpreter in mind, and therefore many of
its functions are short and require minimal typing.

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

Let’s start with a simple example that uses pylab.plot.

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.

2) The multiple figures

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.figure(1) #create figure 1


pylab.plot([1,2,3,4], [1,2,3,4]) #draw on figure 1
pylab.figure(2) #create figure 2
pylab.plot([1,4,2,3], [5,6,7,8]) #draw on figure 2
pylab.savefig('Figure-Addie') #save figure 2
pylab.figure(1) #go back to working on figure 1
pylab.plot([5,6,10,3]) #draw again on figure 1
pylab.savefig('Figure-Jane') #save figure 1
produces and saves to files named Figure-Jane.png and Figure- Addie.png

3) Title and label in the figure

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().

Plotting using Matplotlib

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

Following steps were followed:


1. Define the x-axis and corresponding y-axis values as lists.
2. Plot them on canvas using . plot() function.
3. Give a name to x-axis and y-axis using . xlabel() and . ylabel() functions.
4. Give a title to your plot using . title() function.
5. Finally, to view your plot, we use . show() function.

# importing the required module


import matplotlib.pyplot as plt

# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]

# plotting the points


plt.plot(x, y)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('My first graph!')

# function to show the plot


plt.show()
Here pyplot() is the most important function in matplotlib library, which is used to plot 2D
data. The following script plots the equation y = 2x + 5
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)
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.

Sr.No. Character & Description

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

The following color abbreviations are also defined.

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()

The savefig Method

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.

Plotting two or more lines on same plot


import matplotlib.pyplot as plt

# 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")

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Two lines on same graph!')

# show a legend on the plot


plt.legend()
# function to show the plot
plt.show()

 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

Here, we discuss some elementary customizations applicable on almost any plot.

import matplotlib.pyplot as plt

# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]

# plotting the points


plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3,
marker='o', markerfacecolor='blue', markersize=12)

# setting x and y axis range


plt.ylim(1,8)
plt.xlim(1,8)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('Some cool customizations!')

# function to show the plot


plt.show()

Bar chart
import matplotlib.pyplot as plt

# x-coordinates of left sides of bars


left = [1, 2, 3, 4, 5]

# heights of bars
height = [10, 24, 36, 40, 5]

# labels for bars


tick_label = ['one', 'two', 'three', 'four', 'five']

# plotting a bar chart


plt.bar(left, height, tick_label = tick_label,
width = 0.8, color = ['red', 'green'])

# naming the x-axis


plt.xlabel('x - axis')
# naming the y-axis
plt.ylabel('y - axis')
# plot title
plt.title('My bar chart!')

# function to show the plot


plt.show()

 Here, we use plt.bar() function to plot a bar chart.


 x-coordinates of left side of bars are passed along with heights of bars.
 you can also give some name to x-axis coordinates by defining tick_labels

Pie chart

import matplotlib.pyplot as plt

# defining labels
activities = ['eat', 'sleep', 'work', 'play']

# portion covered by each label


slices = [3, 7, 8, 6]

# color for each label


colors = ['r', 'y', 'g', 'b']

# plotting the pie chart


plt.pie(slices, labels = activities, colors=colors,
startangle=90, shadow = True, explode = (0, 0, 0.1, 0),
radius = 1.2, autopct = '%1.1f%%')

# plotting legend
plt.legend()

# showing the plot


plt.show()

 Here, we plot a pie chart by using plt.pie() method.


 First of all, we define the labels using a list called activities.
 Then, portion of each label can be defined using another list called slices.
 Color for each label is defined using a list called colors.
 shadow = True will show a shadow beneath each label in pie-chart.
 startangle rotates the start of the pie chart by given degrees counterclockwise from the
x-axis.
 explode is used to set the fraction of radius with which we offset each wedge.
 autopct is used to format the value of each label. Here, we have set it to show the
percentage value only upto 1 decimal place.

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.

Starting a New Thread


 To spawn another thread, you need to call following method available
in thread module −
 thread.start_new_thread ( function, args[, kwargs] )
 This method call enables a fast and efficient way to create new threads in both Linux
and Windows.
 The method call returns immediately and the child thread starts and calls function
with the passed list of args. When function returns, the thread terminates.
 Here, args is a tuple of arguments; use an empty tuple to call function without
passing any arguments. kwargs is an optional dictionary of keyword arguments.
Example
#!/usr/bin/python

import thread
import time

# Define a function for the thread


def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows


try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"

while 1:
pass

When the above code is executed, it produces the following result −


Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009

The Threading Module


The newer threading module included with Python 2.4 provides much more powerful, high-
level support for threads than the thread module discussed in the previous section.
The threading module exposes all the methods of the thread module and provides some
additional methods −
 threading.activeCount() − Returns the number of thread objects that are active.
 threading.currentThread() − Returns the number of thread objects in the caller's
thread control.
 threading.enumerate() − Returns a list of all thread objects that are currently active.
In addition to the methods, the threading module has the Thread class that implements
threading. The methods provided by the Thread class are as follows −
 run() − The run() method is the entry point for a thread.
 start() − The start() method starts a thread by calling the run method.
 join([time]) − The join() waits for threads to terminate.
 isAlive() − The isAlive() method checks whether a thread is still executing.
 getName() − The getName() method returns the name of a thread.
 setName() − The setName() method sets the name of a thread.

Creating Thread Using Threading Module

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

class myThread (threading.Thread):


def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, 5, self.counter)
print "Exiting " + self.name

def print_time(threadName, counter, delay):


while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1

# Create new threads


thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads


thread1.start()
thread2.start()

print "Exiting Main Thread"

When the above code is executed, it produces the following result −


Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2

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

class myThread (threading.Thread):


def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1

threadLock = threading.Lock()
threads = []

# Create new threads


thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads


thread1.start()
thread2.start()

# Add threads to thread list


threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete


for t in threads:
t.join()
print "Exiting Main Thread"

When the above code is executed, it produces the following result −


Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread

Multithreaded Priority Queue


The Queue module allows you to create a new queue object that can hold a specific
number of items. There are following methods to control the Queue −
 get() − The get() removes and returns an item from the queue.
 put() − The put adds item to a queue.
 qsize() − The qsize() returns the number of items that are currently in the queue.
 empty() − The empty( ) returns True if queue is empty; otherwise, False.
 full() − the full() returns True if queue is full; otherwise, False.
Example
#!/usr/bin/python

import Queue
import threading
import time

exitFlag = 0

class myThread (threading.Thread):


def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print "Starting " + self.name
process_data(self.name, self.q)
print "Exiting " + self.name

def process_data(threadName, q):


while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print "%s processing %s" % (threadName, data)
else:
queueLock.release()
time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]


nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1

# Create new threads


for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1

# Fill the queue


queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()

# Wait for queue to empty


while not workQueue.empty():
pass

# Notify threads it's time to exit


exitFlag = 1

# Wait for all threads to complete


for t in threads:
t.join()
print "Exiting Main Thread"

When the above code is executed, it produces the following result −


Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread

You might also like