from matplotlib import pyplot as plt
import numpy as np
import matplotlib.animation as animation
import sys
class AniPlot():
# init the class
def __init__(self):
# get the figure object
self.fig = plt.figure()
# setup a single axes
self.ax = plt.subplot(1, 1, 1)
# register the callbac to kill the app when the window is closed
self.fig.canvas.mpl_connect('close_event', self.on_close)
# register the callaback for plot animation
self.anim = animation.FuncAnimation(self.fig, self.ani_update, interval=2000, blit=False)
self.anim.save('growingCoil.mp4', writer = 'ffmpeg', fps = 30)
# `close event` callback`
def on_close(self, event):
print('Closed Figure!')
sys.exit()
# recalculate the sine wave, noise data and perform convolution
def recalculate(self):
# data step
dt = 0.01
# get time series for x axis
self.t = np.arange(0, 10, dt)
# generate some noise data
self.nse = np.random.randn(len(self.t))
r = np.exp(-self.t / 0.05)
self.cnse = np.convolve(self.nse, r) * dt
self.cnse = self.cnse[:len(self.t)]
# generate sine wave with phase noise
self.s = 0.1 * np.sin(2 * np.pi * self.t) + self.cnse
def redraw_figure(self):
# redraw the canvas
self.fig.canvas.draw_idle()
plt.pause(0.00001)
def ani_update(self, i):
# do initial plot
self.recalculate()
h2, = plt.plot(self.t, self.s, linewidth=1, markersize=1.5)
while True:
# do calculate, plot and redraw
self.recalculate()
h2.set_ydata(self.s)
self.redraw_figure()
# create out class
AniPlot()
# start the animation
plt.show()