0% found this document useful (0 votes)
2 views23 pages

2. Notebook

The document outlines the topics covered in a Python programming class, including data types, variables, control flow statements, loops, and functions. It provides examples of operations with numbers, strings, lists, dictionaries, tuples, and sets, as well as demonstrating the use of comparison and logical operators. Additionally, it introduces concepts such as list comprehension, lambda expressions, and basic operations with numpy and matplotlib.
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)
2 views23 pages

2. Notebook

The document outlines the topics covered in a Python programming class, including data types, variables, control flow statements, loops, and functions. It provides examples of operations with numbers, strings, lists, dictionaries, tuples, and sets, as well as demonstrating the use of comparison and logical operators. Additionally, it introduces concepts such as list comprehension, lambda expressions, and basic operations with numpy and matplotlib.
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

20/11/2023, 00:02 Week 01_notebook

Topics covered in today's class:


* Data types
* Numbers
* Strings
* Printing
* Lists
* Dictionaries
* Booleans
* Tuples
* Sets
* Comparison Operators
* if, elif, else Statements
* for Loops
* while Loops
* range()
* list comprehension
* functions
* lambda expressions
* map and filter
* methods
* basic operation with numpy
* basic matplolib function

Data types

Numbers
In [1]: 6-3

3
Out[1]:

In [2]: 1 + 1

2
Out[2]:

In [3]: 1 * 3

3
Out[3]:

In [4]: 1 / 2

0.5
Out[4]:

In [5]: 2 ** 4

16
Out[5]:

In [6]: 4 % 2

0
Out[6]:

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 1/23


20/11/2023, 00:02 Week 01_notebook

In [7]: 5 % 2

1
Out[7]:

In [8]: (2 + 3) * (5 + 5)

50
Out[8]:

Variable Assignment
In [9]: # Can not start with number or special characters
name_of_var = 2

In [10]: x = 2
y = 3

In [11]: z = x + y

In [12]: z

5
Out[12]:

Strings
In [13]: 'single quotes'

'single quotes'
Out[13]:

In [14]: "double quotes"

'double quotes'
Out[14]:

In [15]: " wrap lot's of other quotes"

" wrap lot's of other quotes"


Out[15]:

Printing
In [16]: x = 'hello'

In [17]: x

'hello'
Out[17]:

In [18]: print(x)

hello

In [19]: num = 12
name = 'Samiul'

In [20]: print('My number is: {one}, and my name is: {two}'.format(one=num,two=name))

My number is: 12, and my name is: Samiul

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 2/23


20/11/2023, 00:02 Week 01_notebook

In [21]: print('My number is: {}, and my name is: {}'.format(num,name))

My number is: 12, and my name is: Samiul

Python Collections (Arrays)


There are four collection data types in the Python
programming language:
List is a collection which is ordered and changeable. Allows duplicate members.
Dictionary is a collection which is ordered** and changeable. No duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.

Lists
In [22]: [1,2,3]

[1, 2, 3]
Out[22]:

In [23]: [1,2,2,33]

[1, 2, 2, 33]
Out[23]:

In [24]: ['hi',1,[1,2]]

['hi', 1, [1, 2]]


Out[24]:

In [25]: my_list = ['a','b','c']

In [26]: my_list.append('d')

In [27]: my_list

['a', 'b', 'c', 'd']


Out[27]:

In [28]: my_list[0]

'a'
Out[28]:

In [29]: my_list[1]

'b'
Out[29]:

In [30]: my_list[1:]

['b', 'c', 'd']


Out[30]:

In [31]: my_list[:1]

['a']
Out[31]:

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 3/23


20/11/2023, 00:02 Week 01_notebook

In [32]: my_list[:2]

['a', 'b']
Out[32]:

In [33]: my_list[0] = 'NEW'

In [34]: my_list

['NEW', 'b', 'c', 'd']


Out[34]:

In [35]: nest = [1,2,3,[4,5,['target']]]

In [36]: len(nest) ## to know the length of a list

4
Out[36]:

In [37]: nest[3]

[4, 5, ['target']]
Out[37]:

In [38]: nest[3][2]

['target']
Out[38]:

In [39]: nest[3][2][0]

'target'
Out[39]:

In [40]: nest = [1,2,3,[4,5,['target','bme']]]

In [41]: nest[3][2][1]

'bme'
Out[41]:

Dictionaries
In [42]: d = {'key1':'item1','key2':'item2'}

In [43]: d

{'key1': 'item1', 'key2': 'item2'}


Out[43]:

In [44]: d['key1']

'item1'
Out[44]:

In [45]: d['key1']='BME'

In [46]: d

{'key1': 'BME', 'key2': 'item2'}


Out[46]:

In [47]: del d['key1']

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 4/23


20/11/2023, 00:02 Week 01_notebook

In [48]: d

{'key2': 'item2'}
Out[48]:

In [49]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)## Duplicates Not Allowed

{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

In [50]: len(thisdict)

3
Out[50]:

Booleans
In [51]: True

True
Out[51]:

In [52]: False

False
Out[52]:

Tuples
In [53]: t = (1,2,3)

In [54]: t[0]

1
Out[54]:

In [55]: t[0] = 'NEW'

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[55], line 1
----> 1 t[0] = 'NEW'

TypeError: 'tuple' object does not support item assignment

In [56]: thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

('apple', 'banana', 'cherry', 'apple', 'cherry')

In [57]: thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets


print(thistuple)

('apple', 'banana', 'cherry')

Sets
In [58]: {1,2,3}

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 5/23


20/11/2023, 00:02 Week 01_notebook
{1, 2, 3}
Out[58]:

In [59]: {1,2,3,1,2,1,2,3,3,3,3,2,2,2,1,1,2}

{1, 2, 3}
Out[59]:

Comparison Operators
In [60]: 1 > 2

False
Out[60]:

In [61]: 1 < 2

True
Out[61]:

In [62]: 1 >= 1

True
Out[62]:

In [63]: 1 <= 4

True
Out[63]:

In [64]: 1 == 1

True
Out[64]:

In [65]: 'hi' == 'bye'

False
Out[65]:

Logic Operators
In [66]: (1 > 2) and (2 < 3)

False
Out[66]:

In [67]: (1 > 2) or (2 < 3)

True
Out[67]:

In [68]: (1 == 2) or (2 == 3) or (4 == 4)

True
Out[68]:

if, elif, else Statements


In [69]: if 1 < 2:
print('Yep!')

Yep!

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 6/23


20/11/2023, 00:02 Week 01_notebook

In [70]: if 1 < 2:
print('yep!')

yep!

In [71]: if 1 < 2:
print('first')
else:
print('last')

first

In [72]: if 1 > 2:
print('first')
else:
print('last')

last

In [73]: if 1 != 2:
print('first')
elif 3 == 3:
print('middle')
else:
print('Last')

first

for Loops
In [74]: seq = [1,2,3,4,5]

In [75]: for item in seq:


print(item)

1
2
3
4
5

In [76]: for item in seq:


print('Yep')

Yep
Yep
Yep
Yep
Yep

In [77]: for jelly in seq:


print(jelly+jelly)

2
4
6
8
10

while Loops

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 7/23


20/11/2023, 00:02 Week 01_notebook

In [78]: i = 1
while i < 5:
print('i is: {}'.format(i))
i = i+1

i is: 1
i is: 2
i is: 3
i is: 4

range()
In [79]: range(5)

range(0, 5)
Out[79]:

In [80]: for i in range(5):


print(i)

0
1
2
3
4

In [81]: list(range(-3,3))

[-3, -2, -1, 0, 1, 2]


Out[81]:

In [82]: list(range(-3,4))

[-3, -2, -1, 0, 1, 2, 3]


Out[82]:

list comprehension
In [83]: x = [1,2,3,4]

In [84]: out = []
for item in x:
[Link](item**2)
print(out)

[1, 4, 9, 16]

In [85]: [item**2 for item in x]

[1, 4, 9, 16]
Out[85]:

functions
In [86]: def my_func(param1='default'):
"""
Docstring goes here.
"""
print(param1)

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 8/23


20/11/2023, 00:02 Week 01_notebook

In [87]: my_func

<function __main__.my_func(param1='default')>
Out[87]:

In [88]: my_func()

default

In [89]: my_func('new param')

new param

In [90]: my_func(param1='new param')

new param

In [91]: def square(x):


return x**2

In [92]: out = square(2)

In [93]: print(out)

Example
Define a function arithmeticIf(v, a, b, c) that returns a if v is greater than 0, b if v is equal
to 0, and c if it is less than 0. Your function should have type (num, , , ) -> , where, by *
we mean that it could be any type.

In [94]: def arithmeticIf(v,a,b,c):


if v>0:
return a
elif v==0:
return b
else:
return c
print(arithmeticIf(5, 'Peter', 'Paul', 'Mary'))

Peter

Add in your report as home work


Define a function p2(x) that takes an integer parameter x. If x is greater than 1, the
function returns the largest power of two that is less than x; otherwise, it returns 0. Use
a loop.

In [ ]:

lambda expressions
In [95]: def times2(var):
return var*2

In [96]: times2(2)

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 9/23


20/11/2023, 00:02 Week 01_notebook
4
Out[96]:

In [97]: x = lambda var: var*2

In [98]: x(2)

4
Out[98]:

Why Use Lambda Functions?


The power of lambda is better shown when you use them as
an anonymous function inside another function.
In [99]: def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))

33

map and filter


In [100… seq = [1,2,3,4,5]

In [101… map(times2,seq)

<map at 0x1a25b1eb7c0>
Out[101]:

In [102… list(map(times2,seq))

[2, 4, 6, 8, 10]
Out[102]:

In [103… list(map(lambda var: var*2,seq))

[2, 4, 6, 8, 10]
Out[103]:

In [104… filter(lambda item: item%2 == 0,seq)

<filter at 0x1a25b231130>
Out[104]:

In [105… list(filter(lambda item: item%2 == 0,seq))

[2, 4]
Out[105]:

methods
In [106… st = 'Hello Clarice'

In [107… [Link]()

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 10/23


20/11/2023, 00:02 Week 01_notebook
'hello clarice'
Out[107]:

In [108… [Link]()

'HELLO CLARICE'
Out[108]:

In [109… [Link]()

['Hello', 'Clarice']
Out[109]:

In [110… tweet = 'Go Sports! #Sports'

In [111… [Link]('#')

['Go Sports! ', 'Sports']


Out[111]:

In [112… [Link]('#')[1]

'Sports'
Out[112]:

In [113… d = {'key1':'item1','key2':'item2'}

In [114… [Link]()

dict_keys(['key1', 'key2'])
Out[114]:

In [115… [Link]()

dict_items([('key1', 'item1'), ('key2', 'item2')])


Out[115]:

In [116… lst = [1,2,3]

In [117… [Link]()

3
Out[117]:

In [118… lst

[1, 2]
Out[118]:

In [119… 'x' in [1,2,3]

False
Out[119]:

In [120… 'x' in ['x','y','z']

True
Out[120]:

Using NumPy
Once you've installed NumPy you can import it as a library:

In [121… import numpy as np

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 11/23


20/11/2023, 00:02 Week 01_notebook

In [122… print([Link](1,10))

[ 1. 1.18367347 1.36734694 1.55102041 1.73469388 1.91836735


2.10204082 2.28571429 2.46938776 2.65306122 2.83673469 3.02040816
3.20408163 3.3877551 3.57142857 3.75510204 3.93877551 4.12244898
4.30612245 4.48979592 4.67346939 4.85714286 5.04081633 5.2244898
5.40816327 5.59183673 5.7755102 5.95918367 6.14285714 6.32653061
6.51020408 6.69387755 6.87755102 7.06122449 7.24489796 7.42857143
7.6122449 7.79591837 7.97959184 8.16326531 8.34693878 8.53061224
8.71428571 8.89795918 9.08163265 9.26530612 9.44897959 9.63265306
9.81632653 10. ]

In [123… print([Link](1,10,5))

[ 1. 3.25 5.5 7.75 10. ]

In [124… print([Link](1,10,5))

[ 1. 3.25 5.5 7.75 10. ]

Numpy has many built-in functions and capabilities. We won't cover them all but instead we
will focus on some of the most important aspects of Numpy: vectors,arrays,matrices, and
number generation. Let's start by discussing arrays.

Numpy Arrays
NumPy arrays are the main way we will use Numpy throughout the course. Numpy arrays
essentially come in two flavors: vectors and matrices. Vectors are strictly 1-d arrays and
matrices are 2-d (but you should note a matrix can still have only one row or one column).

Let's begin our introduction by exploring how to create NumPy arrays.

Creating NumPy Arrays


From a Python List
We can create an array by directly converting a list or list of lists:

In [125… my_list = [1,2,3]


my_list

[1, 2, 3]
Out[125]:

In [126… [Link](my_list)

array([1, 2, 3])
Out[126]:

In [127… my_matrix = [[1,2,3],[4,5,6],[7,8,9]]


my_matrix

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]


Out[127]:

In [128… [Link](my_matrix)

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 12/23


20/11/2023, 00:02 Week 01_notebook
array([[1, 2, 3],
Out[128]:
[4, 5, 6],
[7, 8, 9]])

Built-in Methods
There are lots of built-in ways to generate Arrays

arange
Return evenly spaced values within a given interval.

In [129… [Link](0,10)

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Out[129]:

In [130… [Link](0,11,2)

array([ 0, 2, 4, 6, 8, 10])
Out[130]:

zeros and ones


Generate arrays of zeros or ones

In [131… [Link](3)

array([0., 0., 0.])


Out[131]:

In [132… [Link]((5,5))

array([[0., 0., 0., 0., 0.],


Out[132]:
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])

In [133… [Link](3)

array([1., 1., 1.])


Out[133]:

In [134… [Link]((3,3))

array([[1., 1., 1.],


Out[134]:
[1., 1., 1.],
[1., 1., 1.]])

linspace
Return evenly spaced numbers over a specified interval.

In [135… [Link](0,10,3)

array([ 0., 5., 10.])


Out[135]:

In [136… [Link](0,10,50)

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 13/23


20/11/2023, 00:02 Week 01_notebook
array([ 0. , 0.20408163, 0.40816327, 0.6122449 , 0.81632653,
Out[136]:
1.02040816, 1.2244898 , 1.42857143, 1.63265306, 1.83673469,
2.04081633, 2.24489796, 2.44897959, 2.65306122, 2.85714286,
3.06122449, 3.26530612, 3.46938776, 3.67346939, 3.87755102,
4.08163265, 4.28571429, 4.48979592, 4.69387755, 4.89795918,
5.10204082, 5.30612245, 5.51020408, 5.71428571, 5.91836735,
6.12244898, 6.32653061, 6.53061224, 6.73469388, 6.93877551,
7.14285714, 7.34693878, 7.55102041, 7.75510204, 7.95918367,
8.16326531, 8.36734694, 8.57142857, 8.7755102 , 8.97959184,
9.18367347, 9.3877551 , 9.59183673, 9.79591837, 10. ])

eye
Creates an identity matrix

In [137… [Link](4)

array([[1., 0., 0., 0.],


Out[137]:
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])

Random
Numpy also has lots of ways to create random number arrays:

rand
Create an array of the given shape and populate it with random samples from a uniform
distribution over [0, 1) .

In [138… [Link](2)

array([0.50550964, 0.25166773])
Out[138]:

In [139… [Link](5,5)

array([[0.9897932 , 0.29453654, 0.98248183, 0.24356526, 0.85299123],


Out[139]:
[0.92704746, 0.52613744, 0.94154061, 0.52733483, 0.27718488],
[0.18856687, 0.13919424, 0.82720841, 0.34838297, 0.25220906],
[0.13488448, 0.62365033, 0.83303298, 0.56106519, 0.15663543],
[0.08014091, 0.25570997, 0.74956495, 0.47607567, 0.99682665]])

randn
Return a sample (or samples) from the "standard normal" distribution. Unlike rand which is
uniform:

In [140… [Link](2)

array([0.05655596, 0.07164435])
Out[140]:

In [141… [Link](5,5)

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 14/23


20/11/2023, 00:02 Week 01_notebook
array([[-0.14829359, 0.00379048, -2.88010347, 0.2523227 , -1.93492124],
Out[141]:
[-1.0795148 , -0.25988258, 0.49041205, 1.31889468, 1.0274349 ],
[-0.31668398, -0.99374114, -0.02928407, 0.93439282, 2.0079216 ],
[-1.44491557, -2.54900413, -0.15291861, -1.85550862, -0.01303775],
[ 0.06813268, -0.01843822, -0.01500489, 0.46505612, -1.44188758]])

randint
Return random integers from low (inclusive) to high (exclusive).

In [142… [Link](1,100)

9
Out[142]:

In [143… [Link](1,100,10)

array([79, 42, 91, 5, 97, 74, 86, 33, 14, 65])


Out[143]:

Array Attributes and Methods


Let's discuss some useful attributes and methods or an array:

In [144… arr = [Link](25)


ranarr = [Link](0,50,10)

In [145… arr

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,


Out[145]:
17, 18, 19, 20, 21, 22, 23, 24])

In [146… ranarr

array([34, 4, 37, 22, 14, 11, 30, 45, 45, 49])


Out[146]:

Reshape
Returns an array containing the same data with a new shape.

In [147… arr=[Link](1,10,25)
print(arr)

[ 1. 1.375 1.75 2.125 2.5 2.875 3.25 3.625 4. 4.375


4.75 5.125 5.5 5.875 6.25 6.625 7. 7.375 7.75 8.125
8.5 8.875 9.25 9.625 10. ]

In [148… print([Link])

(25,)

In [149… [Link](5,5)

array([[ 1. , 1.375, 1.75 , 2.125, 2.5 ],


Out[149]:
[ 2.875, 3.25 , 3.625, 4. , 4.375],
[ 4.75 , 5.125, 5.5 , 5.875, 6.25 ],
[ 6.625, 7. , 7.375, 7.75 , 8.125],
[ 8.5 , 8.875, 9.25 , 9.625, 10. ]])

In [150… print([Link])

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 15/23


20/11/2023, 00:02 Week 01_notebook
(25,)

In [151… arr_new=[Link](5,5)

In [152… print(arr_new.shape)

(5, 5)

In [153… a=[1,2,3]

In [154… b=[Link]()

In [155… b[0]=71

In [156… a

[1, 2, 3]
Out[156]:

In [157… b

[71, 2, 3]
Out[157]:

max, min, argmax, argmin


These are useful methods for finding max or min values. Or to find their index locations
using argmin or argmax

In [158… ranarr

array([34, 4, 37, 22, 14, 11, 30, 45, 45, 49])


Out[158]:

In [159… [Link]()

49
Out[159]:

In [160… [Link]()

9
Out[160]:

In [161… [Link]()

4
Out[161]:

In [162… [Link]()

1
Out[162]:

Shape
Shape is an attribute that arrays have (not a method):

In [163… # Vector
[Link]

(25,)
Out[163]:

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 16/23


20/11/2023, 00:02 Week 01_notebook

In [164… # Notice the two sets of brackets


[Link](1,25)

array([[ 1. , 1.375, 1.75 , 2.125, 2.5 , 2.875, 3.25 , 3.625,


Out[164]:
4. , 4.375, 4.75 , 5.125, 5.5 , 5.875, 6.25 , 6.625,
7. , 7.375, 7.75 , 8.125, 8.5 , 8.875, 9.25 , 9.625,
10. ]])

In [165… [Link](1,25).shape

(1, 25)
Out[165]:

In [166… [Link](25,1)

array([[ 1. ],
Out[166]:
[ 1.375],
[ 1.75 ],
[ 2.125],
[ 2.5 ],
[ 2.875],
[ 3.25 ],
[ 3.625],
[ 4. ],
[ 4.375],
[ 4.75 ],
[ 5.125],
[ 5.5 ],
[ 5.875],
[ 6.25 ],
[ 6.625],
[ 7. ],
[ 7.375],
[ 7.75 ],
[ 8.125],
[ 8.5 ],
[ 8.875],
[ 9.25 ],
[ 9.625],
[10. ]])

In [167… [Link](25,1).shape

(25, 1)
Out[167]:

dtype
You can also grab the data type of the object in the array:

In [168… [Link]

dtype('float64')
Out[168]:

Matplotlib Overview Lecture


Matplotlib is the "grandfather" library of data visualization with Python. It was created by
John Hunter. He created it to try to replicate MatLab's (another programming language)
plotting capabilities in Python. So if you happen to be familiar with matlab, matplotlib will
feel natural to you.
localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 17/23
20/11/2023, 00:02 Week 01_notebook

It is an excellent 2D and 3D graphics library for generating scientific figures.

Some of the major Pros of Matplotlib are:

* Generally easy to get started for simple plots


* Support for custom labels and texts
* Great control of every element in a figure
* High-quality output in many formats
* Very customizable in general

In [169… import [Link] as plt

In [170… %matplotlib inline

In [171… import numpy as np


x = [Link](0, 5, 11)
y = x ** 2

In [172… x

array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ])


Out[172]:

In [173… y

array([ 0. , 0.25, 1. , 2.25, 4. , 6.25, 9. , 12.25, 16. ,


Out[173]:
20.25, 25. ])

Basic Matplotlib Commands


We can create a very simple line plot using the following ( I encourage you to pause and use
Shift+Tab along the way to check out the document strings for the functions we are using).

In [174… [Link]

<function [Link](xlabel, fontdict=None, labelpad=None, *, loc=No


Out[174]:
ne, **kwargs)>

In [175… [Link](x, y, 'r') # 'r' is the color red


[Link]('X Axis Title Here')
[Link]('Y Axis Title Here')
[Link]('String Title Here')
[Link]()

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 18/23


20/11/2023, 00:02 Week 01_notebook

A common issue with matplolib is overlapping subplots or figures. We ca use


fig.tight_layout() or plt.tight_layout() method, which automatically adjusts the positions of
the axes on the figure canvas so that there is no overlapping content:

In [176… # [Link](nrows, ncols, plot_number)


[Link](1,2,1)
[Link](x, y, 'r--') # More on color options later
[Link](1,2,2)
[Link](y, x, 'g*-');

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 19/23


20/11/2023, 00:02 Week 01_notebook

Introduction to the Object Oriented Method


The main idea in using the more formal Object Oriented method is to create figure objects
and then just call methods or attributes off of that object. This approach is nicer when
dealing with a canvas that has multiple plots on it.

To begin we create a figure instance. Then we can add axes to that figure:

In [177… fig = [Link](figsize=(8,4), dpi=100)


fig, axes = [Link](figsize=(12,3))

[Link](x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
[Link]("[Link]", dpi=200)

<Figure size 800x400 with 0 Axes>

In [178… fig = [Link]()

ax = fig.add_axes([0,0,1,1])

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 20/23


20/11/2023, 00:02 Week 01_notebook
[Link](x, x**2, label="x**2")
[Link](x, x**3, label="x**3")
[Link]()

<[Link] at 0x1a25d878700>
Out[178]:

We can also define colors by their names or RGB hex codes and optionally provide an alpha
value using the color and alpha keyword arguments. Alpha indicates opacity.

In [179… fig, ax = [Link]()

[Link](x, x+1, color="blue", alpha=0.5) # half-transparant


[Link](x, x+2, color="#8B008B") # RGB hex code
[Link](x, x+3, color="#FF8C00") # RGB hex code

[<[Link].Line2D at 0x1a25d8cb5b0>]
Out[179]:

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 21/23


20/11/2023, 00:02 Week 01_notebook

To change the line width, we can use the linewidth or lw keyword argument. The line
style can be selected using the linestyle or ls keyword arguments:

In [180… fig, ax = [Link](figsize=(12,6))

[Link](x, x+1, color="red", linewidth=0.25)


[Link](x, x+2, color="red", linewidth=0.50)
[Link](x, x+3, color="red", linewidth=1.00)
[Link](x, x+4, color="red", linewidth=2.00)

# possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’


[Link](x, x+5, color="green", lw=3, linestyle='-')
[Link](x, x+6, color="green", lw=3, ls='-.')
[Link](x, x+7, color="green", lw=3, ls=':')

# custom dash
line, = [Link](x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...

# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4
[Link](x, x+ 9, color="blue", lw=3, ls='-', marker='+')
[Link](x, x+10, color="blue", lw=3, ls='--', marker='o')
[Link](x, x+11, color="blue", lw=3, ls='-', marker='s')
[Link](x, x+12, color="blue", lw=3, ls='--', marker='1')

# marker size and color


[Link](x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
[Link](x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
[Link](x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerface
[Link](x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8,
markerfacecolor="yellow", markeredgewidth=3, markeredgecolor="green");

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 22/23


20/11/2023, 00:02 Week 01_notebook

Acknowledgement: Samiul Based Shuvo

That's all, folks!

localhost:8888/nbconvert/html/Studies/Undergrad/Teaching/06_July 2023/BME 310/Week 01/Week 01_notebook.ipynb?download=false 23/23

You might also like