Home Subscribe

2. Basic Animation

In this section, we shall visualize a 1-dimensional movement of an object, say, an airplane. To run each of the following projects, make one program in vscode, say, program.py, and then run in vscode terminal $ python program.py.

2.1. Simple Linear X-Y Plot

Let us begin by plotting increasing values of x and y.

 1import matplotlib.pyplot as plt
 2import numpy as np
 3
 4max = 200
 5
 6fig, ax = plt.subplots()
 7
 8x = np.arange(0,max, step=1)
 9y = x
10
11#x and y limits
12ax.set_xlim(0, max)
13ax.set_ylim(0, max)
14
15# plot graph
16ax.plot(x, y, color = "blue")
17ax.set_xlabel("X"); ax.set_ylabel("Y")
18#plt.savefig("../images/xy_plot.png")
19plt.show()
xy plot

2.2. For-Loop-Animated X-Y Plot

This can be animated by adding the following lines.

 1import matplotlib.pyplot as plt
 2import numpy as np
 3
 4x = []
 5y = []
 6max = 100
 7count = 0
 8
 9fig, ax = plt.subplots()
10
11for frame in range(max):
12    x.append(frame)
13    y.append(frame)
14
15    # x and y limits
16    ax.set_xlim(0, max)
17    ax.set_ylim(0, max)
18
19    # plot graph
20    ax.plot(x, y, color = "blue")
21    plt.pause(0.02)
22    #plt.savefig("basic-anim/frame"+str(count)+".jpg")
23    count += 1
24# $ sudo apt-get install imagemagick
25# $ convert -delay 10 -loop 0 *.jpg basic_anim.gif
basic anim

2.3. FunAnimation Sine-Wave Animation

Using FunAnimation can help us to make detailed looping animations with fewer lines of code. We can also save the animation easily.

If you are using Jupyter Notebook, you might have to add the following lines, every time you use FuncAnimation

 1# Add this at the top
 2# import libraries, then:
 3from matplotlib.animation import FuncAnimation
 4from IPython.display import HTML
 5%matplotlib notebook
 6
 7# <insert animation setup code here>
 8
 9anim = FuncAnimation()  # With arguments of course!
10HTML(anim.to_jshtml())
11# Or:
12# HTML(anim.to_html5_video())

 1import numpy as np
 2from matplotlib import pyplot as plt
 3from matplotlib.animation import FuncAnimation
 4
 5max = 200
 6x = np.linspace(0, 2*np.pi, max)
 7y = np.sin(x)
 8
 9fig, ax = plt.subplots() 
10line = ax.plot([])[0] # tuple 
11
12ax.set_xlim(0, 2*np.pi) 
13ax.set_ylim(-1.1, 1.1) 
14ax.set_ylabel("Y")
15ax.set_xlabel("X")
16ax.set_title("Sine Wave Animation")
17
18def animate(frame):
19    y = np.sin(x + 2*np.pi *frame/max)
20    line.set_data((x,y))
21    return line 
22
23anim = FuncAnimation(fig,
24                    animate,
25                    frames=len(x),
26                    interval=20)
27
28#anim.save(r'sine-wav-anim.mp4')
29plt.show()
sine wave animation

2.4. Animating Random Data

 1import numpy as np
 2import matplotlib.pyplot as plt
 3from matplotlib.animation import FuncAnimation
 4
 5# prepare random data
 6max = 100
 7x = range(max)
 8y = np.random.rand(max)
 9
10# prepare figure environment 
11fig, ax = plt.subplots()
12ax.set_xlim(np.min(x), np.max(x))
13ax.set_ylim(np.min(y), np.max(y))
14ax.set_xlabel("Random X")
15ax.set_ylabel("Random Y")
16
17graph = plt.plot([], [], ls='-')[0]
18
19# animation function 
20def animate(i):
21    graph.set_data(x[:i],y[:i])
22    return graph,
23
24# animate
25anim = FuncAnimation(fig, 
26                    animate, 
27                    frames=len(x), 
28                    interval=15, 
29                    blit=True,
30                    #save_count=len(x),
31                    )
32
33##anim.save('gen_anim.gif', writer='PillowWriter')
34#anim.save(r'gen_anim.mp4')
35plt.show()
gen anim

Instead of x and y random data, you can use realistic ecg data by adding the following lines below x and y arrays:

 9# $ conda install -c anaconda scipy
10import scipy.signal as sig
11# or use realistic ecg signal
12rr = [1.0, 1.0, 0.5, 1.5, 1.0, 1.0] # rr time in seconds
13fs = 50.0 # sampling rate
14pqrst = sig.wavelets.daub(10) # just to simulate a signal, whatever
15ecg = np.concatenate([sig.resample(pqrst, int(r*fs)) for r in rr])
16t = np.arange(len(ecg))/fs
17x,y = t,ecg # comment this to use random data instead of ecg signal
gen anim ecg


Add Comment

* Required information
1000
Drag & drop images (max 3)
Enter the word hand backwards.

Comments

No comments yet. Be the first!