学习目标:
利用matplotlib 和 numpy 画三角函数曲线
学习内容:
正弦,余弦,正切,余切函数曲线
双曲正弦,双曲余弦,双曲正切,双曲余切函数曲线
反正弦,反余弦,反正切,反余切函数曲线
反双曲正弦,反双曲余弦,反双曲正切,反双曲余切函数曲线
学习产出:
1.1, python画正弦函数曲线,保持原有的position不变的情况,代码如下:import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize = (6, 8), dpi = 200) # create a frame, dpi = 200
plt.subplot(111) #create a subgraph, grid = 1 * 1
x = np.linspace(-np.pi, np.pi, 256, endpoint = True) #numpy array:[-π, π], total 256 values
y = np.sin(x)
plt.plot(x, y, color = 'blue', linewidth = 2.0, linestyle= '-') #define line color and style
plt.xlim(x.min() * 1.1, x.max() * 1.1) #limit x range
plt.ylim(y.min() * 1.1, y.max() * 1.1) #limit y range
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$\pi/2$',r'$\pi$']) # 5 values in x_axis
plt.yticks([-1,-0.5,0,0.5,1],[r'$-1$',r'$-0.5$',r'$0$',r'$0.5$',r'$1$']) # 5 values in y-axis
plt.show()
正弦曲线图片如下:
利用spine,在数据区域的边界,可以放置在任意位置, 在上述代码中加入,完整的代码和曲线如下:
import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize = (6, 8), dpi = 200) # create a frame, dpi = 200
plt.subplot(111) #create a subgraph, grid = 1 * 1
x = np.linspace(-np.pi, np.pi, 256, endpoint = True) #numpy array:[-π, π], total 256 values
y = np.sin(x)
plt.plot(x, y, color = 'blue', linewidth = 2.0, linestyle= '-') #define line color and style
plt.xlim(x.min() * 1.1, x.max() * 1.1) #limit x range
plt.ylim(y.min() * 1.1, y.max() * 1.1) #limit y range
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$\pi/2$',r'$\pi$']) # 5 values in x_axis
plt.yticks([-1,-0.5,0,0.5,1],[r'$-1$',r'$-0.5$',r'$0$',r'$0.5$',r'$1$']) # 5 values in y-axis
#move the boundary line,set origin is 0
ax = plt.gca() #get current line position
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0)) #set bottom position to 0
ax.spines['left'].set_position(('data', 0))
ax.spines['top'].set_color('none') #cancel original boundary
ax.spines['right'].set_color('none')
plt.show()
去掉边框的正弦曲线图片如下:
1.2, python画余弦函数曲线, 我们在正弦曲线的代码中加入z = np.cos(x)的代码,同时需要区分正弦曲线和余弦曲线:
import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize = (6, 8), dpi = 200) # create a frame, dpi = 200
plt.subplot(111) #create a subgraph, grid = 1 * 1
x = np.linspace(-np.pi, np.pi, 256, endpoint = True) #numpy array:[-π, π], total 256 values
y = np.sin(x)
z = np.cos(x)
plt.plot(x, y, color = 'blue', linewidth = 2.0, linestyle= '-') #define line color and style
plt.plot(x, z, color = 'red', linewidth = 2.0, linestyle= '-')
plt.xlim(x.min() * 1.1, x.max