0% found this document useful (0 votes)
10 views39 pages

Python Lab Latest

The document provides an overview of Python programming concepts, including identifiers, keywords, indentation, comments, and various data structures such as strings, lists, tuples, and dictionaries. It also covers the use of NumPy for array manipulation, indexing, and structured arrays, as well as basic operations in Pandas for creating and managing Series and DataFrames. Each section includes example code snippets to illustrate the concepts discussed.

Uploaded by

jonwik6965
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)
10 views39 pages

Python Lab Latest

The document provides an overview of Python programming concepts, including identifiers, keywords, indentation, comments, and various data structures such as strings, lists, tuples, and dictionaries. It also covers the use of NumPy for array manipulation, indexing, and structured arrays, as well as basic operations in Pandas for creating and managing Series and DataFrames. Each section includes example code snippets to illustrate the concepts discussed.

Uploaded by

jonwik6965
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/ 39

Program 1- Write programs to understand the use of Python Identifiers, Keywords,

Indentations, Comments in Python, Operators, Membership operator.

Program-

There are 33 keywords in Python 3.7. This number can vary slightly over the course of time.

False await else import pass

None break except in raise

True class finally is return

And continue for lambda try

As def from nonlocal while

Assert del global not with

Async elif if or yield

Python Identifiers

An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.

global = 1

Output

File "<interactive input>", line 1

global = 1

SyntaxError: invalid syntax

1. We cannot use special symbols like !, @, #, $, % etc. in our identifier.

1
a@ = 0

Output

File "<interactive input>", line 1

a@ = 0

SyntaxError: invalid syntax

2. An identifier can be of any length.

Python Statement, Indentation and Comments

In this tutorial, you will learn about Python statements, why indentation is important and use of
comments in programming.

Python Statement

Instructions that a Python interpreter can execute are called statements. For example, a = 1 is
an assignment statement. if statement, for statement, while statement, etc. are other kinds of
statements which will be discussed later.

Multi-line statement

In Python, the end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\). For example:

a=1+2+3+\

4+5+6+\

7+8+9

This is an explicit line continuation. In Python, line continuation is implied inside parentheses ( ),
brackets [ ], and braces { }. For instance, we can implement the above multi-line statement as:

a = (1 + 2 + 3 +

4+5+6+

2
7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [
] and { }. For example:

colors = ['red',

'blue',

'green']

We can also put multiple statements in a single line using semicolons, as follows:

a = 1; b = 2; c = 3

Python Indentation

Most of the programming languages like C, C++, and Java use braces { } to define a block of
code. Python, however, uses indentation.

for i in range(1,11):

print(i)

if i == 5:

break

The enforcement of indentation in Python makes the code look neat and clean. This results in
Python programs that look similar and consistent.

Indentation can be ignored in line continuation, but it's always a good idea to indent. It makes
the code more readable. For example:

if True:

print('Hello')

a=5

and

if True: print('Hello'); a = 5

both are valid and do the same thing, but the former style is clearer.

3
Incorrect indentation will result in IndentationError.

Python Comments

#This is a comment

#print out Hello

print('Hello')

Multi-line comments

#This is a long comment

#and it extends

#to multiple lines

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But they can be used as a multi-line
comment as well. Unless they are not docstrings, they do not generate any extra code.

"""This is also a

perfect example of

multi-line comments"""

4
Program 2- Write programs to understand the use of Python String, Tuple, List, Set, Dictionary,
File input/output.

Program-

Strings in Python
A string is a sequence of characters. It can be declared in python by using double-quotes.
Strings are immutable, i.e., they cannot be changed.

# Assigning string to a variable

a = "This is a string"

print (a)

Lists in Python
Lists are one of the most powerful tools in python. They are just like the arrays declared in
other languages. But the most powerful thing is that list need not be always homogeneous. A
single list can contain strings, integers, as well as objects. Lists can also be used for
implementing stacks and queues. Lists are mutable, i.e., they can be altered once declared.
Tuples in Python
A tuple is a sequence of immutable Python objects. Tuples are just like lists with the
exception that tuples cannot be changed once declared. Tuples are usually faster than lists.

tup =(1, "a", "string", 1+2)


print(tup)
print(tup[1])

The output is :
(1, 'a', 'string', 3)
a
Iterations in Python
Iterations or looping can be performed in python by ‘for’ and ‘while’ loops. Apart from
iterating upon a particular condition, we can also iterate on strings, lists, and tuples.

i=1
while(i<10):
print(i)
i+=1

5
The output is :
1
2
3
4
5
6
7
8
9

Iteration by for loop on string

s ="Hello World"
foriins :
print(i)

The output is :
H
e
l
l
o

W
o
r
l
d

6
Iteration by for loop on list

L =[1, 4, 5, 7, 8, 9]
for iinL:
print(i)

The output is :
1
4
5
7
8
9

Creating a list
To create a list, you use the square brackets and add elements into it accordingly. If you do not
pass any elements inside the square brackets, you get an empty list as the output.

my_list = [] #create empty list


print(my_list)
my_list = [1, 2, 3, 'example', 3.132] #creating list with data
print(my_list)
Output:
[]
[1, 2, 3, ‘example’, 3.132]

Adding Elements
Adding the elements in the list can be achieved using the append(), extend() and insert()
functions.

• The append() function adds all the elements passed to it as a single element.
• The extend() function adds the elements one-by-one into the list.
• The insert() function adds the element passed to the index value and increase the size of
the list too.

my_list = [1, 2, 3]
print(my_list)
my_list.append([555, 12]) #add as a single element
print(my_list)

7
my_list.extend([234, 'more_example']) #add as different elements
print(my_list)
my_list.insert(1, 'insert_example') #add element i
print(my_list)
Output:
[1, 2, 3]
[1, 2, 3, [555, 12]]
[1, 2, 3, [555, 12], 234, ‘more_example’]
[1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’]

8
Program 3-Write programs to understand the use of Numpy’sNdarray, Basic Operations,
Indexing, Slicing, and Iterating, Conditions and Boolean Arrays.

Program-

importnumpyas np
a =np.array([1,2,3])
print a
The output is as follows −
[1, 2, 3]

# more than one dimensions


importnumpyas np
a =np.array([[1,2],[3,4]])
print a
The output is as follows −
[[1, 2]
[3, 4]]
Example 3
.

# minimum dimensions
importnumpyas np
a =np.array([1,2,3,4,5],ndmin=2)
print a
The output is as follows −
[[1, 2, 3, 4, 5]]

#ndarray.shape
This array attribute returns a tuple consisting of array dimensions. It can also be used to resize
the array.
Example 1
.

importnumpyas np
a =np.array([[1,2,3],[4,5,6]])

9
printa.shape
The output is as follows −
(2, 3)
Example 2
# this resizes the ndarray
importnumpyas np

a =np.array([[1,2,3],[4,5,6]])
a.shape=(3,2)
print a
The output is as follows −
[[1, 2]
[3, 4]
[5, 6]]

# array of five zeros. Default dtype is float


Import numpy as np
x =np.zeros(5)
print x
The output is as follows −
[ 0. 0. 0. 0. 0.]

# array of five ones. Default dtype is float


importnumpyas np
x =np.ones(5)
print x
The output is as follows −
[ 1. 1. 1. 1. 1.]
Example 2
.

importnumpyas np
x =np.ones([2,2],dtype=int)
print x
Now, the output would be as follows −

10
[[1 1]
[1 1]]

NumPy - Indexing & Slicing

importnumpyas np
a =np.arange(10)
s = slice(2,7,2)
print a[s]
Its output is as follows −
[2 4 6]
In the above example, an ndarray object is prepared by arange() function. Then a slice object is
defined with start, stop, and step values 2, 7, and 2 respectively. When this slice object is passed
to the ndarray, a part of it starting with index 2 up to 7 with a step of 2 is sliced.
The same result can also be obtained by giving the slicing parameters separated by a colon :
(start:stop:step) directly to the ndarray object.

importnumpyas np
a =np.arange(10)
b = a[2:7:2]
print b
Here, we will get the same output −
[2 4 6]
If only one parameter is put, a single item corresponding to the index will be returned. If a : is
inserted in front of it, all items from that index onwards will be extracted. If two parameters
(with : between them) is used, items between the two indexes (not including the stop index)
with default step one are sliced.

# slice single item


importnumpyas np

a =np.arange(10)
b = a[5]
print b

11
Its output is as follows −
5

# slice items starting from index


importnumpyas np
a =np.arange(10)
print a[2:]
Now, the output would be −
[2 3 4 5 6 7 8 9]

# slice items between indexes


importnumpyas np
a =np.arange(10)
print a[2:5]
Here, the output would be −
[2 3 4]
The above description applies to multi-dimensional ndarray too.

12
Program 4- Write programs to understand the use of Numpy’s Shape Manipulation, Array
Manipulation, Vectorization

numpy.reshape
This function gives a new shape to an array without changing the data. It accepts the following
parameters −
numpy.reshape(arr, newshape, order')

importnumpyas np
a =np.arange(8)
print'The original array:'
print a
print'\n'

b =a.reshape(4,2)
print'The modified array:'
print b
Its output would be as follows −
The original array:
[0 1 2 3 4 5 6 7]

The modified array:


[[0 1]
[2 3]
[4 5]
[6 7]]

numpy.resize
This function returns a new array with the specified size. If the new size is greater than the
original, the repeated copies of entries in the original are contained. The function takes the
following parameters.
numpy.resize(arr, shape)

importnumpyas np
a =np.array([[1,2,3],[4,5,6]])

print'First array:'

13
print a
print'\n'

print'The shape of first array:'


printa.shape
print'\n'
b =np.resize(a,(3,2))

print'Second array:'
print b
print'\n'

print'The shape of second array:'


printb.shape
print'\n'
# Observe that first row of a is repeated in b since size is bigger

print'Resize the second array:'


b =np.resize(a,(3,3))
print b
The above program will produce the following output −
First array:
[[1 2 3]
[4 5 6]]

The shape of first array:


(2, 3)

Second array:
[[1 2]
[3 4]
[5 6]]

The shape of second array:


(3, 2)

Resize the second array:


[[1 2 3]
[4 5 6]
[1 2 3]]

14
Program 5-Write programs to understand the use of Numpy’s Structured Arrays, Reading and
Writing Array Data on Files.

Program-

Structured array data types can be specified in a number of ways. Earlier, we saw the dictionary
method:

np.dtype({'names':('name', 'age', 'weight'),


'formats':('U10', 'i4', 'f8')})

dtype([('name', '<U10'), ('age', '<i4'), ('weight', '<f8')])


For clarity, numerical types can be specified using Python types or NumPy dtypes instead:

np.dtype({'names':('name', 'age', 'weight'),


'formats':((np.str_, 10), int, np.float32)})

dtype([('name', '<U10'), ('age', '<i8'), ('weight', '<f4')])


A compound type can also be specified as a list of tuples:

np.dtype([('name', 'S10'), ('age', 'i4'), ('weight', 'f8')])

dtype([('name', 'S10'), ('age', '<i4'), ('weight', '<f8')])


If the names of the types do not matter to you, you can specify the types alone in a comma-
separated string:

np.dtype('S10,i4,f8')

dtype([('f0', 'S10'), ('f1', '<i4'), ('f2', '<f8')])


The shortened string format codes may seem confusing, but they are built on simple principles.
The first (optional) character is < or >, which means "little endian" or "big endian," respectively,
and specifies the ordering convention for significant bits. The next character specifies the type
of data: characters, bytes, ints, floating points, and so on (see the table below). The last
character or characters represents the size of the object in bytes.

15
CharacterDescription Example

'b' Byte np.dtype('b')

'i' Signed integer np.dtype('i4') == np.int32

'u' Unsigned integer np.dtype('u1') == np.uint8

'f' Floating point np.dtype('f8') == np.int64

'c' Complex floating pointnp.dtype('c16') == np.complex128

'S', 'a' String np.dtype('S5')

'U' Unicode string np.dtype('U') == np.str_

'V' Raw data (void) np.dtype('V') == np.void

16
Program 6- Write programs to understand the use of Pandas Series, DataFrame, Index Objects,
Reindexing, Dropping, Arithmetic and Data Alignment.

Program-

1) Series

Creating Series from Array:

Before creating a Series, Firstly, we have to import the numpy module and then use array()
function in the program.

1. import pandas as pd
2. import numpy as np
3. info = np.array(['P','a','n','d','a','s'])
4. a = pd.Series(info)
5. print(a)

Output

0 P
1 a
2 n
3 d
4 a
5 s
dtype: object

Explanation: In this code, firstly, we have imported the pandas and numpy library with
the pd and np alias. Then, we have taken a variable named "info" that consist of an array of some
values. We have called the info variable through a Series method and defined it in an "a"
variable. The Series has printed by calling the print(a) method.

Python Pandas DataFrame

Create a DataFrame using List:

We can easily create a DataFrame in Pandas using list.

1. import pandas as pd
2. # a list of strings
3. x = ['Python', 'Pandas']

17
4.
5. # Calling DataFrame constructor on list
6. df = pd.DataFrame(x)
7. print(df)

Output

0
0 Python
1 Pandas

Explanation: In this code, we have defined a variable named "x" that consist of string values. The
DataFrame constructor is being called on a list to print the values.

Pandas Index

Creating index

First, we have to take a csv file that consist some data used for indexing.

1. # importing pandas package


2. import pandas as pd
3. data = pd.read_csv("aa.csv")
4. data

Output:

Name Hire Date Salary Leaves Remaining


0 John Idle 03/15/14 50000.0 10
1 Smith Gilliam 06/01/15 65000.0 8
2 Parker Chapman 05/12/14 45000.0 10
3 Jones Palin 11/01/13 70000.0 3
4 Terry Gilliam 08/12/14 48000.0 7
5 Michael Palin 05/23/13 66000.0 8

# importing pandas package


import pandas as pd
# making data frame from csv file
info = pd.read_csv("aa.csv", index_col ="Name")

18
# retrieving multiple columns by indexing operator
a = info[["Hire Date", "Salary"]]
print(a)

Output:

Name Hire Date Salary


0 John Idle 03/15/14 50000.0
1 Smith Gilliam 06/01/15 65000.0
2 Parker Chapman 05/12/14 45000.0
3 Jones Palin 11/01/13 70000.0
4 Terry Gilliam 08/12/14 48000.0
5 Michael Palin 05/23/13 66000.0
# importing pandas package
importpandas as pd

# making data frame from csv file


info =pd.read_csv("aa.csv", index_col ="Name")

# retrieving columns by indexing operator


a =info["Salary"]
print(a)

Output:

Name Salary
0 John Idle 50000.0
1 Smith Gilliam 65000.0
2 Parker Chapman 45000.0
3 Jones Palin 70000.0
4 Terry Gilliam 48000.0
5 Michael Palin 66000.0

19
Program 7 – Write programs to understand the use of Pandas Functions by Element, Functions
by Row or Column, Statistics Functions, Sorting and Ranking, Correlation and Covariance, “Not a
Number” Data.

Program-

import pandas as pd

import numpy as np

unsorted_df=pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns=['col2',
'col1'])

print unsorted_df

Its output is as follows −

col2 col1

1 -2.063177 0.537527

4 0.142932 -0.684884

6 0.012667 -0.389340

2 -0.548797 1.848743

3 -1.044160 0.837381

5 0.385605 1.300185

9 1.031425 -1.002967

8 -0.407374 -0.435142

0 2.237453 -1.067139

7 -1.445831 -1.701035

In unsorted_df, the labels and the values are unsorted. Let us see how these can be sorted.

By Label

Using the sort_index() method, by passing the axis arguments and the order of sorting,
DataFrame can be sorted. By default, sorting is done on row labels in ascending order.

import pandas as pd

import numpy as np

20
unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns =
['col2','col1'])

sorted_df=unsorted_df.sort_index()

print sorted_df

Its output is as follows −

col2 col1

0 0.208464 0.627037

1 0.641004 0.331352

2 -0.038067 -0.464730

3 -0.638456 -0.021466

4 0.014646 -0.737438

5 -0.290761 -1.669827

6 -0.797303 -0.018737

7 0.525753 1.628921

8 -0.567031 0.775951

9 0.060724 -0.322425

Order of Sorting

By passing the Boolean value to ascending parameter, the order of the sorting can be
controlled. Let us consider the following example to understand the same.

import pandas as pd

import numpy as np

unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns =
['col2','col1'])

sorted_df = unsorted_df.sort_index(ascending=False)

print sorted_df

21
Its output is as follows −

col2 col1

9 0.825697 0.374463

8 -1.699509 0.510373

7 -0.581378 0.622958

6 -0.202951 0.954300

5 -1.289321 -1.551250

4 1.302561 0.851385

3 -0.157915 -0.388659

2 -1.222295 0.166609

1 0.584890 -0.291048

0 0.668444 -0.061294

By Value

Like index sorting, sort_values() is the method for sorting by values. It accepts a 'by' argument
which will use the column name of the DataFrame with which the values are to be sorted.

import pandas as pd

import numpy as np

unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})

sorted_df = unsorted_df.sort_values(by='col1')

print sorted_df

Its output is as follows −

col1 col2

1 1 3

2 1 2

3 1 4

0 2 1

22
Program 8- Write programs to understand the use of Pandas for Reading and Writing Data
using CSV and Textual Files, HTML Files, XML, Microsoft Excel Files.

Write a CSV File


You can save your Pandas DataFrame as a CSV file with .to_csv():

>>>df.to_csv('data.csv')
That’s it! You’ve created the file data.csv in your current working directory. You can expand the
code block below to see how your CSV file should look:

data.csvShow/Hide
This text file contains the data separated with commas. The first column contains the row
labels. In some cases, you’ll find them irrelevant. If you don’t want to keep them, then you can
pass the argument index=False to .to_csv().

Read a CSV File


Once your data is saved in a CSV file, you’ll likely want to load and use it from time to time. You
can do that with the Pandas read_csv() function:

>>>

>>>df=pd.read_csv('data.csv',index_col=0)
>>>df
COUNTRY POP AREA GDP CONT IND_DAY
CHN China 1398.72 9596.96 12234.78 Asia NaN
IND India 1351.16 3287.26 2575.67 Asia 1947-08-15
USA US 329.74 9833.52 19485.39 N.America 1776-07-04
IDN Indonesia 268.07 1910.93 1015.54 Asia 1945-08-17
BRA Brazil 210.32 8515.77 2055.51 S.America 1822-09-07
PAK Pakistan 205.71 881.91 302.14 Asia 1947-08-14
NGA Nigeria 200.96 923.77 375.77 Africa 1960-10-01
BGD Bangladesh 167.09 147.57 245.63 Asia 1971-03-26
RUS Russia 146.79 17098.25 1530.75 NaN 1992-06-12
MEX Mexico 126.58 1964.38 1158.23 N.America 1810-09-16
JPN Japan 126.22 377.97 4872.42 Asia NaN
DEU Germany 83.02 357.11 3693.20 Europe NaN
FRA France 67.02 640.68 2582.49 Europe 1789-07-14
GBR UK 66.44 242.50 2631.23 Europe NaN

23
ITA Italy 60.36 301.34 1943.84 Europe NaN
ARG Argentina 44.94 2780.40 637.49 S.America 1816-07-09
DZA Algeria 43.38 2381.74 167.56 Africa 1962-07-05
CAN Canada 37.59 9984.67 1647.12 N.America 1867-07-01
AUS Australia 25.47 7692.02 1408.68 Oceania NaN
KAZ Kazakhstan 18.53 2724.90 159.41 Asia 1991-12-16

Write an Excel File


Once you have those packages installed, you can save your DataFrame in an Excel file
with .to_excel():

>>>

>>>df.to_excel('data.xlsx')
The argument 'data.xlsx' represents the target file and, optionally, its path. The above
statement should create the file data.xlsx in your current working directory. That file should
look like this:

The first column of the file contains the labels of the rows, while the other columns store data.

Read an Excel File


You can load data from Excel files with read_excel():

24
>>>

>>>df=pd.read_excel('data.xlsx',index_col=0)
>>>df
COUNTRY POP AREA GDP CONT IND_DAY
CHN China 1398.72 9596.96 12234.78 Asia NaN
IND India 1351.16 3287.26 2575.67 Asia 1947-08-15
USA US 329.74 9833.52 19485.39 N.America 1776-07-04
IDN Indonesia 268.07 1910.93 1015.54 Asia 1945-08-17
BRA Brazil 210.32 8515.77 2055.51 S.America 1822-09-07
PAK Pakistan 205.71 881.91 302.14 Asia 1947-08-14
NGA Nigeria 200.96 923.77 375.77 Africa 1960-10-01
BGD Bangladesh 167.09 147.57 245.63 Asia 1971-03-26
RUS Russia 146.79 17098.25 1530.75 NaN 1992-06-12
MEX Mexico 126.58 1964.38 1158.23 N.America 1810-09-16
JPN Japan 126.22 377.97 4872.42 Asia NaN
DEU Germany 83.02 357.11 3693.20 Europe NaN
FRA France 67.02 640.68 2582.49 Europe 1789-07-14
GBR UK 66.44 242.50 2631.23 Europe NaN
ITA Italy 60.36 301.34 1943.84 Europe NaN
ARG Argentina 44.94 2780.40 637.49 S.America 1816-07-09
DZA Algeria 43.38 2381.74 167.56 Africa 1962-07-05
CAN Canada 37.59 9984.67 1647.12 N.America 1867-07-01
AUS Australia 25.47 7692.02 1408.68 Oceania NaN
KAZ Kazakhstan 18.53 2724.90 159.41 Asia 1991-12-16

25
Program 9-Write programs to understand the use of Matplotlib for Simple Interactive Chart, Set
the Properties of the Plot, matplotlib and NumPy

Program-

Installation of Matplotlib

If you have Python and PIP already installed on a system, then installation of Matplotlib is very
easy.

Install it using this command:

C:\Users\Your Name>pip install matplotlib

If this command fails, then use a python distribution that already has Matplotlib installed, like
Anaconda, Spyder etc.

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:

Pyplot

Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported
under the plt alias:

import matplotlib.pyplot as plt

Now the Pyplot package can be referred to as plt.

Program 1-Draw a line in a diagram from position (0,0) to position (6,250):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([0, 6])

26
ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)
plt.show()

Result:

Plotting x and y points

The plot() function is used to draw points (markers) in a diagram.

By default, the plot() function draws a line from point to point.

The function takes parameters for specifying points in the diagram.

Parameter 1 is an array containing the points on the x-axis.

Parameter 2 is an array containing the points on the y-axis.

If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to
the plot function.

Program 2-Draw a line in a diagram from position (1, 3) to position (8, 10):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)
plt.show()

27
Result:

The x-axis is the horizontal axis.

The y-axis is the vertical axis.

Plotting Without Line

To plot only the markers, you can use shortcut string notation parameter 'o', which means
'rings'.

Program 3-Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints, 'o')


plt.show()

28
Result:

Multiple Points

You can plot as many points as you like, just make sure you have the same number of points in
both axis.

Program 4-Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to
position (8, 10):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 2, 6, 8])


ypoints = np.array([3, 8, 1, 10])

plt.plot(xpoints, ypoints)
plt.show()

29
Result:

30
Program 10-Write programs to understand the use of Matplotlib for Working with Multiple
Figures and Axes, Adding Text, Adding a Grid, Adding a Legend, Saving the Charts.

Program-

Add Grid Lines to a Plot

With Pyplot, you can use the grid() function to add grid lines to the plot.

Program 1-Add grid lines to the plot:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid()

plt.show()

31
Result:

Specify Which Grid Lines to Display


import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid(axis = 'x')

plt.show()

32
Result:

Matplotlib legend

importmatplotlib.pyplotasplt
importnumpyas np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend()
plt.show()

33
Matplotlib legend on bottom
To place the legend on the bottom, change the legend() call to:

ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),&nbsp; shadow=True, ncol=2)

Take into account that we set the number of columns two ncol=2 and set a shadow.

The complete code would be:

importmatplotlib.pyplotasplt
importnumpyas np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),&nbsp; shadow=True, ncol=2)
plt.show()

34
Program 11-Write programs to understand the use of Matplotlib for Working with Line Chart,
Histogram, Bar Chart, Pie Charts

35
Program-

Creating Bars

With Pyplot, you can use the bar() function to draw bar graphs:

Program 1-Draw 4 bars:


import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x,y)
plt.show()

Result:

Creating Pie Charts

With Pyplot, you can use the pie() function to draw pie charts:

36
Program 2-A simple pie chart:
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])

plt.pie(y)
plt.show()

Result:

Create Histogram

In Matplotlib, we use the hist() function to create histograms.

The hist() function will use an array of numbers to create a histogram, the array is sent into the
function as an argument.

For simplicity we use NumPy to randomly generate an array with 250 values, where the values
will concentrate around 170, and the standard deviation is 10. Learn more about Normal Data
Distribution in our Machine Learning Tutorial.

Program 3-A Normal Data Distribution by NumPy:


import numpy as np
x = np.random.normal(170, 10, 250)
print(x)

37
Result:

This will generate a random result, and could look like this:

[167.62255766 175.32495609 152.84661337 165.50264047 163.17457988


162.29867872 172.83638413 168.67303667 164.57361342 180.81120541
170.57782187 167.53075749 176.15356275 176.95378312 158.4125473
187.8842668 159.03730075 166.69284332 160.73882029 152.22378865
164.01255164 163.95288674 176.58146832 173.19849526 169.40206527
166.88861903 149.90348576 148.39039643 177.90349066 166.72462233
177.44776004 170.93335636 173.26312881 174.76534435 162.28791953
166.77301551 160.53785202 170.67972019 159.11594186 165.36992993
178.38979253 171.52158489 173.32636678 159.63894401 151.95735707
175.71274153 165.00458544 164.80607211 177.50988211 149.28106703
179.43586267 181.98365273 170.98196794 179.1093176 176.91855744
168.32092784 162.33939782 165.18364866 160.52300507 174.14316386
163.01947601 172.01767945 173.33491959 169.75842718 198.04834503
192.82490521 164.54557943 206.36247244 165.47748898 195.26377975
164.37569092 156.15175531 162.15564208 179.34100362 167.22138242
147.23667125 162.86940215 167.84986671 172.99302505 166.77279814
196.6137667 159.79012341 166.5840824 170.68645637 165.62204521
174.5559345 165.0079216 187.92545129 166.86186393 179.78383824
161.0973573 167.44890343 157.38075812 151.35412246 171.3107829
162.57149341 182.49985133 163.24700057 168.72639903 169.05309467
167.19232875 161.06405208 176.87667712 165.48750185 179.68799986
158.7913483 170.22465411 182.66432721 173.5675715 176.85646836
157.31299754 174.88959677 183.78323508 174.36814558 182.55474697
180.03359793 180.53094948 161.09560099 172.29179934 161.22665588
171.88382477 159.04626132 169.43886536 163.75793589 157.73710983
174.68921523 176.19843414 167.39315397 181.17128255 174.2674597
186.05053154 177.06516302 171.78523683 166.14875436 163.31607668
174.01429569 194.98819875 169.75129209 164.25748789 180.25773528
170.44784934 157.81966006 171.33315907 174.71390637 160.55423274
163.92896899 177.29159542 168.30674234 165.42853878 176.46256226
162.61719142 166.60810831 165.83648812 184.83238352 188.99833856
161.3054697 175.30396693 175.28109026 171.54765201 162.08762813
164.53011089 189.86213299 170.83784593 163.25869004 198.68079225
166.95154328 152.03381334 152.25444225 149.75522816 161.79200594
162.13535052 183.37298831 165.40405341 155.59224806 172.68678385
179.35359654 174.19668349 163.46176882 168.26621173 162.97527574
192.80170974 151.29673582 178.65251432 163.17266558 165.11172588
183.11107905 169.69556831 166.35149789 178.74419135 166.28562032
169.96465166 178.24368042 175.3035525 170.16496554 158.80682882

38
187.10006553 178.90542991 171.65790645 183.19289193 168.17446717
155.84544031 177.96091745 186.28887898 187.89867406 163.26716924
169.71242393 152.9410412 158.68101969 171.12655559 178.1482624
187.45272185 173.02872935 163.8047623 169.95676819 179.36887054
157.01955088 185.58143864 170.19037101 157.221245 168.90639755
178.7045601 168.64074373 172.37416382 165.61890535 163.40873027
168.98683006 149.48186389 172.20815568 172.82947206 173.71584064
189.42642762 172.79575803 177.00005573 169.24498561 171.55576698
161.36400372 176.47928342 163.02642822 165.09656415 186.70951892
153.27990317 165.59289527 180.34566865 189.19506385 183.10723435
173.48070474 170.28701875 157.24642079 157.9096498 176.4248199 ]

39

You might also like