numpy 和 matplotlib 相關(guān)筆記

  • 用numpy表示高階的函數(shù),并用matplotlib將函數(shù)對應(yīng)的曲線畫出來。可添加子圖,可進(jìn)行顏色填充,可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)  # 起點(diǎn)-10,終點(diǎn)10,共描點(diǎn)30個
y = func(x)
y1 = func1(x)
y2 = func2(x)
plt.plot(x, y, 'ro', x, y2, 'g--')  # 'ro'是紅圓點(diǎn),'g--'是綠色線條
plt.xlabel('this is x')  # 這個是定義x,y坐標(biāo)的名稱
plt.ylabel('this is y')
plt.show()

附: numpy.poly1d詳細(xì)說明

Figure_1.png

'''添加子圖'''
plt.subplot(311)
plt.plot(x, y, c='r', linestyle='-')
plt.title('Polynomial')  # 多項(xiàng)式

plt.subplot(312)
plt.plot(x, y1, c='b', linestyle='-', marker='^')  # 藍(lán)色連線三角形標(biāo)點(diǎn)
plt.title('first dervative')  # 一階導(dǎo)數(shù)

plt.subplot(313)
plt.plot(x, y2, c='g', linestyle='', marker='o')  # 綠色不連線圓形標(biāo)點(diǎn)
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)  # 在曲線和'兩端點(diǎn)之間線段'之間填充
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容