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()
I want to plot y=omega*sin(x), which omega is start from -3 to 3 with step size 0.25, and x start from -4 to 4 with step size 0.1. I can animate it with above code.
Now, I want add the animated title "omega = ..." (the value of omega is suitable with moving curve). I don't know how to do it. I just can add plt.title('omega = {}')
. So, how to animate the title in FuncAnimation? Any help be very appreciated.
Inside animate()
use plt.title()
or axis.title.set_text()
with new text.
And you can use f-string
to format it.
def animate(i):
# use 5 places (also count `-` and `.`), and always two digits after dot
plt.title( f'omega = {omega[i]:5.2f}' )
#axis.title.set_text(f'omega = {omega[i]:5.2f}')
y = omega[i]*np.sin(x)
line.set_data(x, y)
return line,