Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating Rectangles around point with matplotlib

I wanted to rotate Rectangles with matplotlib, but the normal patch always rotates around the lower left corner of the Rectangle. Is there a way to describe more general transformations? For Example I want to rotate about the mid point on the shorter side of the rectangle, so that the result looks like the motion of a clock hand.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

height = 0.1
width = 1
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.set_xlim([-width * 1.2, width * 1.2])
ax.set_ylim([-width * 1.2, width * 1.2])

ax.plot(0, 0,  color='r', marker='o', markersize=10)
for deg in range(0, 360, 45):
    rec = Rectangle((0, 0), width=width, height=height, 
                    angle=deg, color=str(deg / 360), alpha=0.9)
    ax.add_patch(rec)

Original

like image 563
scleronomic Avatar asked Jan 25 '26 13:01

scleronomic


1 Answers

Same as the other answer, just without subclassing and using private attributes.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D

height = 0.1
width = 1
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.set_xlim([-width * 1.2, width * 1.2])
ax.set_ylim([-width * 1.2, width * 1.2])
ax.plot(0, 0,  color='r', marker='o', markersize=10)
point_of_rotation = np.array([0, height/2])          # A
# point_of_rotation = np.array([width/2, height/2])  # B
# point_of_rotation = np.array([width/3, height/2])  # C
# point_of_rotation = np.array([width/3, 2*height])  # D

for deg in range(0, 360, 45):
    rec = plt.Rectangle(-point_of_rotation, width=width, height=height, 
                        color=str(deg / 360), alpha=0.9,
                        transform=Affine2D().rotate_deg_around(*(0,0), deg)+ax.transData)
    ax.add_patch(rec)
plt.show()

enter image description here

like image 94
ImportanceOfBeingErnest Avatar answered Jan 28 '26 10:01

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!