# 汪群超 Chun-Chao Wang

Dept. of Statistics, National Taipei University, Taiwan

# Lesson 2: Start with function computing and graphing

### Objective :

1. Learn how to evaluate a function.
2. Learn how to draw the graph of a function with various presentations.
3. Get familiar with Python syntax.

### Prerequisite:

1. Object type : Number, String, List, Tuple, Dictionary, File

Note:
1. Use numpy and matplotlib packages
2. Use numpy.linspace to generate a sequence of x with fixed size.
import matplotlib.pyplot as plt
import numpy as np

n = 100 # number of points
# create a x vector by number
x = np.linspace(-5, 5, n)
# compute y
y = x**2 + 3*x + 5

plt.plot(x, y)
plt.grid(True)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('$f(x)=x^2+3x+5$')
plt.show()


Note:
1. Use numpy.arange to get a sequence of x with fixed step.
2. Use numpy’s anonymous function: lambda.
3. Create a empty figure before drawing on the axis.
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 7, 0.01)
# formulate a function f
f = lambda x : x**3 - 10*x**2 + 29*x - 20

fig = plt.figure(figsize=[6, 4])
plt.plot(x, f(x), linestyle = '--', color = 'r')
plt.grid(True)
plt.xlabel('X'), plt.ylabel('Y')
plt.title('$f(x)=x^3-10x^2+29x-20$')
plt.show()


Note:
1. Try to select an appropriate range for x so that the global minimum of f(x) is visually identified.
2. Use numpy polyval to compute the polynomial function.
3. Use the axis object to work on the details of plotting.
4. Save the current figure as an eps file.
import matplotlib.pyplot as plt
import numpy as np

xmin, xmax = -5, 10
x = np.linspace(xmin, xmax, 100)
p = [1, -8, 16, -2, 8]
f = lambda x : np.polyval(p, x)

fig = plt.figure()
# use axis object
ax = plt.gca() # get current axis
ax.plot(x, f(x), linewidth = 3, color ='g', linestyle ='-.')
ax.grid(True)
ax.set_xlabel('X'), ax.set_ylabel('f(x)')
ax.set_title('The range of $x$ is not appropriate')
ax.text(0, 2500, 'Re-define the range of $x$')
# save the current figure as an eps file
plt.savefig('poly.eps', format='eps')
plt.show()


Note:
1. Mimic the previous codes to complete this example.
2. Treat this function as an addition of finite terms and add one term in the code each time.
3. Use “for loop” technique after successfully drawing the graphs after adding some terms.
4. Use “pause()” to demonstrate the animation as more and more terms adding in.
5. Search in Numpy document for the use of $\sin x$ and $\pi$.
6. Determine specific tick and ticklabel in X axis
7. Learn how to use pause() in matplotlib.pyplot
import numpy as np
import matplotlib.pyplot as plt

# The codes below demonstrate the ticks and labels in x axis
x = np.linspace(-3*np.pi, 3*np.pi,200)
y = 4 / np.pi * np.sin(x)
fig, ax = plt.subplots(1)
ax.plot(x, y, color='b')
ax.set_xticks(np.array([-3, -2, -1, 0, 1, 2, 3])*np.pi)
ax.set_xticklabels(['-3$\pi$', '-2$\pi$', '$\pi$', '0', '$\pi$','2$\pi$','3$\pi$'], \
fontsize=10, color = 'b')
ax.set_ylim([-3, 3])
ax.grid(True)
plt.show()



$f_1(x) = \sin x, \; f_2(x) = \sin 2x, \;\; f_3(x) = \sin 3x$

Note:

1. Learn Python syntax for looping statements.
2. Add legend on a graph by labelling each line.
3. Practice insert number in a text string by “format”.
import numpy as np
import matplotlib.pyplot as plt

n = [1, 2, 3]
colors = ['r', 'g', 'b']
x = np.linspace(-3*np.pi, 3*np.pi, 200)
for i in n:         # always start with a colon
y=np.sin(i*x)   #blocks of code are identified by indentation
plt.plot(x, y, label = 'sin({}x)'.format(i), \
color = colors[i - 1])

plt.legend()
plt.ylim(-2.5, 2.5), plt.grid(True), plt.xlabel('X')
plt.title('Demonstration of legend for each line')
plt.show()


Note:

1. Try to patch a polygon (Search “polygon” in matplotlib).
2. Test the transparency of colors.
import matplotlib.pyplot as plt
import matplotlib.patches as pat

fig, ax = plt.subplots(figsize=(4,3))
rec1 = pat.Rectangle((1, 1), 2, 3, color ='green', alpha = 0.5)
rec2 = pat.Rectangle((2, 2), 2, 3, color ='red', alpha = 0.5)
plt.xlim([0,5]), plt.ylim([0,6])
plt.show()


$f(x) = 2x-x^2,\;\; g(x) = x^2$

Note:

1. Try to patch the region enclosed by two functions at your selections.
2. Re-arrange four axes spines.
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-0.5, 1.6, 100)
f = lambda x : 2*x - x**2
g = lambda x : x**2

plt.plot(x, f(x), x, g(x)) # draw two lines in a command
plt.fill_between(x, f(x), g(x), where = f(x) > g(x), color = 'pink') # defaut : y1>y2
plt.text(0.2, 2, '$\int_0^1 (f(x) - g(x)) \; dx$', fontsize = 14)
ax = plt.gca()
# Re-arrange four axes spines
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
ax.spines['top'].set_visible(False) # take off top line
ax.spines['right'].set_visible(False)
plt.show()


Exercises :

Note:

1. For each function, please define appropriate range for x to have a better look at the function.
2. Try to use all the graphing techniques introduced here.
Exercises:
1. $f(x) = \sin(x) + \cos(x)$
2. $f(x) = \frac{1-e^{-2x}}{1+e^{-2x}}$
3. $f(x) = \sqrt[3]{\frac{4-x^3}{1+x^2}}$
4. $f(x) = \frac{1}{x}$
5. $f(x) = \frac{1}{2\sqrt{2\pi}} e^{-\frac{(x-1)^2}{8}}$
6. $f(x) = \sqrt[3]{x^2}$
7. $f(x) = 2x^3-x^4$
8. $f(x) = \frac{\ln x}{x^3}$
9. $f(x) = 3, \;\; 1 \leq x \leq 5$
10. $x^2+y^2 = 1$.
You may want to try one of the followings:
• Rewrite as parametric equations, i.e. $x = \sin \theta, y = \cos \theta, \;\; 0 \leq \theta \leq 2\pi$
• Treat the circle as an implicit function.
• May use a command for drawing a circle in matplotlib module.
Need to set the aspect as equal to have a perfect circle, e.g. ax.set_aspect(1)
11. Draw a square of side =1