Ch - 3 Advance Python
Ch - 3 Advance Python
Sem - 6
TOPICS COVERED :
Page 1 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
There are various toolkits available that are used to enhance the functionality of the
matplotlib.
Some of these tools are downloaded separately, others can be shifted with the matplotlib
source code but have external dependencies.
Bashmap: It is a map plotting toolkit with several map projections,
coastlines, and political boundaries.
Cartopy: It is a mapping library consisting of object-oriented map projection
definitions,and arbitrary point, line, polygon, and image transformation abilities.
Excel tools: Matplotlib provides the facility to utilities for exchanging
data with Microsoft Excel.
Mplot3d: It is used for 3D plots.
Natgrid: It is an interface to the Natgrid library for irregular gridding of the spaced data.
Data Visualization:
Page 2 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Graphics provides an excellent approach for exploring the data, which is essential for
presenting results.
Data visualization is a new term.
It expresses the idea that involves more than just representing data in the graphical form
(instead of using textual form).
This can be very helpful when discovering and getting to know a dataset and can help
with classifying patterns, corrupt data, outliers, and much more.
With a little domain knowledge, data visualizations can be used to express and
demonstrate key relationships in plots and charts.
The static does indeed focus on quantitative description and estimations of data.
It provides an important set of tools for gaining a qualitative understanding.
There are five key plots that are used for data visualization.
1. Visualize: We analyze the raw data, which means it makes complex data
more accessible, understandable, and more usable. Tabular data
representation is used where the user will look up a specific measurement,
while the chart of several types is used to show patterns or relationships in the
data for one or more variables.
2. Analysis: Data analysis is defined as cleaning, inspecting, transforming, and
modeling data to derive useful information. Whenever we make a decision for
the business or in daily life, is by past experience. What will happen to
choose a particular decision, it is nothing but analyzing our past. That may
be affected in the future, so the proper analysisis necessary for better
decisions for any business or organization.
3. Document Insight: Document insight is the process where the useful data or
information is organized in the document in the standard format.
4. Transform Data Set: Standard data is used to make the decision more
effectively.
Page 3 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
The ability to make these types of correlations enables the executives to identify the root
cause of the problem and act quickly to resolve it.
Suppose a food company is looking their monthly customer data, and the data is
presented with bar charts, which shows that the company's score has dropped by five
points in the previous months in that particular region; the data suggest that there's a
problem with customer satisfaction in this area.
Page 4 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Matplotlib Architecture:
There are three different layers in the architecture of the matplotlib which are the
following:
1. Backend Layer
2. Artist layer
3. Scripting layer
1. Backend layer:
The backend layer is the bottom layer of the figure, which consists of the implementation
of the various functions that are necessary for plotting.
There are three essential classes from the backend layer FigureCanvas(The surface on
which the figure will be drawn), Renderer(The class that takes care of the drawing on the
surface), and Event(It handle the mouse and keyboard events).
2. Artist Layer:
The artist layer is the second layer in the architecture.
It is responsible for the various plotting functions, like axis, which coordinates on how to
use the renderer on the figure canvas.
3. Scripting layer:
The scripting layer is the topmost layer on which most of our code will run.
The methods in the scripting layer, almost automatically take care of the other layers, and
all we need to care about is the current state (figure & subplot).
Page 5 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
2. Axes:
A Figure can contain several Axes.
It consists of two or three (in the case of 3D) Axis objects.
Each Axes is comprised of a title, an x-label, and a y-label.
3. Axis:
Axises are the number of line like objects and responsible for generating the
graph limits.
4. Artist:
An artist is the all which we see on the graph like Text objects, Line2D
objects, and collection objects.
Most Artists are tied to Axes.
If this command fails, then use a python distribution that already has Matplotlib
installed, like Anaconda, Spyder etc.
2. Import Matplotlib:
Once Matplotlib is installed, import it in your applications by adding the import
module statement:
import matplotlib
Now Matplotlib is imported and ready to use:
4. Pyplot:
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported
under the plt alias:
import matplotlib.pyplot as plt
Page 6 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
Plot:
import matplotlib.pyplot as plt
import numpy as np
plt.plot([1,1])
plt.show()
Output:
Page 7 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Figure:
It is a diagram or a shape that can be formed by a collection of plots in different
dimensions.
Output:
Graph:
from matplotlib import pyplot as plt
#ploting our canvas
plt.plot([1,2,3],[4,5,1])
#display the graph
plt.show()
Page 8 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
It takes only three lines to plot a simple graph using the Python matplotlib.
We can add titles, labels to our chart which are created by Python matplotlib library to
make it more meaningful.
The example is the following:
Output:
Page 9 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
In the above program, it plots the graph x-axis ranges from 0-4 and the y-axis from 1-5.
If we provide a single list to the plot(), matplotlib assumes it is a sequence of y values, and
automatically generates the x values.
Since we know that python index starts at 0, the default x vector has the same length as y
but starts at 0.
Hence the x data are [0, 1, 2, 3, 4].
We can pass the arbitrary number of arguments to the plot().
For example, to plot x versus y, we can do this following way:
Page 10 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
Output:
Page 11 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Character Color
'b' Blue
'g' Green
'r' Red
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White
Page 12 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
In the above program, we have plotted the categorical graph using the subplot() function.
Let's a have a look on the subplot() function.
What is subplot():
The Matplotlib subplot() function is defined as to plot two or more plots in one figure.
We can use this method to separate two graphs which plotted in the same axis Matplotlib
supports all kinds of subplots, including 2x1 vertical, 2x1 horizontal, or a 2x2 grid.
It accepts the three arguments: they are nrows, ncols, and index.
It denote the number of rows, number of columns and the index.
The subplot() function can be called in the following way:
subplot(nrows,ncols,index,**kwargs)
subplot(pos,**kwargs)
subplot(ax)
Parameters:
1. *args:
Three separate integers or three-digit integer describes the position of the subplot.
If the three integers are nrows, ncols, and index in order, the subplot will take the index
position on a grid with nrows row and ncol column.
The argument pos are a three-digit integer, where the first digit is denoted the number of
rows, the second digit denoted the number of columns, and the third represents the
index of the subplot.
For example, subplot (1, 3, 2) is the same as the subplot (132).
Page 13 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
2. **kwargs:
The subplot() function also accepts the keyword arguments for the returned axes base
class.
Output:
Page 14 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
Plotting curves is done with the plot command. It takes a pair of same-length arrays (or
sequences) –
Output:
Page 15 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
2. Bar graphs:
Bar graphs are one of the most common types of graphs and are used to show data
associated with the categorical variables.
Matplotlib provides a bar() to make bar graphs which accepts arguments such as:
categorical variables, their value and color.
Output:
Page 16 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
Let's have a look on the other example using the style() function:
Output:
Similarly to vertical stack, the bar graph together by using the bottom argument and
define the bar graph, which we want to stack below and its value.
Page 17 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
+
3. Pie Chart:
A pie chart is a circular graph that is broken down in the segment or slices of pie.
It is generally used to represent the percentage or proportional data where each slice of
pie represents a particular category.
Let's have a look at the below example:
Page 18 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
4. Histogram:
First, we need to understand the difference between the bar graph and histogram.
A histogram is used for the distribution, whereas a bar chart is used to compare different
entities.
A histogram is a type of bar plot that shows the frequency of a number of values
compared to a set of values ranges.
For example we take the data of the different age group of the people and plot a
histogram with respect to the bin. Now, bin represents the range of values that are
divided into series of intervals. Bins are generally created of the same size.
Page 19 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
Output:
Page 20 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
5. Scatter plot:
The scatter plots are mostly used for comparing variables when we need to define how
much one variable is affected by another variable.
The data is displayed as a collection of points.
Each point has the value of one variable, which defines the position on the horizontal
axes, and the value of other variable represents the position on the vertical axis.
Example-1:
from matplotlib import pyplot as plt
from matplotlib import style
style.use('ggplot')
x = [5,7,10]
y = [18,10,6]
x2 = [6,9,11]
y2 = [7,14,17]
plt.scatter(x, y)
plt.scatter(x2, y2, color='g')
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
Output:
Example-2:
import matplotlib.pyplot as plt
x = [2, 2.5, 3, 3.5, 4.5, 4.7, 5.0]
y = [7.5, 8, 8.5, 9, 9.5, 10, 10.5]
x1 = [9, 8.5, 9, 9.5, 10, 10.5, 12]
y1 = [3, 3.5, 4.7, 4, 4.5, 5, 5.2]
plt.scatter(x, y, label='high income low saving', color='g')
plt.scatter(x1, y1, label='low income high savings', color='r')
plt.xlabel('saving*100')
plt.ylabel('income*1000')
plt.title('Scatter Plot')
Page 21 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
plt.legend()
plt.show()
Output:
Thread:
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 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.
Page 22 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Example:
#!/usr/bin/python
import thread
import time
while 1:
pass
Output:
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
Although it is very effective for low-level threading, but the thread module is very limited
compared to the newer threading module.
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
Page 23 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
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.
Example:
#!/usr/bin/python
import threading
import time
exitFlag = 0
Page 24 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
counter -= 1
Output:
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 threads 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.
Page 25 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Example:
#!/usr/bin/python
import threading
import time
threadLock = threading.Lock()
threads = []
Page 26 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Output:
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:
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
Page 27 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
queueLock.release()
print "%s processing %s" % (threadName, data)
else:
queueLock.release()
time.sleep(1)
Output:
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
Page 28 of 29
Subject: ADVANCE PYTHON Chapter - 3 B.C.A. Sem - 6
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread
Page 29 of 29