Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

12_Numpy&Matplotlib

Uploaded by

haeinpark1376
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)
1 views

12_Numpy&Matplotlib

Uploaded by

haeinpark1376
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/ 48

Lecture 12

Numpy and Matplot Library

Prof. Hyeong-Seok Ko
Seoul National University
Dept. of Electrical and Computer Engineering
Contents
• Introduction to NumPy
• NumPy Arrays
• Matplotlib
What is Numpy?
• NumPy (Numeric Python)
– Provides routines for arrays and matrices.
– Use numpy for large numerical computation.
– Each numpy dimension is called axis. The total number of axes is rank.
How to install NumPy? (1)
• Execute cmd.
How to install NumPy? (2)

• Visit the directory where python is installed.


• Enter python –m pip install numpy.

• If numpy is successfully installed, the following one-line program will execute all right.
• Otherwise, it will produce an error.
import numpy as np
Introduction to NumPy Arrays
• NumPy’s array is a collection of values, organized in a specific order.

import numpy as np

arr = np.array([1,2,3,4,5])
print(arr)

[1 2 3 4 5]

Array vs. List:


• To use array, you need to import NumPy (not built-in).
• There are no commas in the array.
• Arrays can store data very compactly and are more efficient for storing
large amounts of data.
• Use arrays for numerical computations; lists cannot directly handle math
operations.
• NumPy provides lots of ways to create arrays.
Creating Arrays with arange() and linspace()
import math [0. 0.25 0.5 0.75]
import numpy [0. 0.25 0.5 0.75 1. ]
0.0 0.25 0.5 0.75 1.0
x = numpy.arange(0, 1, 0.25); print(x)
x = numpy.linspace(0, 1, num=5); [0. 0.5 1. 1.5 2. ]
print(x) [0. 0.0625 0.25 0.5625 1. ]
for i in x : [0. 0.24740396 0.47942554 0.68163876 0.84147098]
print(i, end = ' ')
print(); print()

y = x*2; print(y)
y = x**2; print(y)
y = numpy.sin(x); print(y)

• numpy.arange(start, stop, step) returns evenly spaced values array


within a given interval. Values are generated within [start, stop).

• numpy.linspace(start, stop, num=50) returns num evenly spaced


values array over the interval [start, stop].
Creating Arrays of 0’s and 1’s

import numpy [0. 0. 0. 0. 0.]


[ [0. 0. 0. 0. 0. 0.]
x = numpy.zeros(5); [0. 0. 0. 0. 0. 0.]]
print(x) [1. 1. 1. 1. 1.]
x = numpy.zeros((2,5)); [ [1. 1. 1. 1. 1.]
print(x) [1. 1. 1. 1. 1.]]
x = numpy.ones(5);
print(x)
x = numpy.ones((2,5));
print(x)

• numpy.zeros(tuple) creates an array of zeros.

• numpy.ones(tuple) creates an array of ones.


Indexing Arrays
• The indices in NumPy start with 0.

import numpy as np 1
4
x = np.array([1, 2, 3, 4])
print(x[0])

y = np.array([[1,2],[3,4]])
print(y[1,1])
Slicing

import numpy as np [2 3 4 5]
[[3 4]
a = np.array([1, 2, 3, 4, 5, 6, 7]) [7 6]]
print(a[1:5])

b = np.array([[1,2,3],[3,4,5],[7,6,7]])
print(b[1:,:2])
Reshaping Arrays
• The shape of an array means the number of elements in each dimension.

import numpy as np [ 1 2 3 4 5 6 7 8 9 10 11 12]


[[ 1 2 3]
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) [ 4 5 6]
new_a = a.reshape(4, 3) [ 7 8 9]
print(a) [10 11 12]]
print(new_a) [ 1 2 3 4 5 6 7 8 9 10 11 12]

new_a2 = new_a.reshape(12,)
print(new_a2)
Concatenating Arrays

import numpy as np [1 2 3 4 5 6]
[[1 2]
a1 = np.array([1, 2, 3]) [3 4]
a2 = np.array([4, 5, 6]) [5 6]
a = np.concatenate((a1, a2), axis=0) [7 8]]
print(a) [[1 2 5 6]
[3 4 7 8]]
b1 = np.array([[1, 2], [3, 4]])
b2 = np.array([[5, 6], [7, 8]])
b = np.concatenate((b1, b2), axis=0)
print(b) axis 1
c = np.concatenate((b1, b2), axis=1)
1 2

axis 0
print(c)
3 4
What is Matplotlib?
• Python’s plotting library
How to install Matplotlib
• Install it using this command

• Once Matplotlib is installed, import it in your python code by adding the “import module”

• Most of the Matplotlib utilities lies under the “pyplot” submodule, and are usually imported
under the “plt” alias like below:
Matplotlib Plotting
• Plotting x and y points

import matplotlib.pyplot as plt


import numpy as np

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


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

plt.plot(x_vals, y_vals)
plt.show()

• plt.plot(xCoords, yCoords) connects the points by drawing lines.


• xCoods is the array containing x coordinates.
• yCoods is the array containing y coordinates.

• plt.show() displays the resultant graph


Default X Values
• If we do not specify x values, it uses 0, 1, 2, 3,…

import matplotlib.pyplot as plt


import numpy as np

y_vals = np.array([3, 8, 1, 10, 5, 7])

plt.plot(y_vals)
plt.show()
'+' Plus

Using Different Markers


'P' Plus (filled)

's' Square

'D' Diamond
• We can use the keyword argument “marker”.
'd' Diamond (thin)

'p' Pentagon
import matplotlib.pyplot as plt
import numpy as np 'H' Hexagon 'o' Circle

'h' Hexagon '*' Star


y_vals = np.array([3, 8, 1, 10]) 'v' Triangle Down '.' Point

'^' Triangle Up ',' Pixel


plt.plot(y_vals, marker = 'o')
plt.show() '<' Triangle Left 'x' X

'>' Triangle Right 'X' X (filled)

'+' Plus
'1' Tri Down
'P' Plus (filled)
'2' Tri Up
's' Square
'3' Tri Left

'4' Tri Right


'D' Diamond

'|' Vline 'd' Diamond (thin)

'_' Hline 'p' Pentagon

'H' Hexagon

'h' Hexagon
Line Style
• We can use the keyword argument “linestyle”, or shorter “ls”.

import matplotlib.pyplot as plt


import numpy as np

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

plt.plot(y_vals, linestyle = 'dotted')


plt.show()

• linestyles available:
• solid (default)
• dotted
• dashed
• dashdot
Color
• We can use the keyword argument “color”, or shorter “c”.

import matplotlib.pyplot as plt


import numpy as np

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

plt.plot(ypoints, color = 'r', linestyle = 'dashed')


# plt.plot(ypoints, color = '#00FF00', linestyle = 'dashdot')
plt.show()

• colors available:
• r (red)
• g (green)
• b (blue)
• c (cyan)
• m (magenta)
• we can also use hexadecimal color values: #RRGGBB
Line Width
• We can use the keyword argument ‘linewidth’ or the shorter ‘lw’.

import matplotlib.pyplot as plt


import numpy as np

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

plt.plot(ypoints, linewidth = '20.5')


plt.show()
Plotting Multiple Lines
• We can plot as many lines as we like by calling ‘plt.plot()’ multiple times

import matplotlib.pyplot as plt


import numpy as np

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


y_vals_2 = np.array([6, 2, 7, 11])

plt.plot(y_vals_1)
plt.plot(y_vals_2)

plt.show()
Putting Labels to the Plot
• We can use ‘xlabel()’ and ‘ylabel()’ to create labels for the x- and y-axes.

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110])


y = np.array([240, 260, 290, 100, 120, 190, 300])

plt.plot(x, y)

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

plt.show()
Putting the Title
• We can use the ‘title()’ to create a title for the plot.

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110])


y = np.array([240, 260, 290, 100, 120, 190, 300])

plt.plot(x, y)

plt.title("Sports Watch Data")


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

plt.show()
Figure Consisting of Multiple Plots
• With the ‘subplot()’, we can organize multiple plots to a figure.

import matplotlib.pyplot as plt


import numpy as np
# plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1) # Among 1x2 plots, this is the 1st one
plt.plot(x,y)
# plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2) # Among 1x2 plots, this is the 2nd one
plt.plot(x,y)
plt.show()

• plt.subplot(n_row, n_col, i):


• The figure consists of n_rows x n_col plots.
• The current plot is the i-the plot.
Figure Consisting of Multiple Plots (Cont.)

import matplotlib.pyplot as plt


import numpy as np

# plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)

# plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x,y)

plt.show()
Plotting Points
• We can use ‘scatter()’ to plot points.
– It needs two arrays of the same length, one for the x values, and the other for y values.

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

plt.scatter(x, y)
plt.show()
Plotting Multiple Sets of Points

import matplotlib.pyplot as plt


import numpy as np

# first set:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)

# second set:
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112])
plt.scatter(x, y)

plt.show()
Setting Point Colors
• You can set the color for each point set with the ‘color’ or the ‘c’ argument

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y, color = 'hotpink')

x = np.array([2,2,8,1,15,8,12,9,7,3,11,4])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112])
plt.scatter(x, y, color = '#88c999')

plt.show()
Coloring Each Point
• We can control the color of each point by giving an array of colors as
the value for the ‘c’ argument.

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
c_arr =
np.array(["red","green","blue","yellow","pink","black","o
range","purple","beige","brown","gray","cyan","magenta"])

plt.scatter(x, y, c=c_arr)

plt.show()
Controlling the Point Size
• We can control the size of the points with the ‘s’ argument.

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4, 6])
y = np.array([99,86,87,88,111,86,103,87,94,78])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300])

plt.scatter(x, y, s=sizes)

plt.show()
Drawing Bar Graphs
• We can use ‘bar()’ to draw bar graphs

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()
Drawing Bar Graphs (Cont.)
• ‘barh()’ draws a horizontal bar graph.

import matplotlib.pyplot as plt


import numpy as np

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


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

plt.barh(x, y)
plt.show()
Plotting a Sine Curve

import math
import matplotlib.pyplot as plt

nSamples = 64
xr = (-math.pi, math.pi)
x, y = [], []

for n in range(nSamples):
k = n / (nSamples-1)
x.append(xr[0] + (xr[1] - xr[0]) * k)
y.append(math.sin(x[-1]))

plt.plot(x,y)
plt.show()
Plotting a Sine Curve
• using NumPy arrays

import math
import numpy
import matplotlib.pyplot as plt

nSamples = 64
x = numpy.linspace(-math.pi, math.pi, num=nSamples)
y = numpy.sin(x)

plt.plot(x,y)
plt.show()
Bar Plot

import math
import numpy
import matplotlib.pyplot as plt

nSamples = 64
x = numpy.linspace(-math.pi, math.pi, num=nSamples)
y = numpy.sin(x)

plt.bar(x,y,width=math.pi/32)
#plt.bar(x,y,width=math.pi/64)
plt.show()
Scatter Plot

import math
import numpy
import matplotlib.pyplot as plt

nSamples = 64
x = numpy.linspace(-math.pi, math.pi, num=nSamples)
y = numpy.sin(x)

plt.scatter(x,y)
plt.show()
Drawing Options

import math
import numpy
import matplotlib.pyplot as plt

nSamples = 64
x = numpy.linspace(-math.pi, math.pi, num=nSamples)
y = numpy.sin(x)

fig = plt.figure()
axis = fig.add_subplot(111)
axis.set_ylim(-1.5, 1.5)
axis.grid(True)

plt.scatter(x,y)
plt.show()
Plotting two Curves

import math
import numpy
import matplotlib.pyplot as plt

nSamples = 64
x = numpy.linspace(-math.pi, math.pi, num=nSamples)
y = numpy.sin(x)
z = numpy.cos(x)

plt.plot(x,y)
plt.plot(x,z)
plt.show()
Line Style, Width, Color, Label

import math
import numpy
import matplotlib.pyplot as plt

nSamples = 64
x = numpy.linspace(-math.pi, math.pi, num=nSamples)
y = numpy.sin(x)
z = numpy.cos(x)

plt.plot(x,y, linestyle='--', c='magenta', label='sin(x)')


plt.plot(x,z, linewidth=5, label='cos(x)')
plt.legend(loc='best')
plt.show()
Figure Consisting of Multiple Plots

import math
import numpy
import matplotlib.pyplot as plt

nSamples = 64
x = numpy.linspace(-math.pi, math.pi, num=nSamples)
y = numpy.sin(x)

fig = plt.figure()
fig.add_subplot(211) # among 2x1 plots, this is the 1st
plt.plot(x,y)

fig.add_subplot(212) # among 2x1 plots, this is the 2nd


plt.bar(x,y,width=math.pi/32)

plt.show()
3D Plotting
• Drawing a surface which represents a two-dimensional function.

z = f ( x, y )
Introduction to mplot3d
import math
import numpy
import matplotlib.pyplot as plt

fig = plt.figure()
axis = fig.add_subplot(111, projection='3d')

def func(x,y):
return (1- x/2 + x**5 + y**3)*numpy.exp(-x**2-y**2)

x = numpy.arange(-3.0, 3.01, 0.1)


y = numpy.arange(-3.0, 3.01, 0.1)
X,Y = numpy.meshgrid(x, y)
Z = func(X, Y)

surf = axis.plot_surface(X, Y, Z, rstride=1, cstride=1,


linewidth=0, antialiased=False)
axis.set_zlim3d(-1, 1)
plt.show()

, cmap = 'jet'
Forming the Mesh Grid
• It is done by sampling two-dimensional space.

x = numpy.arange(-3.0, 3.01, 0.1)


y = numpy.arange(-3.0, 3.01, 0.1)
X,Y = numpy.meshgrid(x, y)
Z = func(X, Y)

Range of x : (-3.0, 3.01), hx = 0.1


Range of y : (-3.0, 3.01), hy = 0.1

hy

hx
Plotting the Surface as an Image
import math
import numpy
import matplotlib.pyplot as plt

fig = plt.figure()
axis = fig.add_subplot(111)

def func(x,y):
return (1- x/2 + x**5 + y**3) \
* numpy.exp(-x**2-y**2)

x = numpy.arange(-3.0, 3.01, 0.1)


y = numpy.arange(-3.0, 3.01, 0.1)
X,Y = numpy.meshgrid(x, y)
Z = func(X, Y)

plt.imshow(Z
, interpolation='nearest'
, origin='lower'
, extent=(-3,3,-3,3)
, cmap = 'jet')

plt.colorbar()
plt.show()
Resolution Control

...
def func(x,y):
return (1- x/2 + x**5 + y**3) \
* numpy.exp(-x**2-y**2)

x = numpy.arange(-3.0, 3.01, 0.5)


y = numpy.arange(-3.0, 3.01, 0.5)
X,Y = numpy.meshgrid(x, y)
Z = func(X, Y)

plt.imshow(Z
, interpolation='nearest'
, origin='lower'
, extent=(-3,3,-3,3)
, cmap = 'jet')

plt.colorbar()
plt.show()
Selecting Interpolation Methods
• How to estimate the function value at an arbitrary position x based on the function values at
the grid points?
Matplotlib Interpolation Types ...
plt.imshow(Z,
interpolation='nearest',
origin='lower',
extent=(-3,3,-3,3),
cmap = 'jet')

Nearest Bilinear Bicubic


Lecture 12
Numpy and Matplot Library

The End

You might also like