Plot animation
Using the matplotlib.animation
and FuncAnimation
module, we can create animations of our plots:
class matplotlib.animation.FuncAnimation(
fig, func,
frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs
)
Earth rotation around sun
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def rotate_around_point(p_old, a, b, phi):
translation_matrix = np.array([
[1, 0, a],
[0, 1, b],
[0, 0, 1]
])
rotation_matrix = np.array([
[np.cos(phi), -np.sin(phi), 0],
[np.sin(phi), np.cos(phi), 0],
[0, 0, 1]
])
return (translation_matrix @ rotation_matrix @ np.linalg.inv(translation_matrix)) @ p_old
if __name__ == '__main__':
# start coordinates of earth
earth = np.array([5, 0, 1])
# coordinates of the sun
sun = np.array([0, 0, 1])
n_per_day = 5
n_days = 365
n = n_days * n_per_day # number of iterations
phi_rotate = (np.pi * 2) / n # angular velocity earth - sun
# Earths orbit with respect to time
earth_coordinates = [earth]
for i in range(n):
earth_coordinates.append(
rotate_around_point(earth_coordinates[-1], sun[0], sun[1], phi_rotate)
)
fig, ax = plt.subplots()
plt.plot(sun[0], sun[1], '*b')
ln, = plt.plot([], [], 'or')
def init():
ax.axis([-8, 8, -8, 8])
ax.set_aspect('equal', 'box')
return ln,
def update(frame):
ln.set_data(earth_coordinates[frame][0], earth_coordinates[frame][1])
return ln,
ani = FuncAnimation(fig, update, frames=n, init_func=init, interval=10)
plt.show()