import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Time step for the animation (s), max time to animate for (s).
dt, tmax = 0.01, 5
# Signal frequency (s-1), decay constant (s-1).
f, alpha = 2.5, 1
# These lists will hold the data to plot.
t, M = [], []
# Draw an empty plot, but preset the plot x- and y-limits.
fig, ax = plt.subplots()
line, = ax.plot([], [])
ax.set_xlim(0, tmax)
ax.set_ylim(-1, 1)
ax.set_xlabel('t /s')
ax.set_ylabel('M (arb. units)')
def init():
return line,
def animate(i, t, M):
# Append this time point and its data and set the plotted line data.
_t = i*dt
t.append(_t)
M.append(np.sin(2*np.pi*f*_t) * np.exp(-alpha*_t))
line.set_data(t, M)
return line,
# Interval between frames in ms, total number of frames to use.
interval , nframes = 1000 * dt, int(tmax / dt)
ani = animation.FuncAnimation(fig, animate , frames=nframes , init_func=init,
fargs=(t, M), repeat=False, interval=interval , blit=True)
ani.save('ex424.gif', writer='imagemagick')
plt.show()
Recent Comments