1 3D圖
繪製3D圖,額外導入一個 Axes3D的包;
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
# 把圖像傳入到3D的視圖中
ax = Axes3D(fig)
x = np.arange(-4,4,0.25)
y = np.arange(-4,4,0.25)
# 將x,y傳入到網格中
X,Y = np.meshgrid(x,y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# 3D圖,rstride和cstride是下圖中小方格的大小
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))
# 等高線圖的映射,底盤
ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
ax.set_zlim(-2,2)
plt.show()
注:在jupyter中,這個3D圖不能動,可以把代碼複製到 IPython 中運行,就會生成一個figure,可以鼠標旋轉查看。
2 subplot多圖合一
import matplotlib.pyplot as plt
import numpy as np
調用 .subplot函數設置多個子圖像
三個參數,第一個參數是幾行,第二個參數是幾列,第三個參數是第幾個位置
plt.figure()
plt.subplot(2,2,1)
plt.plot([0,1],[0,1])
plt.subplot(2,2,2)
plt.plot([0,1],[0,1])
plt.subplot(2,2,3)
plt.plot([0,1],[0,1])
plt.subplot(2,2,4)
plt.plot([0,1],[0,1])
plt.show()
plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,1])
plt.subplot(235)
plt.plot([0,1],[0,1])
plt.subplot(236)
plt.plot([0,1],[0,1])
plt.show()
3 動態圖
動態圖也需要導入animation包;
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
fig,ax = plt.subplots()
x = np.arange(0,2*np.pi,0.01)
line, = ax.plot(x,np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10))
return line,
def init():
line.set_ydata(np.sin(x))
return line,
# interval=20,動態圖的圖像間隔是20毫秒
ani = animation.FuncAnimation(fig=fig,func=animate,init_func=init,interval=20)
plt.show()
注:這裏並沒有貼出gif動態圖,可以在 IPython中輸入上述代碼,運行產看動態圖。