import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig = plt.figure()
axis = plt.axes(xlim=(-4, 4), ylim=(-3, 3))
line, = axis.plot([], [],'r+', lw=2)
plt.title('omega = {}')
def init():
line.set_data([], [])
return line,
def animate(i):
y = omega[i]*np.sin(x)
line.set_data(x, y)
return line,
x = np.arange(-4, 4+0.1, 0.1)
domega = 0.25
omega = np.arange(-3, 3+domega, domega)
anim = FuncAnimation(fig, animate, init_func=init, frames=omega.size, interval=120, blit=False)
plt.show()
我想绘制 y=omega*sin(x),其中 omega 从 -3 到 3 开始,步长为 0.25,x 从 -4 到 4 开始,步长为 0.1。我可以用上面的代码为其添加动画。
现在,我想添加动画标题“omega = ...”(omega的值适合移动曲线)。我不知道该怎么做。我只能添加
plt.title('omega = {}')
。那么,如何在 FuncAnimation 中对标题进行动画处理呢?非常感谢任何帮助。
在
animate()
内部使用plt.title()
与新文本
例如此代码在标题中显示
i
`
def animate(i):
plt.title(f'i = {i}')
y = omega[i]*np.sin(x)
line.set_data(x, y)
return line,