Thursday, March 28, 2024

PMAE 7 : regular star polygon

Python Matplotlib Animation Example7

regular star polygon

The Python code presented utilizes matplotlib to dynamically visualize a regular star polygon, employing mathematical principles to compute its coordinates. The getdata function calculates these coordinates based on the number of vertices (n) and a parameter (k) determining the star's density. Trigonometric functions are employed for computation. The update function dynamically updates the plot with generated coordinates as the animation progresses, controlled by the drawfig function for timing and theta calculation. Through the FuncAnimation class, the animation smoothly portrays the rotation of the star polygon, showcasing its geometric properties. This code exemplifies Python's capacity for mathematical visualization, facilitating both exploration and representation of complex geometric concepts in an interactive manner.

 

 

The Python code skillfully animates a regular star polygon by first leveraging a function called getdata to accurately compute the vertices of the star based on the desired number of points and a scaling factor. It then harnesses the power of Matplotlib for visualization, creating a clean and well-defined figure. The animation is achieved through a time-dependent loop that continuously updates the plot with a calculated portion of the star's points, masterfully generating the illusion of smooth rotation. This code showcases a deep understanding of both geometric principles and Python's plotting and animation tools, resulting in an informative and visually engaging experience.

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, 0.0, 1.0, 1.0])
ax.set_xlim([-1.2, 1.2])
ax.set_ylim([-1.2, 1.2])
ax.axis("off")

def getdata(n, k):
nth = 3000
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 = cos(sth/2*k)
y2 = y1*(tan(sth/2*k)*x2)/(tan(sth/2)*x1)
x3 = x2*cos(rth*k) + y2*sin(rth*k)
y3 = -x2*sin(rth*k) + y2*cos(rth*k)
xs.append(x3)
ys.append(y3)
xs.append(xs[0])
ys.append(ys[0])
return xs, ys

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

xs, ys = getdata(5, 2)

def update(theta):
ith = int(theta/(2*pi/(len(xs)-1)))
pl.set_data(xs[0:ith+1], ys[0:ith+1])

def drawfig(i):
P = 5.0
t = time.time()
theta = t/P*2.0*pi%(2.0*pi)
update(theta)

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

plt.show()

 ■ Import Necessary Libraries:

   • `time` for time-based operations
• `matplotlib.pyplot` for creating visualizations
• `matplotlib.animation` for animating the plot
• `math` for mathematical functions

■ Figure Setup:
• Create a figure with a white background and square dimensions.
• Define axes with limits ranging from -1.2 to 1.2 for both x and y.
• Turn off axis labels and ticks for visual clarity.

■ Polygon Data Generation (`getdata` Function):
• Takes two parameters: the number of points (`n`) and a scaling factor (`k`).
• Calculates the x and y coordinates of the star polygon's vertices using trigonometric functions and rotations.
• Returns lists of x and y coordinates for the polygon.

■ Initial Plot Creation:
• Create an empty plot with blue color for later updates.

■ Polygon Data Calculation:
• Call `getdata` to generate coordinates for a 5-pointed star with scale factor 2.

■ Animation Loop (`drawfig` Function):
• Calculate a time-dependent angle `theta`.
• Call `update` to update the plot with a portion of the polygon based on `theta`.

■ Plot Update (`update` Function):
• Determine how much of the polygon to display based on `theta`.
• Set the plot's data to the calculated portion of coordinates.

■ Animation Initialization:
• Create an animation using `matplotlib.animation.FuncAnimation`.
• Call `drawfig` repeatedly for animation, with a 40-millisecond interval.

■ Show the Animation:
• Display the animated plot using `plt.show()`.

Sunday, March 24, 2024

PMAE 6 : rounded rectangle

Python Matplotlib Animation Example 6

rounded rectangle

The provided Python code generates an animated plot of a rounded rectangle using matplotlib, initializing the figure and axes and defining parameters such as dimensions and curvature. Through trigonometric computations, the getdata function determines coordinates along the rectangle's outline, accounting for the specified curvature. The update function dynamically modifies the plot during animation, adjusting data points based on the current angle, while the draw function regulates animation timing. Utilizing FuncAnimation, the code orchestrates continuous plot updates, exemplifying matplotlib's capabilities and mathematical techniques for geometric manipulation in Python. This illustrative example showcases the transformation of a rounded rectangle over time, providing insights into graphical representation and animation methodologies.



This Python code animates a rotating, filled rounded rectangle using Matplotlib's libraries. It defines functions to generate the shape's data based on a radius value. The getdata function calculates corner points using trigonometric functions and adjusts them for smooth curvature. An animation loop continuously updates the visible portion of the rectangle. It receives a time-dependent angle, calculates the visible data points, and creates the illusion of rotation. This showcases how to create and animate a visually appealing rounded rectangle.

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, 1])
ax.set_ylim([-1, 1])
ax.axis('off')

thmin = 0
thmax = pi
nth = 100
dth = pi/(nth-1)

rmin = 0.5
rmax = 1.0
nr = 3
dr = (rmax-rmin)/(nr)

def getdata(rr):
if rr < 0.0: rr = 0.0
if rr > 1.0: rr = 1.0
nth = int(300/4)*4
dth = 2*pi/(nth)
sth = 2*pi/4
xmax = cos(sth/2)
ymax = sin(sth/2)
xsmall0 = xmax - xmax*rr
ysmall0 = ymax - ymax*rr
rsmall = xmax*rr
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
if abs(y1) > ysmall0:
if y1 == 0: sign = 1.0
else: sign = abs(y1)/(y1)
thsmall = (rsmall-(ymax-abs(y1)))/rsmall*pi/4
xsmall = cos(thsmall*sign)*rsmall
ysmall = sin(thsmall*sign)*rsmall
x1 = xsmall + xsmall0
y1 = ysmall + ysmall0*sign
x2 = x1*cos(rth) + y1*sin(rth)
y2 = -x1*sin(rth) + y1*cos(rth)
xs.append(x2)
ys.append(y2)
xs.append(xs[0])
ys.append(ys[0])
return xs, ys

xs, ys = getdata(0.5)

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

def update(theta):
ith = int(theta/(2*pi/(len(xs)-1)))
pl.set_data(xs[0:ith+1], ys[0:ith+1])

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

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

plt.show()


■  Setting Up the Environment:
• Imports libraries for plotting (matplotlib) and animation.
• Creates a figure with a white background and an axis without labels or ticks.
• Defines parameters for angles and radii used in the animation.

■ Calculating Rounded Rectangle Points:
• The `getdata` function takes a radius value (`rr`) as input.
• It calculates trigonometric values based on a reference angle (`sth`).
• It iterates through a range of angles (`nth`) to define points along the rounded rectangle's edge.
• For points falling outside the rectangle due to curvature, it adjusts them using additional calculations to maintain a smooth shape.
• Finally, it returns lists containing the x and y coordinates of all the points for the rounded rectangle.

■ Creating the Initial Plot and Animation Functions:
• The code retrieves points for a medium radius and creates the initial plot of the rounded rectangle using `ax.plot`.
• The `update` function takes an angle (`theta`) as input. It calculates the number of points visible based on the rotation and updates the line plot data accordingly.
• The `draw` function is called repeatedly during the animation. It calculates a time-dependent angle, calls `update` to adjust the visible portion, and creates the illusion of rotation.

■ Running the Animation:
• `FuncAnimation` from matplotlib's animation library is used to initiate the animation process. It calls the `draw` function at set intervals (40 milliseconds in this case).
• Finally, `plt.show()` displays the animation on the screen.

Sunday, March 10, 2024

PMAE 5 : curved regular polygon

Python Matplotlib Animation Example 5

curved regular polygon

The provided Python code generates an animated plot of a curved regular polygon using the Matplotlib library. The polygon is dynamically drawn with a specified number of sides (in this case, 4), resulting in a visually appealing animation. The getdata function computes the coordinates of the polygon vertices based on the number of sides, utilizing trigonometric functions like cosine and sine. The update function progressively updates the plot during the animation, while the draw function, invoked by the animation framework, calculates the current angle of rotation for the polygon based on time, creating the illusion of continuous motion. The animation interval is set to 40 milliseconds, controlling the speed of the rotation and showcasing a smoothly rotating regular polygon within the specified plot limits. The code efficiently utilizes mathematical computations and animation functionalities from Matplotlib to generate an engaging visualization of a curved regular polygon. It's a concise and well-structured piece of code that leverages the strengths of Matplotlib for dynamic graphics generation.



This Python code animates a curved regular polygon. The getdata function calculates the coordinates for a curved shape by rotating smaller line segments. The animation function continuously reveals more segments as time progresses, creating the illusion of a curved polygon rotating and unfolding. Libraries like matplotlib handle plotting and animation. In essence, the code dynamically generates and animates a curved regular polygon with continuous motion. This animation hinges on a clever interplay of trigonometric functions, coordinate transformations, and Matplotlib's animation capabilities.

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
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(pi-sth/2+(theta-rth)) + cos(sth/2)*2
y1 = sin(pi-sth/2+(theta-rth))
x2 = x1*cos(rth) + y1*sin(rth)
y2 = -x1*sin(rth) + y1*cos(rth)
xs.append(x2)
ys.append(y2)
xs.append(xs[0])
ys.append(xs[0])
return xs, ys

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

xs, ys = getdata(4)

def update(theta):
ith = int(theta/(2*pi/(len(xs)-1)))
pl.set_data(xs[0:ith], ys[0:ith])

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

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

plt.show()

■  Imports:
• Brings in `time`, `matplotlib.pyplot`, `matplotlib.animation`, and `math` for time-related functions, plotting, animation, and mathematical calculations.

■ Figure and Axes Setup:
• Creates a figure for the animation with a white background.
• Sets up axes with specified limits and turns off axis labels.

■ `getdata` Function:
• Takes the number of sides (`n`) as input.
• Calculates coordinates for a curved n-sided polygon using trigonometric functions.
• Returns lists of x- and y-coordinates representing the polygon's points.

■ Plotting Elements:
• Creates an empty plot with blue color for future updates.
• Calls `getdata(4)` to generate coordinates for a 4-sided polygon.

■ Animation Functions:
• `update(theta)`: Takes an angle `theta`, calculates which portion of the polygon to display based on `theta`, and updates the plot accordingly.
• `draw(i)`: Calculates a time-dependent angle `theta`, calls `update(theta)`, and handles animation frame updates.

■ Animation Creation:
• Uses `matplotlib.animation.FuncAnimation` to create a continuous animation based on the `draw` function.

■ Display:
• `plt.show()`: Shows the animated plot.

Monday, February 26, 2024

PMAE 4 : regular polygons resembling a Ferris wheel

Python Matplotlib Animation Example 4

regular polygons resembling a Ferris wheel

This Python code utilizes the Matplotlib library to generate an animated Ferris wheel-like visualization featuring rotating regular polygons. The animation continues indefinitely, showcasing polygons with varying numbers of sides rotating around a central point. The update function dynamically adjusts the positions of the polygons based on a rotating angle, creating an engaging and visually intriguing effect. The rotation speed is controlled by the P parameter in the draw function, and each frame is updated at a 40-millisecond interval. Users can customize parameters such as the number of polygon sides, colors, and animation speed to achieve different visual effects. Overall, this code delivers a captivating and customizable representation of regular polygons in continuous rotation, resembling a Ferris wheel.



This Python code visualizes a rotating Ferris wheel with attached regular polygons. It combines mathematical functions, animation libraries, and visualization tools to create a visually appealing and informative animation of a rotating Ferris wheel with various polygons attached. The code effectively simulates the rotation of different sized polygons, showcasing animation capabilities in Python.

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.3, 1.3])
ax.set_ylim([-1.5, 1.1])
ax.axis('off')

def getdata(n):
nth = 361
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

def getinit(n):
dth = 2*pi/8
theta = dth*(n-3)
x0 = cos(theta)
y0 = sin(theta)
return x0, y0

def getposdata(n):
x, y = getdata(n)
sth = 2*pi/n
x0, y0 = getinit(n)
xs, ys = [], []
for i in range(len(x)):
x3 = x[i]*cos(pi/2-sth/2) - y[i]*sin(pi/2-sth/2)
y3 = x[i]*sin(pi/2-sth/2) + y[i]*cos(pi/2-sth/2)
x4 = x3*0.2+x0
y4 = (y3-1)*0.2+y0
xs.append(x4)
ys.append(y4)
return xs, ys

def getwheel():
nth = 25
dth = 2*pi/(nth-1)
xs, ys = [], []
for ith in range(nth):
theta = ith*dth
x1 = cos(theta)
y1 = sin(theta)
xs.append(x1)
ys.append(y1)
if ith%3 == 0:
nth2 = 13
dth2 = 2*pi/(nth2-1)
for ith2 in range(nth2):
theta2 = ith2*dth2
x2 = cos(theta2)*0.05 + x1
y2 = sin(theta2)*0.05 + y1
xs.append(x2)
ys.append(y2)
xs.append(x1)
ys.append(y1)
return xs, ys

xs1, ys1 = getwheel()
xs2, ys2 = getposdata(3)
xs3, ys3 = getposdata(4)
xs4, ys4 = getposdata(5)
xs5, ys5 = getposdata(6)
xs6, ys6 = getposdata(7)
xs7, ys7 = getposdata(8)
xs8, ys8 = getposdata(9)
xs9, ys9 = getposdata(10)

pl1 = ax.plot(xs1, ys1, color="#000000", lw=2.5, zorder=0)[0]
pl2 = ax.plot(xs2, ys2, color="#0000FF", lw=2.5, zorder=1)[0]
pl3 = ax.plot(xs3, ys3, color="#0000FF", lw=2.5, zorder=1)[0]
pl4 = ax.plot(xs4, ys4, color="#0000FF", lw=2.5, zorder=1)[0]
pl5 = ax.plot(xs5, ys5, color="#0000FF", lw=2.5, zorder=1)[0]
pl6 = ax.plot(xs6, ys6, color="#0000FF", lw=2.5, zorder=1)[0]
pl7 = ax.plot(xs7, ys7, color="#0000FF", lw=2.5, zorder=1)[0]
pl8 = ax.plot(xs8, ys8, color="#0000FF", lw=2.5, zorder=1)[0]
pl9 = ax.plot(xs9, ys9, color="#0000FF", lw=2.5, zorder=1)[0]

def rotate(x, y, theta):
xp, yp = [], []
for i in range(len(x)):
x1 = x[i]*cos(theta) - y[i]*sin(theta)
y1 = x[i]*sin(theta) + y[i]*cos(theta)
xp.append(x1)
yp.append(y1)
return xp, yp

def shift(x, y, n, theta):
x0, y0 = getinit(n)
x0p = x0*cos(theta) - y0*sin(theta)
y0p = x0*sin(theta) + y0*cos(theta)
xp, yp = [], []
for i in range(len(x)):
x1 = x[i] + (x0p-x0)
y1 = y[i] + (y0p-y0)
xp.append(x1)
yp.append(y1)
return xp, yp


def update(theta):
xp, yp = rotate(xs1, ys1, theta); pl1.set_data(xp, yp)
xp, yp = shift(xs2, ys2, 3, theta); pl2.set_data(xp, yp)
xp, yp = shift(xs3, ys3, 4, theta); pl3.set_data(xp, yp)
xp, yp = shift(xs4, ys4, 5, theta); pl4.set_data(xp, yp)
xp, yp = shift(xs5, ys5, 6, theta); pl5.set_data(xp, yp)
xp, yp = shift(xs6, ys6, 7, theta); pl6.set_data(xp, yp)
xp, yp = shift(xs7, ys7, 8, theta); pl7.set_data(xp, yp)
xp, yp = shift(xs8, ys8, 9, theta); pl8.set_data(xp, yp)
xp, yp = shift(xs9, ys9, 10, theta); pl9.set_data(xp, yp)

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

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

plt.show()

This code creates an animation of regular polygons resembling a Ferris wheel. Here's a breakdown:

■ Imports:
• Libraries for plotting (`matplotlib.pyplot`) and animation (`matplotlib.animation`) are imported.
• Mathematical functions (cosine, sine, tangent, and pi) are imported from the `math` library.

■ Figure and Axes Setup:
• A figure is created with a size of 3x3 inches and a white background.
• Axes are added to the figure, and their limits and visibility are set for a clean appearance.

■ Data Generation Functions:
• `getdata(n)`: Generates a regular polygon with `n` sides. It calculates the x and y coordinates of each vertex based on the angle and radius.
• `getinit(n)`: Provides the initial position (x and y coordinates) for a polygon with `n` sides.
• `getposdata(n)`: Creates a smaller, shifted, and rotated version of the polygon based on the original data and initial position.
• `getwheel()`: Defines the large base polygon with smaller polygons attached at specific intervals, resembling the Ferris wheel structure.

■ Variable Initialization:
• Nine sets of data (x and y coordinates) are generated for each polygon using the functions above.
• Each set is assigned to a corresponding variable (`xs1`, `ys1`, etc.).

■ Plotting:
• Nine lines representing the polygons are plotted using `ax.plot` with different colors and line widths.

■ Rotation and Shifting Functions:
• `rotate(x, y, theta)`: Takes x and y coordinates and a rotation angle. It returns the rotated coordinates.
• `shift(x, y, n, theta)`: Takes x and y coordinates, the number of sides (`n`), and a rotation angle. It returns the shifted and rotated coordinates based on the initial position.

■ Animation Update Function:
• `update(theta)`: Takes a rotation angle (`theta`) as input.
• It updates the data (x and y coordinates) of each plotted line using the `shift` and `rotate` functions with appropriate arguments.
• This essentially rotates and shifts the individual polygons based on their defined parameters.

■ Animation Drawing Function:
• `draw(i)`: This function is called repeatedly during the animation loop.
• It calculates the rotation angle based on the current time and a desired animation period (`P`).
• It calls the `update` function to update the data for each polygon based on the calculated angle.

■ Animation Creation:
• `ani`: Creates an animation object using `FuncAnimation`.
• It specifies the figure (`fig`), the drawing function (`draw`), and the interval (40 milliseconds) between frame updates.

■ Display:
• `plt.show()`: Displays the generated animation.

Overall, this code effectively utilizes mathematical functions, data generation, animation techniques, and plotting libraries to create a visually appealing animation of regular polygons rotating like a Ferris wheel.



Sunday, February 25, 2024

PMAE 3 : grid plot of regular polygons

Python Matplotlib Animation Example 3

grid plot of regular polygons

The Python code utilizes the Matplotlib library to generate an animated grid plot of regular polygons. Employing trigonometric calculations, the code positions the polygons in a 4x4 grid and animates the plot, revealing diverse polygons over time. Each subplot features a regular polygon with an increasing number of sides, and the animation updates continuously, creating a dynamic and visually appealing pattern. The code achieves this by defining a function getdata to compute the vertices of regular polygons and utilizes the animation module of Matplotlib to update the plot at regular intervals. In summary, the code leverages Matplotlib to create an animated grid plot, showcasing a captivating sequence of regular polygons evolving in a visually compelling manner.



The code creates an animated grid of regular polygons, where each polygon has a different number of sides (from 3 to 18). The polygons are positioned in a 4x4 grid and smoothly transition between different shapes as the animation progresses. It utilizes trigonometry for accurate polygon generation and animation techniques for dynamic visualization, resulting in a visually appealing grid of evolving polygon shapes.

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([0, 1])
ax.set_ylim([0, 1])
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

nbin = 16
pl = [0 for i in range(nbin)]

def update(i):
if i > 0 and i%nbin == 0:
for j in range(nbin):
pl[j].set_data([], [])
ibin = i%nbin
ix = ibin%4
iy = ibin/4
n = ibin + 3
x0 = ix*1.0/4.0+1.0/8.0
y0 = (4-iy)*1.0/4.0-1.0/8.0
xs, ys = getdata(n)
for j in range(len(xs)):
xs[j] = xs[j]*0.1 + x0
ys[j] = ys[j]*0.1 + y0
pl[ibin] = ax.plot(xs, ys, color="#0000FF")[0]

def draw(i):
update(i)

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

plt.show()


This code creates an animation of a grid filled with regular polygons with varying numbers of sides.

■ Setting up the environment:
• Imports necessary libraries for plotting and animation (`matplotlib.pyplot`, `matplotlib.animation`, `math`).
   • Creates a figure and an axes object for plotting.
• Sets the axes limits and removes unnecessary labels.

■ Generating polygon data:
• Defines the `getdata` function:
• Takes the number of sides (`n`) as input.
• Calculates the number of points needed for a smooth curve (`nth`).
• Iterates through each point and calculates its coordinates using trigonometric functions.
• Returns lists of x and y coordinates for the polygon.

■ Animation loop:
• Defines `nbin` as the total number of plots in the grid (16 in this case).
• Creates a list `pl` to store plot objects.
• Defines the `update` function:
• Clears previous plots at regular intervals.
• Calculates the index (`ibin`) for the current plot in the animation sequence.
• Determines the number of sides for the current polygon based on `ibin`.
• Calculates the position of the polygon within the grid.
• Generates polygon coordinates using `getdata`.
• Updates the corresponding plot in the list with the new polygon.
• Defines the `draw` function:
• Calls `update` to update the plot for each frame.

■ Running the animation:
• Creates an animation object using `FuncAnimation`.
• Sets the figure, update function, and frame interval (200 milliseconds).
• Displays the animation using `plt.show()`.

Overall, this code effectively utilizes trigonometry and animation techniques to create a visually appealing visualization of regular polygons with varying side counts.

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.

PMAE 1 : n-sided regular polygon

Python Matplotlib Animation Example 1

n-sided regular polygon

This Python code employs the Matplotlib library to produce an animated plot illustrating the construction and rotation of an n-sided regular polygon. The polygon evolves over time, gradually connecting points on a circle to create the desired shape. The animation is orchestrated through the draw function, which calculates the angle based on the elapsed time and updates the plot accordingly. By adjusting the argument in the getdata function, users can modify the number of sides, allowing for customization such as generating a hexagon by using getdata(6). The code provides a versatile and visually engaging tool for exploring different polygon shapes and animation speeds, making it a valuable resource for interactive visualization and experimentation.


This code animates an n-sided regular polygon rotating smoothly at a constant speed. You can adjust the number of sides (n) and animation speed (P) to explore different shapes and behaviors. The code uses efficient trigonometric calculations for point generation. Overall, it effectively generates and animates an n-sided polygon, providing a visualization of its rotation in a circle.

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 = 361
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(8)

def update(theta):
ith = int(theta/(2*pi/(len(xs)-1)))
pl.set_data(xs[0:ith], ys[0:ith])

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

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

plt.show()

Summary:
This Python code generates and animates an n-sided regular polygon, where `n` is specified as an input value. It employs mathematical calculations, matplotlib, and animation functionalities to achieve this.

Code Breakdown:

■ Imports:
• `time`: Used for timing the animation.
• `matplotlib.pyplot as plt`: Provides plotting functions.
• `matplotlib.animation as animation`: Used for creating the animation.
• `math`: Provides mathematical functions like `cos`, `sin`, `tan`, and `pi`.

■ Figure and Axis Setup:
• A figure with a fixed size of 300x300 and white background is created.
• An axis is added within the figure, setting the x and y limits to [-1.2, 1.2] and turning off the axis labels and ticks.

■ `getdata` Function:
• Takes `n` (the number of sides) as input.
• Initializes `nth` to 361 (number of points to create) and `dth` to the angular distance between points based on `n`.
• Calculates the step angle `sth` between vertices of the polygon.
• Creates empty lists `xs` and `ys` to store x and y coordinates of points.
• Iterates `nth` times to generate points:
• Calculates the current angle `theta`.
• Rounds `theta` down to the nearest multiple of `sth` using `int(theta/sth)*sth`.
• Calculates intermediate values `x1` and `y1` based on `sth` and `theta`.
• Rotates the point by `rth` using `x2` and `y2`.
• Appends the point's coordinates to `xs` and `ys`.
• Returns `xs` and `ys`.

■ Line Plot Setup:
• Creates an empty line plot with a blue color in the axis.

■ Data Generation:
• Calls `getdata(8)` to get data for an 8-sided polygon and stores the points in `xs` and `ys`.

■ `update` Function:
• Takes a `theta` value as input.
• Calculates the index `ith` of the point corresponding to `theta` based on the angular distance between points and the number of points.
• Updates the line plot data using `pl.set_data(xs[0:ith], ys[0:ith])`, showing only points up to `ith`.

■ `draw` Function:
• Takes a frame number `i` as input (not used in this code).
• Sets a period `P` for the animation (5.0 seconds).
• Calculates the current time `t`.
• Calculates the animation angle `theta` based on `t`, `P`, and a 2*pi factor to ensure a full rotation within `P`.
• Calls `update(theta)` to update the line plot data.

■ Animation Creation:
• Creates an animation using `animation.FuncAnimation`.
• Sets the animation function to `draw`.
• Sets the update interval to 40 milliseconds.

■ Displaying the Animation:
• Calls `plt.show()` to display the animation.

Key Points:

○ The animation creates a rotating polygon with `n` sides.
○ The animation speed is controlled by the `P` value in the `draw` function.
○ The code can be modified to change the number of sides, animation speed, and other parameters.