fig,ax=plt.subplots()
xdata,ydata=[],[]
ln, = ax.plot([],[],'r--') #这里要解包,用ln, 逗号不能省略
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig,ax=plt.subplots()
xdata,ydata=[],[]
ln, = ax.plot([],[],'r--')
print(ax)
#画布初始化配置
ax.set_ylim(-2, 2)
ax.set_xlim(0, 4 * np.pi)
def init():
print('init-->')
# ax.set_xlim(0,2*np.pi)
# ax.set_ylim(-1,1)
return ln,
def animate(frame):
print('ani-->',frame)
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata,ydata)
return ln,
ani=FuncAnimation(fig, #画板
animate,
frames=np.linspace(0,2*np.pi,60),
init_func=init,
blit=True
)
plt.show()
通用绘制动画模板
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig,ax=plt.subplots()
xdata,ydata=[],[]
ln, = ax.plot([],[],'r--')
def init():
print('init-->')
ax.set_xlim(0,2*np.pi)
ax.set_ylim(-1,1)
return ln,
def animate(frame):
print('ani-->',frame)
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata,ydata)
return ln,
ani=FuncAnimation(fig, #画板
animate,
frames=np.linspace(0,2*np.pi,60),
init_func=init,
blit=True)
plt.show()
多子图显示动画示例:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig,ax=plt.subplots(1,2) #注意,这里ax是个列表,里面放了两个子图画布
xdata,ydata1,ydata2=[],[],[]
ln1, = ax[0].plot([],[],'r--')
ln2, = ax[1].plot([],[],'g*') #这里必须这样解包,哪怕是一个,也有解包列表
def init():
print('init-->')
ax[0].set_xlim(0,2*np.pi)
ax[0].set_ylim(-1,1)
ax[1].set_xlim(0, 2 * np.pi)
ax[1].set_ylim(-1, 1)
return ln1,ln2,
def animate(frame):
print('ani-->',frame)
xdata.append(frame)
ydata1.append(np.sin(frame))
ln1.set_data(xdata,ydata1)
ydata2.append(np.cos(frame))
ln2.set_data(xdata,ydata2)
return ln1,ln2,
ani=FuncAnimation(fig, #画板
animate,
frames=np.linspace(0,2*np.pi,60),
init_func=init,
blit=True
)
plt.show()
这里有个地方要特别注意,ln2, = ax[1].plot([],[],'g*'),这的逗号不额能省略。