You are on page 1of 39

NUMERICAL METHODS

(MCSC-202)
USING PYTHON
By
Samir Shrestha
Department of Mathematics
Kathmandu University, Dhulikhel

Lecture-5
Python Packages
Python Packages
 numpy: Multi-dimensional Array Operations

 matplotlib: Plotting Library

 scipy: Scientific Computing

 pandas: DataFrame (data analysis & manipulate)

 seaborn: Statistical Data visualization


Importing Packages
Python Tips
Python Packages should be imported with their commonly
used names:

import numpy as np

import matplotlib.pyplot as plt

import scipy as sp

import pandas as pd

import seaborn as sns


References
1. H. Bhasin, Python Basics A Self-Teaching Introduction, 2019
2. H. P. Langtangen, A Primer on Scientific Programming with Python,
2016
3. Jaan Kiusalaas, Numerical Methods in Engineering with Python 3, 2013
4. Robert Johansson, Numerical Python: Scientific Computing and Data
Science Applications with Numpy, SciPy and Matplotlib, 2019
5. https://www.javatpoint.com/python-tutorial
Matplotlib
Visualization with Python
Outlines
 Introduction to matplotlib

 Plotting basic steps

 Plotting 2D-curves, Choosing colors and markers

 Subplot, Subplots

 3D-plots

 Quiver plots
Introducing Matplotlib
Matplotlib
Matplotlib is a comprehensive library for creating static, animated
and interactive visualization of data in Python
Features:
 Develops publication quality plots with just few lines of code
 Provides full control of line styles, font properties, axis properties,
color choise etc
 Export to a number of file formats and interactive environments
 The module matplotlib.pyplot is a collection of 2D/3D plotting
functions that provide Python with MATLAB-style functionality
 matplotlib doesn't come bundled with Python. It has to be
installed it separately:

In Windows: $ pip install matplotlib


In Ubuntu: $ sudo apt-get install python-matplotlib
In Anaconda distribution of Python: matplotlib comes pre-installed
If not, $ conda install matplotlib
Plotting Basic Steps
Matplotlib
Basic steps involved in plotting a graph:
 import matplotlib.pyplot as plt
 Define x data values and corresponding y data values as list or
tuple, or set, or numpy array
 Plot the data using the plot function plt.plot(x,y)
 Name x-axis and y-axis using functions plt.xlabel('x_name') ,
plt.xlabel('y_name')
 Give title of the plot using title function plt.title('Title of the plot')
 Finally to view the plot use show function plt.show()

There are other kinds of visulization function plt.scatter(), plt.bar(),


plt.pie(), plt.hist()
Plotting 2D-Curves
Example1: Plotting with given x-data and y-data Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
plt.plot(x,y)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Data visualization')
plt.show()

Example2: Plotting with given x-data and y-data using marker


import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
plt.plot(x,y,'*') # marker *
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Data visualization')
plt.show()
Matplotlib
Example3: Plotting with given x-data and y-data choosing color
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
plt.plot(x,y,'r') # red curve
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Data visualization')
plt.show()

Example4: Plotting with given x-data and y-data choosing color, marker
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
plt.plot(x,y,'-ro')# red color curve together with marker o
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Data visualization')
plt.show()
Matplotlib

Example5: Plotting with given function 𝑦 = 𝑠𝑖𝑛 𝑥 on the interval


− 2𝜋 ≤ 𝑥 ≤ 2𝜋
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2*np.pi,2*np.pi, 50)
y = np.sin(x)
plt.plot(x,y,'r')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Plot of $\sin x$')
plt.show()
Matplotlib
Example6: Plotting with given two functions 𝑦 = 𝑠𝑖𝑛 𝑥 𝑎𝑛𝑑 cos 𝑥
on the interval −2𝜋 ≤ 𝑥 ≤ 2𝜋
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2*np.pi,2*np.pi, 50)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x,y1,'r')
plt.plot(x,y2,'b')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Plot of $\sin x$ and $\cos x$')
plt.legend(['sinx','cosx']) # legend
plt.show()
Choosing Colors
and Markers
Matplotlib
Specifying the Colors
 Matplotlib provides single character short hand notations for choise
of few basic colors:
Color Meaning
'b' Blue
'g' Green
'r' Red
'c' Cyan
'm' Yellow
'y' Mangenta
'k' Black
'w' White

 An RGB or RGBA (red, green, blue, alpha) tuple of float values in the
closed interval [0,1] can be used for all possible color combinations.
Eg (0.1, 0.3. 0.5) or (0.1, 0.3. 0.5, 0.9)
Matplotlib
Specifying the Marker
 Matplotlib provides single character short hand notations to handle
markers. Marker works for both plot and scatter
Color Meaning
'.' point
'*' star
'o' circle
'v' Triangle down
'^' Triangle up
'<' Traingle left
'>' Triangle right
's' square
'p' pentagon
'x' cross
'd' Dimond
'+' plus
Subplot
Matplotlib
Subplot:
 Matplotlib subplot() function can be used to plot two or more plots
in one figure. Explained with example
Example1:
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-4,4,30);
y1 = x**2
y2 = x**3
plt.figure()

plt.subplot(1,2,1)
plt.plot(x,y1,'r')

plt.subplot(1,2,2)
plt.plot(x,y2,'b')
plt.show()
Subplots
Matplotlib
Subplots:
 This ia an alternate method that provides a way to plot multiple
figures in single figure window
 subplots() returns a Figure instance and single or an array of Axes
objects. This is the simplest and recommended way of creating
single and multiple figures.
 This way of creating figures has more control over figure and axes
Example2: (Single Plot)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2*np.pi,2*np.pi,50)
y = x*np.sin(x)
fig, ax = plt.subplots(1,1,figsize=(10,6))
ax.plot(x,y,'g')
ax.set_title('Single Plot')
plt.show()
Matplotlib
Subplots continue...
Example3: (Vertically Staked plot)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2*np.pi,2*np.pi,50)
y = x*np.sin(x)
z = x*np.cos(x)
fig, ax = plt.subplots(2,1,figsize=(8,8))
fig.suptitle('Vertically staked subplots')
ax[0].plot(x,y,'r')
ax[0].set_title('plot of $x sinx$')

ax[1].plot(x,z,'g')
ax[1].set_title('plot of $x cosx$')
plt.show()
Matplotlib
Subplots continue...
Example4: (Horizontally Staked Plot)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2*np.pi,2*np.pi,50)
y = x*np.sin(x)
z = x*np.cos(x)
fig, ax = plt.subplots(1,2,figsize=(8,8))
fig.suptitle('Vertically staked subplots')
ax[0].plot(x,y,'r')
ax[0].set_title('plot of $x sinx$')

ax[1].plot(x,z,'g')
ax[1].set_title('plot of $x cosx$')
plt.show()
Subplots continue... Matplotlib
Example5: ( Two direnctional Staked Plot)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2*np.pi,2*np.pi,50)
y = x*np.sin(x)
z = x*np.cos(x)
fig, ax = plt.subplots(2,2,figsize=(15,6))
fig.suptitle('Horizontal staked subplots')
ax[0,0].plot(x,y,'m')
ax[0,0].set_title('plot of $x sinx$')
ax[0,1].plot(x,z,'c')
ax[0,1].set_title('plot of $x cosx$')
ax[1,0].plot(x,y,'g')
ax[1,0].set_title('plot of $x sinx$')
ax[1,1].plot(x,z,'r')
ax[1,1].set_title('plot of $x cosx$')
plt.show()
3D-Plots
3-Dimensional Plotting
Matplotlib
 3-dimensional plots are enabled by importing the mplot3d toolkit that is
included with the main matplotlib installation

 Once this submodule is imported, 3D plots can be created by passing the


keyword projection = "3D" to any of the normal axes creation routine

Example1: (Space Curve Plot)


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,8))
ax = plt.axes(projection="3d") # creates 3-dimensional axes
t = np.linspace(0,4*np.pi,100);
x = np.cos(t)
y = np.sin(t)
z=t
ax. plot3D(x,y,z,'g')
ax.scatter3D(x,y,z)
plt.show()
Matplotlib
3-Dimensional Plotting Continue ...

Example2: (Contour plot on xy-plane)


import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,8))
x = np.linspace(-5,5,50)
y = np.linspace(-5,5,50)
X, Y = np.meshgrid(x,y)
Z = X**2 + Y**2
plt.contour(X,Y,Z,10, colors='blue', linewidths = 2) # Simple contour plot
#plt.contourf(X,Y,Z,10, cmap='jet') # If required filled contour plot
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.grid([])
plt.show()
Matplotlib
3-Dimensional Plotting Continue ...
Example3: (Surface Plot)
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,8))
ax = plt.axes(projection="3d") # creates 3-dimensional axes
x = np.linspace(-5,5,50)
y = np.linspace(-5,5,50)
X, Y = np.meshgrid(x,y)
Z = X**2 + Y**2
ax. plot_surface(X,Y,Z,cmap='plasma')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Surface')
ax.grid([])
plt.show()

https://jakevdp.github.io/PythonDataScienceHandbook/index.html
3-Dimensional Plotting Continue ... Matplotlib
Example4: (Contour Plot on Space)
from mpl_toolkits import mpl ot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,8))
ax = plt.axes(projection="3d") # creates 3-dimensional axes
x = np.linspace(-5,5,50)
y = np.linspace(-5,5,50)
X, Y = np.meshgrid(x,y)
Z = X**2 + Y**2
ax.view_init(60,35) # View angle
ax.contour3D(X,Y,Z,50,cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.grid([])

https://jakevdp.github.io/PythonDataScienceHandbook/index.html
Matplotlib
3-Dimensional Plotting Continue ...
Example5: (Surface Wireframe)
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,8))
ax = plt.axes(projection="3d") # creates 3-dimensional axes
x = np.linspace(-5,5,50)
y = np.linspace(-5,5,50)
X, Y = np.meshgrid(x,y)
Z = X**2 + Y**2
ax.plot_wireframe(X,Y,Z,color='green')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('Wireframe')
ax.grid([])

https://jakevdp.github.io/PythonDataScienceHandbook/index.html
Matplotlib
3-Dimensional Plotting Continue ...

Exercise:
Question 1: Write the program to show the contour plot of
𝑥 5 5 −𝑥 2 −𝑦 2
the function 𝑓 𝑥, 𝑦 = (1 − + 𝑥 + 𝑦 )/𝑒 on the
2
domain −3 ≤ 𝑥, 𝑦 ≤ 3

Question 2: Write the program to show the surface plot of


the function 𝑓 𝑥, 𝑦 = sin( 𝑥 2 + 𝑦 2 ) on the domain
− 4 ≤ 𝑥, 𝑦 ≤ 4
2D-Quiver Plots
Matplotlib
2D Quiver: Vector Field Plot
Example1: Plot of the vector field of vector valued function
𝐹 = −𝑥 𝒊 + 𝑦 𝒋 using matplotlib quiver function
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(10,8))
x = np.linspace(-5,5,10)
y = np.linspace(-5,5,10)
X, Y = np.meshgrid(x,y) # Mesh points
Fx, Fy = -X, Y
plt.quiver(X,Y,Fx, Fy,color='red',scale=50)
2D Quiver: Vector Field Plot Matplotlib
Example2: Plot of the vector field of vector valued function
𝐹 = 𝑠𝑖𝑛𝑥𝑐𝑜𝑠𝑦 𝒊 + 𝑐𝑜𝑠𝑥𝑠𝑖𝑛𝑦 𝒋 using matplotlib quiver function
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,2*np.pi+2*np.pi/20,2*np.pi/20)
y = np.arange(0,2*np.pi+2*np.pi/20,2*np.pi/20)
X,Y = np.meshgrid(x,y)
U = np.sin(X)*np.cos(Y)
V = -np.cos(X)*np.sin(Y)
fig, ax = plt.subplots(figsize=(8,8))
ax.quiver(X,Y,U,V,color='green', alpha=0.5, scale=15.0)
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
ax.axis([0,2*np.pi,0,2*np.pi])
Matplotlib
2D Quiver: Vector Field Plot
Example3: Plot of the colored gradient vector field of vector
valued function 𝐹 = 𝑠𝑖𝑛𝑥𝑐𝑜𝑠𝑦 𝒊 + 𝑐𝑜𝑠𝑥𝑠𝑖𝑛𝑦 𝒋 using matplotlib
quiver function
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,2*np.pi+2*np.pi/20,2*np.pi/20)
y = np.arange(0,2*np.pi+2*np.pi/20,2*np.pi/20)
X,Y = np.meshgrid(x,y)
U = np.sin(X)*np.cos(Y)
V = -np.cos(X)*np.sin(Y)
n=0
color_array = np.sqrt(((U-n)/2)**2 + ((V-n)/2)**2)
fig, ax = plt.subplots(figsize=(8,8))
ax.quiver(X,Y,U,V,color_array)
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
ax.set_aspect('equal')
Matplotlib
2D Quiver: Vector Field Plot
Example4: Plot of the colored gradient vector of a scalar valued
−𝑥 2 −𝑦 2
function valued function 𝑓 𝑥, 𝑦 = 𝑥𝑒 using matplotlib
quiver function
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2,2.2,0.2)
y = np.arange(-2,2.2,0.2)
X, Y = np.meshgrid(x, y)
Z = X*np.exp(-X**2 -Y**2)
dx, dy = np.gradient(Z)
n=0
color_array = np.sqrt(((dx-n)/2)**2 + ((dy-n)/2)**2)
fig, ax = plt.subplots(1,1,figsize=(8,8))
ax.quiver(X,Y,dx,dy,color_array)
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
ax.set_aspect('equal')
End of Lecture-5
Next
Implementation of MCSC-202
Problems
39

You might also like