Saturday, February 24, 2024

PMAE 2 : rotating regular polygon

Python Matplotlib Animation Example 2

rotating regular polygon

This Python code utilizes the Matplotlib library to create an animated visualization of a rotating regular polygon. The polygon, defined by the getdata function, has five sides in this example, but you can adjust the number of sides as desired. The rotation of the polygon is animated based on the current time, providing a continuous rotation effect. The code employs trigonometric functions to calculate the coordinates of the polygon's vertices and updates the plot accordingly. The resulting plot showcases a dynamic and visually appealing animation of a regularly rotating polygon in a window.


The Python code effectively generates a regular polygon and animates its rotation using mathematical calculations and Matplotlib's animation capabilities. Key functions include getdata for calculating vertex coordinates, update for rotating the polygon, and draw for controlling animation timing and updating the plot. The code demonstrates the use of trigonometry for polygon generation and rotation, and highlights the importance of FuncAnimation for creating smooth animations in Matplotlib. While currently generating a pentagon, the getdata function can be modified to handle polygons with different numbers of sides.

Python source code

import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from math import cos, sin, tan, pi

fig = plt.figure(figsize=(3,3), facecolor="#FFFFFF")
ax = plt.axes([0, 0, 1, 1])
ax.set_xlim([-1.2, 1.2])
ax.set_ylim([-1.2, 1.2])
ax.axis('off')

def getdata(n):
nth = int(500/n)*n+1
dth = 2*pi/(nth-1)
sth = 2*pi/n
xs, ys = [], []
for ith in range(nth):
theta = ith*dth
rth = int(theta/sth)*sth
x1 = cos(sth/2)
y1 = tan(sth/2-(theta-rth))*x1
x2 = x1*cos(rth) + y1*sin(rth)
y2 = -x1*sin(rth) + y1*cos(rth)
xs.append(x2)
ys.append(y2)
return xs, ys

pl = ax.plot([], [], color="#0000FF")[0]

xs, ys = getdata(5)

def update(theta):
ith = int(theta/(2*pi/(len(xs)-1)))
xp, yp = [], []
for i in range(len(xs)):
x = xs[i]*cos(theta) - ys[i]*sin(theta)
y = xs[i]*sin(theta) + ys[i]*cos(theta)
xp.append(x)
yp.append(y)
pl.set_data(xp, yp)

def draw(i):
P = 10.0
t = time.time()
theta = t/P*2*pi%(2*pi)
update(theta)

ani = animation.FuncAnimation(fig, draw, interval=40)

plt.show()

This Python code creates an animation of a rotating regular polygon using the `matplotlib` library.

■ Import necessary libraries:
• `time`: Provides access to time-related functions for animation.
• `matplotlib.pyplot as plt`: Offers functionalities for creating plots and visualizations.
• `matplotlib.animation as animation`: Enables creating animations from sequences of images.
• `math`: Contains mathematical functions like `cos`, `sin`, `tan`, and `pi`.

■ Set up the figure and axes:
• `fig = plt.figure(figsize=(3,3), facecolor="#FFFFFF")`: Creates a figure with a specified size (3x3 inches) and white background.
• `ax = plt.axes([0, 0, 1, 1])`: Defines an axes object within the figure, occupying the entire area.
• `ax.set_xlim([-1.2, 1.2])`: Sets the x-axis limits from -1.2 to 1.2.
• `ax.set_ylim([-1.2, 1.2])`: Sets the y-axis limits from -1.2 to 1.2.
• `ax.axis('off')`: Hides the axes labels and tick marks for a cleaner visualization.

■ Define the `getdata` function:
• `getdata(n)`: This function takes the number of sides (`n`) of the regular polygon as input and returns the coordinates of its vertices.
• `nth = int(500/n)*n+1`: Calculates a suitable number of points (`nth`) for smooth visualization, ensuring at least one point per side.
• `dth = 2*pi/(nth-1)`: Calculates the angular increment (`dth`) between consecutive points on the polygon's perimeter.
• `sth = 2*pi/n`: Computes the central angle (`sth`) subtended by each side.
• The function iterates through `nth` points, calculating their x and y coordinates using trigonometric functions and transformations.
• `xs` and `ys` lists store the calculated x and y coordinates, respectively.
• The function returns `xs` and `ys`.

■ Initialize the plot:
• `pl = ax.plot([], [], color="#0000FF")[0]`: Creates an empty line plot (`pl`) with blue color, initially representing the polygon.

■ Define the `update` function:
• `update(theta)`: This function takes the rotation angle (`theta`) as input and updates the coordinates of the polygon's vertices.
• `ith = int(theta/(2*pi/(len(xs)-1)))`: Calculates the index of the vertex that should be at the "front" based on the current rotation angle.
• `xp` and `yp` lists are created to store the updated x and y coordinates.
• The function iterates through all vertices, applying the rotation transformation using `cos` and `sin` functions.
• The updated coordinates are appended to `xp` and `yp`.
• The line plot (`pl`) is updated with the new coordinates using `pl.set_data(xp, yp)`.

■ Define the `draw` function:
• `draw(i)`: This function is called repeatedly to produce animation frames.
• `P = 10.0`: Sets the animation period (`P`) to 10 seconds (controls the speed of rotation).
• `t = time.time()`: Gets the current time.
• `theta = t/P*2*pi%(2*pi)`: Calculates the rotation angle (`theta`) based on the elapsed time and animation period, ensuring it stays within a full circle (0 to 2pi).
• The `update` function is called with the calculated `theta` to update the polygon's position.

■ Create and display the animation:
• `ani = animation.FuncAnimation(fig, draw, interval=40)`: Creates an animation object (`ani`) using the `FuncAnimation` class.
• `fig`: The figure to be animated.
• `draw`: The function to be called for each frame.
• `interval=40`: The time interval (in milliseconds) between frames, controlling the animation speed.
• `plt.show()`: Displays the animation.

No comments:

Post a Comment