0% found this document useful (0 votes)
15 views59 pages

2024 Spring Practice Week 13 Lecture 12

The document outlines a practice session focused on using NumPy and Matplotlib, including tasks such as creating classes for shapes and implementing basic graphical interactions. It provides an overview of NumPy, including array creation, indexing, slicing, reshaping, and concatenation. Additionally, it includes examples of using functions like arange and linspace for numerical computations.

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)
15 views59 pages

2024 Spring Practice Week 13 Lecture 12

The document outlines a practice session focused on using NumPy and Matplotlib, including tasks such as creating classes for shapes and implementing basic graphical interactions. It provides an overview of NumPy, including array creation, indexing, slicing, reshaping, and concatenation. Additionally, it includes examples of using functions like arange and linspace for numerical computations.

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/ 59

Practice

Week 13 (Lecture 12)

Hyeon-Seung Shin
Seoul National University
Graphics & Media Lab
Today’s features to practice
• NumPy
• Matplotlib
Today’s mission
• (1) Shoot the ball on the player as (2) playing music.
– Define Circle and Rectangle class.
• (optional) Define Shape class and let the classes above inherit from Shape.
– Draw a guideline between the ball and mouse cursor.
– Shoot the ball along the guideline with LMB pressed.
– Reposition the ball when it is out of the boundary.
– Play any music.

– (optional) Modularization
• Shape.py
• Circle.py
• Rectangle.py
• etc.
• Import the modules above in main source code file.
Lecture review (NumPy)
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.
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
Advanced
NumPy Array
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

Source code
import numpy
Result
x = numpy.linspace(0, 10, num=5);
print(x, '\n') [ 0. 2.5 5. 7.5 10. ]

x = numpy.linspace(0, 10, num=5, endpoint=False) [0. 2. 4. 6. 8.]


print(x, '\n')
(array([ 0. , 2.5, 5. , 7.5, 10. ]), 2.5)
x = numpy.linspace(0, 10, num=5, retstep=True)
print(x, '\n') [ 0 2 5 7 10]

x = numpy.linspace(0, 10, num=5, dtype=int)


print(x)
Advanced
NumPy Array
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
Source code Result
import numpy [[ 0. 1. 2. ]
[ 2.5 5.75 9. ]
x = numpy.linspace([0,1,2], [10,20,30], num=5) [ 5. 10.5 16. ]
[ 7.5 15.25 23. ]
print(x, '\n') [10. 20. 30. ]]

x = numpy.linspace([0,1,2], [10,20,30], num=5, endpoint=False) [[ 0. 1. 2. ]


print(x, '\n') [ 2. 4.8 7.6]
[ 4. 8.6 13.2]
x = numpy.linspace([0,1,2], [10,20,30], num=5, retstep=True) [ 6. 12.4 18.8]
[ 8. 16.2 24.4]]
print(x, '\n')
(array([[ 0. , 1. , 2. ],
x = numpy.linspace([0,1,2], [10,20,30], num=5, dtype=int) [ 2.5 , 5.75, 9. ],
print(x, '\n') [ 5. , 10.5 , 16. ],
[ 7.5 , 15.25, 23. ],
x = numpy.linspace([0,1,2], [10,20,30], num=5, axis=1) [10. , 20. , 30. ]]), array([2.5 , 4.75, 7. ]))
print(x) [[ 0 1 2]
[ 2 5 9]
[ 5 10 16]
[ 7 15 23]
[10 20 30]]

[[ 0. 2.5 5. 7.5 10. ]


[ 1. 5.75 10.5 15.25 20. ]
[ 2. 9. 16. 23. 30. ]]
Practice
numpy array (5 minutes)
import numpy as np [0 1 2]
[3. 4. 5.]
arr1 = np.array([0, 1, 2]) # from list [1 1 1]
arr2 = np.array((3, 4, 5), dtype=float) # from tuple [0 0 0]
arr3 = np.ones(3, dtype=int)
arr4 = np.zeros(3, dtype=int) [1. 1.5 2. 2.5]
print(arr1) [1 1 1 1]
print(arr2) [1. 1.5 2. 2.5 3. ]
print(arr3) [1. 1.4 1.8 2.2 2.6]
print(arr4, "\n") [1 1 2 2 3]

arr5_1 = np.arange(1, 3, 0.5)


arr5_2 = np.arange(1, 3, 0.5, dtype=int)
arr6_1 = np.linspace(1, 3, 5)
arr6_2 = np.linspace(1, 3, 5, endpoint=False)
arr6_3 = np.linspace(1, 3, 5, dtype=int)
print(arr5_1)
print(arr5_2)
print(arr6_1)
print(arr6_2)
print(arr6_3)
numpy array (5 minutes)
import numpy as np [0 1 2]
[3 4 5]
arr1 = np.array([0, 1, 2])
arr2 = np.array((3, 4, 5)) [ 0 -1 -2]
print(arr1) [0 1 2]
print(arr2, "\n") [3 5 7]
[-3 -3 -3]
print(-arr1) [ 0 4 10]
print(+arr1) [0. 0.25 0.4 ]
print(arr1 + arr2) [ 0 1 32]
print(arr1 - arr2) [0 0 0]
print(arr1 * arr2) [0 1 2]
print(arr1 / arr2)
print(arr1 ** arr2) [False False False]
print(arr1 // arr2) [ True True True]
print(arr1 % arr2, "\n") [ True True True]
[False False False]
print(arr1 == arr2) [ True True True]
print(arr1 != arr2) [False False False]
print(arr1 < arr2)
print(arr1 > arr2) False
print(arr1 <= arr2) True
print(arr1 >= arr2, "\n")

print(arr1 is arr2)
print(arr1 is not arr2)
numpy array (5 minutes)
import numpy as np 0
1
arr1 = np.array([0, 1, 2]) 2

for item in arr1: 0


print(item) [0 1]
print() [0 1 2]

print(arr1[0]) 3
print(arr1[0:2]) 0
print(arr1[:], "\n") 1.0
0.816496580927726
print(arr1.sum()) 0.6666666666666666
print(arr1.prod()) 0
print(arr1.mean()) 2
print(arr1.std())
print(arr1.var())
print(arr1.min())
print(arr1.max())
linspace (5 minutes)
import numpy (array([[ 0., 1., 2.],
[ 1., 3., 6.],
start = [0,1,2] [ 2., 5., 10.],
end = [5,11,22] [ 3., 7., 14.],
x = numpy.linspace( [ 4., 9., 18.]]), array([1., 2., 4.]))
start,
end, [[[ 0. 1. 2. ]
num=5, [ 1. 2. 3. ]
endpoint = False, [ 2. 3. 4. ]]
dtype = float,
retstep = True) [[ 2.5 5.75 9. ]
print(x, '\n') [ 5.75 9. 12.25]
[ 9. 12.25 15.5 ]]
start = [[0,1,2], [1,2,3], [2,3,4]]
end = [[10,20,30], [20,30,40], [30,40,50]] [[ 5. 10.5 16. ]
x = numpy.linspace( [10.5 16. 21.5 ]
start, [16. 21.5 27. ]]
end,
num = 5) [[ 7.5 15.25 23. ]
print(x) [15.25 23. 30.75]
[23. 30.75 38.5 ]]

[[10. 20. 30. ]


[20. 30. 40. ]
[30. 40. 50. ]]]
linspace (5 minutes)
[[[ 0. 1. 2. ]
[ 2.5 5.75 9. ]
[ 5. 10.5 16. ]
import numpy [ 7.5 15.25 23. ]
[10. 20. 30. ]]
start = [[0,1,2], [1,2,3], [2,3,4]]
end = [[10,20,30], [20,30,40], [30,40,50]] [[ 1. 2. 3. ]
x = numpy.linspace( [ 5.75 9. 12.25]
start, [10.5 16. 21.5 ]
end, [15.25 23. 30.75]
num = 5, [20. 30. 40. ]]
axis = 1)
print(x, '\n') [[ 2. 3. 4. ]
[ 9. 12.25 15.5 ]
start = [[0,1,2], [1,2,3], [2,3,4]] [16. 21.5 27. ]
end = [[10,20,30], [20,30,40], [30,40,50]] [23. 30.75 38.5 ]
x = numpy.linspace( [30. 40. 50. ]]]
start,
end, [[[ 0. 2.5 5. 7.5 10. ]
num = 5, [ 1. 5.75 10.5 15.25 20. ]
axis = 2) [ 2. 9. 16. 23. 30. ]]
print(x)
[[ 1. 5.75 10.5 15.25 20. ]
[ 2. 9. 16. 23. 30. ]
[ 3. 12.25 21.5 30.75 40. ]]

[[ 2. 9. 16. 23. 30. ]


[ 3. 12.25 21.5 30.75 40. ]
[ 4. 15.5 27. 38.5 50. ]]]
Lecture review (2D plotting)
What is Matplotlib?
• Python’s plotting library
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()
Drawing options

Line style Color Title location Legend Marker


Character Description Character Description Location string Location string Character Description Character Description
'-' Solid line 'b' Blue 'center' 'best' '.' Point 'p' pentagon
'--' Dashed line 'g' Green 'left' 'upper right' ',' Pixel 'P' Plus (filled)
'-.' Dash-dot line 'r' Red 'right' 'upper left' 'o' Circle '*' Star
':' Dotted line 'c' Cyan 'lower left' 'v' Triangle_down 'h' Hexagon1
'm' Magenta 'lower right' '^' Triangle_up 'H' Hexagon2
'y' Yellow 'right' '<' Triangle_left '+' Plus
'k' Black 'center left' '>' Triangle_right 'x' X
'w' white 'center right' '1' Tri_down 'X' X (filled)
'lower center' '2' Tri_up 'D' Diamond
'upper center' '3' Tri_left 'd' Thin-diamond
'center' '4' Tri_right '|' Vline
'8' Octagon '_' hline
's' square
'+' 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()
Other drawings
Source code
import math
import numpy as np
import matplotlib.pyplot as plt

nSamples = 64
x = np.linspace(-math.pi, math.pi, num=nSamples)
y1 = np.sin(x)
y2 = np.cos(x)

fig = plt.figure()
fig.canvas.set_window_title('My Figure')
axis = fig.add_subplot(1, 1, 1)
#axis = fig.add_subplot(111)
axis.set_ylim(-2, 2)
axis.grid(True)

plt.title('Plot')
plt.xlabel('x')
plt.ylabel('y')

plt.plot(x, y1, linestyle='-', color='b', label='sin(x)')


plt.plot(x, y2, ls=':', c='r', label='cos(x)')
plt.bar(x, y1 + 1, width=0.05)
plt.scatter(x, y1 - 1)
plt.legend(loc='best')

plt.show()
Other drawings
Source code import math
import numpy as np
import matplotlib.pyplot as plt

nSamples = 64
x = np.linspace(-math.pi, math.pi, num=nSamples)
y1 = np.sin(x); y2 = np.cos(x); y3 = np.tan(x); y4 = x

fig = plt.figure()
fig.canvas.set_window_title('My Figure')

axis1 = fig.add_subplot(2, 2, 1)
axis1.set_ylim(-1, 1)
plt.title('Plot1', loc='left')
plt.ylabel('y')
plt.plot(x, y1, linestyle='-', color='b', label='sin(x)')

axis2 = fig.add_subplot(2, 2, 2)
axis2.set_xlim(-3, 3)
axis2.set_ylim(-3, 3)
plt.title('Plot2', loc='right')
plt.plot(x, y2, ls=':', c='r', label='cos(x)')

axis3 = fig.add_subplot(2, 2, 3)
plt.xlabel('x')
plt.plot(x, y3, ls='--', c='g', label='tan(x)')
plt.legend(loc='upper center')

axis4 = fig.add_subplot(2, 2, 4)
axis4.set_xticks([-2, -1, 0, 1, 2])
axis4.set_yticks([-2, -1, 0, 1, 2])
plt.plot(x, y4,ls='-.', c='m', label='x')
plt.legend(loc='lower right')
plt.xticks()

plt.show()
Practice
2D plotting (5 minutes)
Source code
import numpy as np
import matplotlib.pyplot as plt

nSamples = 50
x = np.linspace(-1, 1, num=nSamples)
y1 = np.log(x)
y2 = np.exp(x)
y3 = np.abs(x)
y4 = np.sqrt(x)

fig = plt.figure()
fig.canvas.set_window_title('My Figure')

axis1 = fig.add_subplot(1, 2, 1)
plt.title('Plot1')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y1, '.', x, y2, 's')

axis2 = fig.add_subplot(1, 2, 2)
plt.title('Plot2')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y3, 'x', x, y4, '+')

plt.show()
Lecture review (3D plotting)
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'
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()
Practice #01
• Plot two-dimensional Gaussian functions.
– http://en.wikipedia.org/wiki/Gaussian_function

 x2 2 
 
y
 2
 2 
x 2 y
2

f ( x, y )  Ae  
Practice #01
import numpy as np
import matplotlib.pyplot as plt

def func(A, sigmaX, sigmaY, x ,y):


return A * np.exp(-(x*x/(2*sigmaX*sigmaX)+y*y/(2*sigmaY*sigmaY)))

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


y = np.arange(-3.0, 3.01, 0.1)
X,Y = np.meshgrid(x, y)

fig = plt.figure()
axis1 = fig.add_subplot(221)
Z = func(1, 1, 1, X, Y)
plt.title('A=1, sigmaX=1, sigmaY=1', {'fontsize': 8, 'fontweight': 'bold'}, pad=0)
plt.imshow(Z, interpolation='nearest', extent=(-2,2,-2,2), cmap = 'jet')

axis2 = fig.add_subplot(222)
Z = func(1, 2, 2, X, Y)
plt.title('A=1, sigmaX=2, sigmaY=2', {'fontsize': 8, 'fontweight': 'bold'}, pad=0)
plt.imshow(Z, interpolation='nearest', extent=(-2,2,-2,2), cmap = 'jet')

axis3 = fig.add_subplot(223)
Z = func(1, 2, 1, X, Y)
plt.title('A=1, sigmaX=2, sigmaY=1', {'fontsize': 8, 'fontweight': 'bold'}, pad=0)
plt.imshow(Z, interpolation='nearest', extent=(-2,2,-2,2), cmap = 'jet')

axis4 = fig.add_subplot(224)
Z = func(1, 1, 2, X, Y)
plt.title('A=1, sigmaX=1, sigmaY=2', {'fontsize': 8, 'fontweight': 'bold'}, pad=0)
plt.imshow(Z, interpolation='nearest', extent=(-2,2,-2,2), cmap = 'jet')

plt.colorbar()
plt.show()
https://www.pygame.org/docs/ref/mixer.html
https://www.pygame.org/docs/ref/music.html

Pygame (music)
How to play music?
• Step1: Put a music file in the folder where the source code file exists.

Source code file

Music file

• Step2: Load a music file.


pygame.mixer.music.load("ukulele.mp3")

filename

• Stpe3: Play the music.


pygame.mixer.music.play()
Playing music (5 minutes)
import pygame # Run until the user asks to quit
running = True
# initialize while running:
pygame.init() # Main Event Loop
screen_width, screen_height = 320, 320 for event in pygame.event.get():
screen = pygame.display.set_mode((screen_width, screen_height)) if event.type == pygame.QUIT:
pygame.display.set_caption("Playing music") running = False

# music screen.fill('white')
pygame.mixer.init()
pygame.mixer.music.load("ukulele.mp3") # Update the screen
pygame.mixer.music.set_volume(0.5) pygame.display.flip()
pygame.mixer.music.play()
pygame.quit()

pygame.mixer.music.set_volume(volume)
0.0 ≤ volume ≤ 1.0
https://www.pygame.org/docs/ref/mixer.html
https://www.pygame.org/docs/ref/music.html

Pygame (mixer)
Playing music in different channels
Mixer (10 minutes)
import pygame # Run until the user asks to quit
running = True
# initialize while running:
pygame.init() # Main Event Loop
screen_width, screen_height = 320, 320 for event in pygame.event.get():
screen = pygame.display.set_mode((screen_width, screen_height)) if event.type == pygame.QUIT:
pygame.display.set_caption("Playing a music") running = False

# music screen.fill('white')
pygame.mixer.init()
# Update the screen
channel0 = pygame.mixer.Channel(0) pygame.display.flip()
channel0.set_volume(0.5)
sound0 = pygame.mixer.Sound("ukulele.mp3") pygame.quit()

channel1 = pygame.mixer.Channel(1)
channel1.set_volume(0.2)
sound1 = pygame.mixer.Sound("dreams.mp3")

channel0.play(sound0)
channel1.play(sound1)

Channel method:
- play, stop, pause, unpause, fadeout
- set_volume, get_volume, get_busy, get_sound
- …
Today’s mission
• (1) Shoot the ball on the player as (2) playing music.
– Define Circle and Rectangle class.
• (optional) Define Shape class and let the classes above inherit from Shape.
– Draw a guideline between the ball and mouse cursor.
– Shoot the ball along the guideline with LMB pressed.
– Reposition the ball when it is out of the boundary.
– Play any music.

– (optional) Modularization
• Shape.py
• Circle.py
• Rectangle.py
• etc.
• Import the modules above in main source code file.
Today’s mission (an example of class definition)

Shape Circle
x Instance
radius
y variable
Instance Instance
vx draw
variable method
vy
color
Rectangle
[Abstract]
draw Instance Width
Instance move variable Height
method
setPosition Instance
draw
method
setVelocity
Today’s mission (calculation the velocity)
1. Calculate the direction to shoot
Mouse
𝐝 = 𝑑𝑥 , 𝑑𝑦 = (𝑥𝑚 − 𝑥𝑏 , 𝑦𝑚 − 𝑦𝑏 )
(𝑥𝑚 , 𝑦𝑚 )

2. Calculate the unit vector.

𝑚𝑎𝑔𝑛𝑖𝑡𝑢𝑑𝑒 𝑚 = 𝑑𝑥2 + 𝑑𝑦2

𝐝 𝑑𝑥 𝑑𝑦 Ball
𝑢𝑛𝑖𝑡 𝑣𝑒𝑐𝑡𝑜𝑟 𝐝ሚ = = ,
𝑚 𝑚 𝑚
(𝑥𝑏 , 𝑦𝑏 )
3. Calculate [speed x unit vector].
𝑆𝑝𝑒𝑒𝑑: 𝑠
𝑠 𝑠
𝐯 = s𝐝ሚ = 𝑑 , 𝑑
𝑚 𝑥 𝑚 𝑦

You might also like