- Original coordinates: (x, y)
- Rotated coordinates: (x', y')
- Pivot point: (cx, cy)
- Rotation angle: θ (in radians)
x' = cos(θ) * (x - cx) - sin(θ) * (y - cy) + cx
y' = sin(θ) * (x - cx) + cos(θ) * (y - cy) + cy
import math
import matplotlib.pyplot as plt
def rotate_point(x, y, cx, cy, angle):
"""Rotate point (x, y) around pivot (cx, cy) by a given angle"""
radians = math.radians(angle)
cos_theta = math.cos(radians)
sin_theta = math.sin(radians)
x_new = cos_theta * (x - cx) - sin_theta * (y - cy) + cx
y_new = sin_theta * (x - cx) + cos_theta * (y - cy) + cy
return x_new, y_new
def rotate_rectangle(rect, cx, cy, angle):
"""Rotate all points of a rectangle"""
return [rotate_point(x, y, cx, cy, angle) for x, y in rect]
# Initial rectangle coordinates (starting from top-left, clockwise)
rectangle = [(1, 3), (4, 3), (4, 1), (1, 1)]
center = (2.5, 2) # Pivot point
angle = 45 # Rotation angle (degrees)
# Rotate the rectangle
rotated_rectangle = rotate_rectangle(rectangle, *center, angle)
# Visualization
def plot_rectangle(rect, label, color):
x, y = zip(*rect + [rect[0]]) # Close the rectangle by adding the first point again
plt.plot(x, y, marker='o', label=label, color=color)
plt.figure()
plot_rectangle(rectangle, 'Original', 'blue')
plot_rectangle(rotated_rectangle, 'Rotated', 'red')
plt.scatter(*center, color='green', label='Center', zorder=5)
plt.legend()
plt.gca().set_aspect('equal', adjustable='box')
plt.grid(True)
plt.title(f"Rectangle Rotation (Angle: {angle}°)")
plt.show()
rotate_point
function: Rotates a given point around a specified pivot point.rotate_rectangle
function: Rotates all four corners of a rectangle.- Matplotlib Visualization: Plots the original rectangle (blue) and the rotated rectangle (red).
- Pivot Point: Shown as a green dot. The rotation angle is measured counterclockwise starting from 0 degrees.
- To rotate counterclockwise, use a positive angle.
- To rotate clockwise, use a negative angle or modify the
rotate_point
function to handle negative angles directly.
The rotated rectangle, rotated by 45 degrees, is visualized alongside the original rectangle to demonstrate the transformation.