- 用numpy表示高階的函數(shù)蜡坊,并用matplotlib將函數(shù)對應(yīng)的曲線畫出來〕嵴螅可添加子圖歪玲,可進行顏色填充,可3D掷匠,可等高圖滥崩。
import numpy as np
import matplotlib.pyplot as plt
func = np.poly1d(np.array([1, 2, 3, 4]))
# print(func) # 1 x^3 + 2 x^2 + 3 x + 4
func1 = func.deriv(m=1)
# print(func1) # 3x^2 + 4x +3 對func求一階導(dǎo)數(shù)
func2 = func.deriv(m=2)
# print(func2) # 6x + 4 對func求二階導(dǎo)數(shù)
x = np.linspace(-10, 10, 30) # 起點-10,終點10讹语,共描點30個
y = func(x)
y1 = func1(x)
y2 = func2(x)
plt.plot(x, y, 'ro', x, y2, 'g--') # 'ro'是紅圓點,'g--'是綠色線條
plt.xlabel('this is x') # 這個是定義x,y坐標的名稱
plt.ylabel('this is y')
plt.show()
Figure_1.png
'''添加子圖'''
plt.subplot(311)
plt.plot(x, y, c='r', linestyle='-')
plt.title('Polynomial') # 多項式
plt.subplot(312)
plt.plot(x, y1, c='b', linestyle='-', marker='^') # 藍色連線三角形標點
plt.title('first dervative') # 一階導(dǎo)數(shù)
plt.subplot(313)
plt.plot(x, y2, c='g', linestyle='', marker='o') # 綠色不連線圓形標點
plt.title('second derivative') # 二階導(dǎo)數(shù)
plt.show()
Figure_2.png
'''顏色填充'''
fig = plt.figure()
# fig.fill_between(x, y, y1, facecolor='b') # 'Figure' object has no attribute 'fill_between'
ax = fig.add_subplot(211)
ax.fill_between(x, y, y1, facecolor='b') # 在兩條曲線之間填充
ax.grid(True)
ax2 = fig.add_subplot(212)
ax2.fill(x, y, facecolor='b', alpha=0.3) # 在曲線和'兩端點之間線段'之間填充
ax2.fill(x, y1, facecolor='g', alpha=0.3)
ax2.grid(True)
plt.show()
Figure_3.png
'''三維繪圖'''
from mpl_toolkits.mplot3d import Axes3D
u = np.linspace(-1, 1, 100)
x, y = np.meshgrid(u, u)
z = x ** 2 + y ** 2
fig = plt.figure()
ax = Axes3D(fig)
# cmap = color_map
ax.plot_surface(x, y, z, rstride=4, cstride=4, cmap='rainbow')
plt.show()
Figure_4.png
'''三維等高線圖'''
u = np.linspace(-1, 1, 100)
x, y = np.meshgrid(u, u)
z = x**2+y**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.contourf(x, y, z)
plt.show()
Figure_5.png