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